mcp-use 1.5.1-canary.2 → 1.5.1-canary.4

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.
@@ -592,6 +592,22 @@ var McpServer = class {
592
592
  }
593
593
  return `http://${this.serverHost}:${this.serverPort}`;
594
594
  }
595
+ /**
596
+ * Gets additional CSP URLs from environment variable
597
+ * Supports comma-separated list or single URL
598
+ * @returns Array of URLs to add to CSP resource_domains
599
+ */
600
+ getCSPUrls() {
601
+ console.log(globalThis.Deno.env.get("CSP_URLS"));
602
+ const cspUrlsEnv = getEnv2("CSP_URLS");
603
+ if (!cspUrlsEnv) {
604
+ console.log("[CSP] No CSP_URLS environment variable found");
605
+ return [];
606
+ }
607
+ const urls = cspUrlsEnv.split(",").map((url) => url.trim()).filter((url) => url.length > 0);
608
+ console.log("[CSP] Parsed CSP URLs:", urls);
609
+ return urls;
610
+ }
595
611
  /**
596
612
  * Define a static resource that can be accessed by clients
597
613
  *
@@ -763,11 +779,6 @@ var McpServer = class {
763
779
  */
764
780
  tool(toolDefinition) {
765
781
  const inputSchema = this.createParamsSchema(toolDefinition.inputs || []);
766
- const context = {
767
- sample: /* @__PURE__ */ __name(async (params, options) => {
768
- return await this.createMessage(params, options);
769
- }, "sample")
770
- };
771
782
  this.server.registerTool(
772
783
  toolDefinition.name,
773
784
  {
@@ -777,7 +788,98 @@ var McpServer = class {
777
788
  annotations: toolDefinition.annotations,
778
789
  _meta: toolDefinition._meta
779
790
  },
780
- async (params) => {
791
+ async (params, extra) => {
792
+ const progressToken = extra?._meta?.progressToken;
793
+ const context = {
794
+ /**
795
+ * Request sampling from the client's LLM with automatic progress notifications.
796
+ *
797
+ * Progress notifications are sent every 5 seconds (configurable) while waiting
798
+ * for the sampling response. This prevents client-side timeouts when
799
+ * resetTimeoutOnProgress is enabled.
800
+ *
801
+ * @param params - Sampling parameters (messages, model preferences, etc.)
802
+ * @param options - Optional configuration
803
+ * @param options.timeout - Timeout in milliseconds (default: no timeout / Infinity)
804
+ * @param options.progressIntervalMs - Interval between progress notifications (default: 5000ms)
805
+ * @param options.onProgress - Optional callback called each time progress is reported
806
+ * @returns The sampling result from the client's LLM
807
+ */
808
+ sample: /* @__PURE__ */ __name(async (sampleParams, options) => {
809
+ const {
810
+ timeout,
811
+ progressIntervalMs = 5e3,
812
+ onProgress
813
+ } = options ?? {};
814
+ let progressCount = 0;
815
+ let completed = false;
816
+ let progressInterval = null;
817
+ if (progressToken && extra?.sendNotification) {
818
+ progressInterval = setInterval(async () => {
819
+ if (completed) return;
820
+ progressCount++;
821
+ const progressData = {
822
+ progress: progressCount,
823
+ total: void 0,
824
+ message: `Waiting for LLM response... (${progressCount * Math.round(progressIntervalMs / 1e3)}s elapsed)`
825
+ };
826
+ if (onProgress) {
827
+ try {
828
+ onProgress(progressData);
829
+ } catch {
830
+ }
831
+ }
832
+ try {
833
+ await extra.sendNotification({
834
+ method: "notifications/progress",
835
+ params: {
836
+ progressToken,
837
+ progress: progressData.progress,
838
+ total: progressData.total,
839
+ message: progressData.message
840
+ }
841
+ });
842
+ } catch {
843
+ }
844
+ }, progressIntervalMs);
845
+ }
846
+ try {
847
+ const samplePromise = this.createMessage(sampleParams);
848
+ if (timeout && timeout !== Infinity) {
849
+ const timeoutPromise = new Promise((_, reject) => {
850
+ setTimeout(
851
+ () => reject(
852
+ new Error(`Sampling timed out after ${timeout}ms`)
853
+ ),
854
+ timeout
855
+ );
856
+ });
857
+ return await Promise.race([samplePromise, timeoutPromise]);
858
+ }
859
+ return await samplePromise;
860
+ } finally {
861
+ completed = true;
862
+ if (progressInterval) {
863
+ clearInterval(progressInterval);
864
+ }
865
+ }
866
+ }, "sample"),
867
+ /**
868
+ * Send a progress notification to the client.
869
+ * Only works if the client requested progress updates for this tool call.
870
+ */
871
+ reportProgress: progressToken && extra?.sendNotification ? async (progress, total, message) => {
872
+ await extra.sendNotification({
873
+ method: "notifications/progress",
874
+ params: {
875
+ progressToken,
876
+ progress,
877
+ total,
878
+ message
879
+ }
880
+ });
881
+ } : void 0
882
+ };
781
883
  if (toolDefinition.cb.length >= 2) {
782
884
  return await toolDefinition.cb(params, context);
783
885
  }
@@ -1602,6 +1704,7 @@ if (container && Component) {
1602
1704
  error
1603
1705
  );
1604
1706
  }
1707
+ const mcp_connect_domain = this.getServerBaseUrl() ? new URL(this.getServerBaseUrl() || "").origin : null;
1605
1708
  this.uiResource({
1606
1709
  name: widget.name,
1607
1710
  title: metadata.title || widget.name,
@@ -1631,14 +1734,16 @@ if (container && Component) {
1631
1734
  "openai/widgetCSP": {
1632
1735
  connect_domains: [
1633
1736
  // always also add the base url of the server
1634
- ...this.getServerBaseUrl() ? [this.getServerBaseUrl()] : [],
1737
+ ...mcp_connect_domain ? [mcp_connect_domain] : [],
1635
1738
  ...metadata.appsSdkMetadata?.["openai/widgetCSP"]?.connect_domains || []
1636
1739
  ],
1637
1740
  resource_domains: [
1638
1741
  "https://*.oaistatic.com",
1639
1742
  "https://*.oaiusercontent.com",
1640
1743
  // always also add the base url of the server
1641
- ...this.getServerBaseUrl() ? [this.getServerBaseUrl()] : [],
1744
+ ...mcp_connect_domain ? [mcp_connect_domain] : [],
1745
+ // add additional CSP URLs from environment variable
1746
+ ...this.getCSPUrls(),
1642
1747
  ...metadata.appsSdkMetadata?.["openai/widgetCSP"]?.resource_domains || []
1643
1748
  ]
1644
1749
  }
@@ -1816,6 +1921,8 @@ if (container && Component) {
1816
1921
  "https://*.openai.com",
1817
1922
  // always also add the base url of the server
1818
1923
  ...this.getServerBaseUrl() ? [this.getServerBaseUrl()] : [],
1924
+ // add additional CSP URLs from environment variable
1925
+ ...this.getCSPUrls(),
1819
1926
  ...metadata.appsSdkMetadata?.["openai/widgetCSP"]?.resource_domains || []
1820
1927
  ]
1821
1928
  }
@@ -1868,14 +1975,7 @@ if (container && Component) {
1868
1975
  if (this.mcpMounted) return;
1869
1976
  const { StreamableHTTPServerTransport } = await import("@modelcontextprotocol/sdk/server/streamableHttp.js");
1870
1977
  const idleTimeoutMs = this.config.sessionIdleTimeoutMs ?? 3e5;
1871
- const createNewTransport = /* @__PURE__ */ __name(async (closeOldSessionId) => {
1872
- if (closeOldSessionId && this.sessions.has(closeOldSessionId)) {
1873
- try {
1874
- this.sessions.get(closeOldSessionId).transport.close();
1875
- } catch (error) {
1876
- }
1877
- this.sessions.delete(closeOldSessionId);
1878
- }
1978
+ const getTransportConfig = /* @__PURE__ */ __name(() => {
1879
1979
  const isProduction = this.isProductionMode();
1880
1980
  let allowedOrigins = this.config.allowedOrigins;
1881
1981
  let enableDnsRebindingProtection = false;
@@ -1887,6 +1987,17 @@ if (container && Component) {
1887
1987
  allowedOrigins = void 0;
1888
1988
  enableDnsRebindingProtection = false;
1889
1989
  }
1990
+ return { allowedOrigins, enableDnsRebindingProtection };
1991
+ }, "getTransportConfig");
1992
+ const createNewTransport = /* @__PURE__ */ __name(async (closeOldSessionId) => {
1993
+ if (closeOldSessionId && this.sessions.has(closeOldSessionId)) {
1994
+ try {
1995
+ this.sessions.get(closeOldSessionId).transport.close();
1996
+ } catch (error) {
1997
+ }
1998
+ this.sessions.delete(closeOldSessionId);
1999
+ }
2000
+ const { allowedOrigins, enableDnsRebindingProtection } = getTransportConfig();
1890
2001
  const transport = new StreamableHTTPServerTransport({
1891
2002
  sessionIdGenerator: /* @__PURE__ */ __name(() => generateUUID(), "sessionIdGenerator"),
1892
2003
  enableJsonResponse: true,
@@ -1909,6 +2020,81 @@ if (container && Component) {
1909
2020
  await this.server.connect(transport);
1910
2021
  return transport;
1911
2022
  }, "createNewTransport");
2023
+ const createAndAutoInitializeTransport = /* @__PURE__ */ __name(async (oldSessionId) => {
2024
+ const { allowedOrigins, enableDnsRebindingProtection } = getTransportConfig();
2025
+ const transport = new StreamableHTTPServerTransport({
2026
+ sessionIdGenerator: /* @__PURE__ */ __name(() => oldSessionId, "sessionIdGenerator"),
2027
+ // Reuse old session ID!
2028
+ enableJsonResponse: true,
2029
+ allowedOrigins,
2030
+ enableDnsRebindingProtection,
2031
+ // We'll manually store the session, so don't rely on onsessioninitialized
2032
+ onsessionclosed: /* @__PURE__ */ __name((id) => {
2033
+ if (id) {
2034
+ this.sessions.delete(id);
2035
+ }
2036
+ }, "onsessionclosed")
2037
+ });
2038
+ await this.server.connect(transport);
2039
+ this.sessions.set(oldSessionId, {
2040
+ transport,
2041
+ lastAccessedAt: Date.now()
2042
+ });
2043
+ const initBody = {
2044
+ jsonrpc: "2.0",
2045
+ method: "initialize",
2046
+ params: {
2047
+ protocolVersion: "2024-11-05",
2048
+ capabilities: {},
2049
+ clientInfo: { name: "mcp-use-auto-reconnect", version: "1.0.0" }
2050
+ },
2051
+ id: "__auto_init__"
2052
+ };
2053
+ const syntheticHeaders = {
2054
+ "content-type": "application/json",
2055
+ accept: "application/json, text/event-stream"
2056
+ // SDK requires both!
2057
+ };
2058
+ const syntheticReq = {
2059
+ method: "POST",
2060
+ headers: syntheticHeaders,
2061
+ header: /* @__PURE__ */ __name((name) => syntheticHeaders[name.toLowerCase()], "header"),
2062
+ body: initBody
2063
+ };
2064
+ const syntheticRes = {
2065
+ statusCode: 200,
2066
+ setHeader: /* @__PURE__ */ __name(() => syntheticRes, "setHeader"),
2067
+ writeHead: /* @__PURE__ */ __name((code) => {
2068
+ syntheticRes.statusCode = code;
2069
+ return syntheticRes;
2070
+ }, "writeHead"),
2071
+ write: /* @__PURE__ */ __name(() => true, "write"),
2072
+ end: /* @__PURE__ */ __name(() => {
2073
+ }, "end"),
2074
+ on: /* @__PURE__ */ __name(() => syntheticRes, "on"),
2075
+ once: /* @__PURE__ */ __name(() => syntheticRes, "once"),
2076
+ removeListener: /* @__PURE__ */ __name(() => syntheticRes, "removeListener")
2077
+ };
2078
+ await new Promise((resolve) => {
2079
+ syntheticRes.end = () => {
2080
+ resolve();
2081
+ };
2082
+ transport.handleRequest(syntheticReq, syntheticRes, initBody);
2083
+ });
2084
+ if (syntheticRes.statusCode !== 200) {
2085
+ console.error(
2086
+ `[MCP] Auto-initialization failed with status ${syntheticRes.statusCode}`
2087
+ );
2088
+ this.sessions.delete(oldSessionId);
2089
+ throw new Error(
2090
+ `Auto-initialization failed: ${syntheticRes.statusCode}`
2091
+ );
2092
+ }
2093
+ console.log(
2094
+ `[MCP] Auto-initialized session ${oldSessionId} for seamless reconnection`
2095
+ );
2096
+ return transport;
2097
+ }, "createAndAutoInitializeTransport");
1912
2098
  const getOrCreateTransport = /* @__PURE__ */ __name(async (sessionId, isInit = false) => {
1913
2099
  if (isInit) {
1914
2100
  return await createNewTransport(sessionId);
@@ -1922,9 +2108,9 @@ if (container && Component) {
1922
2108
  const autoCreate = this.config.autoCreateSessionOnInvalidId ?? true;
1923
2109
  if (autoCreate) {
1924
2110
  console.warn(
1925
- `[MCP] Session ${sessionId} not found (expired or invalid), auto-creating new session for seamless reconnection`
2111
+ `[MCP] Session ${sessionId} not found (expired or invalid), auto-creating and initializing new session for seamless reconnection`
1926
2112
  );
1927
- return await createNewTransport(sessionId);
2113
+ return await createAndAutoInitializeTransport(sessionId);
1928
2114
  } else {
1929
2115
  return null;
1930
2116
  }
@@ -1,4 +1,79 @@
1
1
  import type { CreateMessageRequest, CreateMessageResult } from "@modelcontextprotocol/sdk/types.js";
2
+ /**
3
+ * Options for the sample() function in tool context.
4
+ */
5
+ export interface SampleOptions {
6
+ /**
7
+ * Timeout in milliseconds for the sampling request.
8
+ * Default: no timeout (Infinity) - waits indefinitely for the LLM response.
9
+ * Set this if you want to limit how long to wait for sampling.
10
+ */
11
+ timeout?: number;
12
+ /**
13
+ * Interval in milliseconds between progress notifications.
14
+ * Default: 5000 (5 seconds).
15
+ * Progress notifications are sent to the client to prevent timeout
16
+ * when the client has resetTimeoutOnProgress enabled.
17
+ */
18
+ progressIntervalMs?: number;
19
+ /**
20
+ * Optional callback called each time a progress notification is sent.
21
+ * Useful for logging or custom progress handling.
22
+ */
23
+ onProgress?: (progress: {
24
+ progress: number;
25
+ total?: number;
26
+ message: string;
27
+ }) => void;
28
+ }
29
+ /**
30
+ * Context object passed to tool callbacks.
31
+ * Provides access to sampling and progress reporting capabilities.
32
+ */
33
+ export interface ToolContext {
34
+ /**
35
+ * Request sampling from the client's LLM with automatic progress notifications.
36
+ *
37
+ * Progress notifications are sent every 5 seconds (configurable) while waiting
38
+ * for the sampling response. This prevents client-side timeouts when the client
39
+ * has `resetTimeoutOnProgress: true` enabled.
40
+ *
41
+ * By default, there is no timeout - the function waits indefinitely for the
42
+ * LLM response. Set `options.timeout` to limit the wait time.
43
+ *
44
+ * @param params - Sampling parameters (messages, model preferences, etc.)
45
+ * @param options - Optional configuration for timeout and progress
46
+ * @returns The sampling result from the client's LLM
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * // Basic usage - waits indefinitely with automatic progress notifications
51
+ * const result = await ctx.sample({
52
+ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
53
+ * });
54
+ *
55
+ * // With timeout and custom progress handling
56
+ * const result = await ctx.sample(
57
+ * { messages: [...] },
58
+ * {
59
+ * timeout: 120000, // 2 minute timeout
60
+ * progressIntervalMs: 3000, // Report progress every 3 seconds
61
+ * onProgress: ({ progress, message }) => console.log(message),
62
+ * }
63
+ * );
64
+ * ```
65
+ */
66
+ sample: (params: CreateMessageRequest["params"], options?: SampleOptions) => Promise<CreateMessageResult>;
67
+ /**
68
+ * Send a progress notification to the client.
69
+ * Only available if the client requested progress updates for this tool call.
70
+ *
71
+ * @param progress - Current progress value (should increase with each call)
72
+ * @param total - Total progress value if known
73
+ * @param message - Optional message describing current progress
74
+ */
75
+ reportProgress?: (progress: number, total?: number, message?: string) => Promise<void>;
76
+ }
2
77
  import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
3
78
  import { type Hono as HonoType } from "hono";
4
79
  import type { PromptDefinition, ResourceDefinition, ResourceTemplateDefinition, ServerConfig, ToolDefinition, UIResourceDefinition } from "./types/index.js";
@@ -33,6 +108,12 @@ export declare class McpServer {
33
108
  * @returns The complete base URL for the server
34
109
  */
35
110
  private getServerBaseUrl;
111
+ /**
112
+ * Gets additional CSP URLs from environment variable
113
+ * Supports comma-separated list or single URL
114
+ * @returns Array of URLs to add to CSP resource_domains
115
+ */
116
+ private getCSPUrls;
36
117
  /**
37
118
  * Define a static resource that can be accessed by clients
38
119
  *
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-server.d.ts","sourceRoot":"","sources":["../../../src/server/mcp-server.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,oBAAoB,EACpB,mBAAmB,EAEpB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8CAA8C,CAAC;AACnF,OAAO,EAAsB,KAAK,IAAI,IAAI,QAAQ,EAAa,MAAM,MAAM,CAAC;AAkB5E,OAAO,KAAK,EAEV,gBAAgB,EAChB,kBAAkB,EAClB,0BAA0B,EAC1B,YAAY,EACZ,cAAc,EAEd,oBAAoB,EAErB,MAAM,kBAAkB,CAAC;AA4G1B,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAoB;IAClC,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,GAAG,CAAW;IACtB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,UAAU,CAAC,CAAS;IAC5B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,aAAa,CAAC,CAAS;IAC/B,OAAO,CAAC,eAAe,CAAgB;IACvC,OAAO,CAAC,iBAAiB,CAAgB;IACzC,OAAO,CAAC,mBAAmB,CAAgB;IAC3C,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,QAAQ,CAMZ;IACJ,OAAO,CAAC,mBAAmB,CAAC,CAAiB;IAE7C;;;;;;;;;OASG;gBACS,MAAM,EAAE,YAAY;IAwGhC;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAcxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;O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O,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;CACpD,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,OAAO,CAAC,YAAY,CAAM,GACjC,iBAAiB,CAWnB"}
@@ -1,7 +1,12 @@
1
1
  import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  import type { InputDefinition } from "./common.js";
3
3
  import type { ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
4
- export type ToolCallback = (params: Record<string, any>) => Promise<CallToolResult>;
4
+ import type { ToolContext } from "../mcp-server.js";
5
+ /**
6
+ * Callback function for tool execution.
7
+ * Can optionally receive a ToolContext as the second parameter for sampling support.
8
+ */
9
+ export type ToolCallback = (params: Record<string, any>, ctx?: ToolContext) => Promise<CallToolResult>;
5
10
  export interface ToolDefinition {
6
11
  /** Unique identifier for the tool */
7
12
  name: string;
@@ -11,7 +16,26 @@ export interface ToolDefinition {
11
16
  description?: string;
12
17
  /** Input parameter definitions */
13
18
  inputs?: InputDefinition[];
14
- /** Async callback function that executes the tool */
19
+ /**
20
+ * Async callback function that executes the tool.
21
+ * Receives tool parameters and optionally a ToolContext for sampling support.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // Simple tool without sampling
26
+ * cb: async ({ name }) => ({
27
+ * content: [{ type: 'text', text: `Hello, ${name}!` }]
28
+ * })
29
+ *
30
+ * // Tool with sampling support
31
+ * cb: async ({ text }, ctx) => {
32
+ * const result = await ctx.sample({
33
+ * messages: [{ role: 'user', content: { type: 'text', text } }]
34
+ * });
35
+ * return { content: result.content };
36
+ * }
37
+ * ```
38
+ */
15
39
  cb: ToolCallback;
16
40
  /** Tool annotations */
17
41
  annotations?: ToolAnnotations;
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../../src/server/types/tool.ts"],"names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,EAAE,MAAM,CAAC;IACb,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wCAAwC;IACxC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kCAAkC;IAClC,MAAM,CAAC,EAAE,eAAe,EAAE,CAAC;IAC3B;;;;;;;;;;;;;;;;;;;OAmBG;IACH,EAAE,EAAE,YAAY,CAAC;IACjB,uBAAuB;IACvB,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,4BAA4B;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "1.5.1-canary.2",
4
+ "version": "1.5.1-canary.4",
5
5
  "description": "Opinionated MCP Framework for TypeScript (@modelcontextprotocol/sdk compatible) - Build MCP Agents and Clients + MCP Servers with support for MCP-UI.",
6
6
  "author": "mcp-use, Inc.",
7
7
  "license": "MIT",
@@ -115,8 +115,8 @@
115
115
  "ws": "^8.18.2",
116
116
  "zod": "^3.25.48",
117
117
  "zod-to-json-schema": "^3.24.6",
118
- "@mcp-use/cli": "2.3.1-canary.2",
119
- "@mcp-use/inspector": "0.7.1-canary.2"
118
+ "@mcp-use/cli": "2.3.1-canary.4",
119
+ "@mcp-use/inspector": "0.7.1-canary.4"
120
120
  },
121
121
  "optionalDependencies": {
122
122
  "@tailwindcss/vite": "^4.1.15",