mcp-use 0.1.3 → 0.1.5

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 CHANGED
@@ -188,6 +188,13 @@ const agent = new MCPAgent({
188
188
 
189
189
  <table>
190
190
  <tr>
191
+ <td align="center" style="word-wrap: break-word; width: 150.0; height: 150.0">
192
+ <a href=https://github.com/pietrozullo>
193
+ <img src=https://avatars.githubusercontent.com/u/62951181?v=4 width="100;" style="border-radius:50%;align-items:center;justify-content:center;overflow:hidden;padding-top:10px" alt=Pietro Zullo/>
194
+ <br />
195
+ <sub style="font-size:14px"><b>Pietro Zullo</b></sub>
196
+ </a>
197
+ </td>
191
198
  <td align="center" style="word-wrap: break-word; width: 150.0; height: 150.0">
192
199
  <a href=https://github.com/zandko>
193
200
  <img src=https://avatars.githubusercontent.com/u/37948383?v=4 width="100;" style="border-radius:50%;align-items:center;justify-content:center;overflow:hidden;padding-top:10px" alt=Zane/>
@@ -196,10 +203,10 @@ const agent = new MCPAgent({
196
203
  </a>
197
204
  </td>
198
205
  <td align="center" style="word-wrap: break-word; width: 150.0; height: 150.0">
199
- <a href=https://github.com/pietrozullo>
200
- <img src=https://avatars.githubusercontent.com/u/62951181?v=4 width="100;" style="border-radius:50%;align-items:center;justify-content:center;overflow:hidden;padding-top:10px" alt=Pietro Zullo/>
206
+ <a href=https://github.com/Pederzh>
207
+ <img src=https://avatars.githubusercontent.com/u/11487621?v=4 width="100;" style="border-radius:50%;align-items:center;justify-content:center;overflow:hidden;padding-top:10px" alt=Luigi Pederzani/>
201
208
  <br />
202
- <sub style="font-size:14px"><b>Pietro Zullo</b></sub>
209
+ <sub style="font-size:14px"><b>Luigi Pederzani</b></sub>
203
210
  </a>
204
211
  </td>
205
212
  </tr>
@@ -20,7 +20,7 @@ import { MCPAgent, MCPClient } from '../index.js';
20
20
  // Load environment variables from .env file
21
21
  config();
22
22
  async function main() {
23
- const config = { mcpServers: { http: { url: 'https://hf.com/mcp' } } };
23
+ const config = { mcpServers: { http: { url: 'https://gitmcp.io/docs' } } };
24
24
  // Create MCPClient from config
25
25
  const client = MCPClient.fromDict(config);
26
26
  // Create LLM
@@ -28,8 +28,9 @@ async function main() {
28
28
  // Create agent with the client
29
29
  const agent = new MCPAgent({ llm, client, maxSteps: 30 });
30
30
  // Run the query
31
- const result = await agent.run('Find the best restaurant in San Francisco USING GOOGLE SEARCH', 30);
31
+ const result = await agent.run('Which tools are available and what can they do?', 30);
32
32
  console.log(`\nResult: ${result}`);
33
+ await agent.close();
33
34
  }
34
35
  if (import.meta.url === `file://${process.argv[1]}`) {
35
36
  main().catch(console.error);
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAMzD,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAGpE;AAED,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAChC,aAAa,CAwBf"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAMzD,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAGpE;AAED,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAChC,aAAa,CA6Bf"}
@@ -15,9 +15,13 @@ export function createConnectorFromConfig(serverConfig) {
15
15
  });
16
16
  }
17
17
  if ('url' in serverConfig) {
18
+ // HttpConnector automatically handles streamable HTTP with SSE fallback
19
+ const transport = serverConfig.transport || 'http';
18
20
  return new HttpConnector(serverConfig.url, {
19
21
  headers: serverConfig.headers,
20
- authToken: serverConfig.auth_token,
22
+ authToken: serverConfig.auth_token || serverConfig.authToken,
23
+ // Only force SSE if explicitly requested
24
+ preferSse: serverConfig.preferSse || transport === 'sse',
21
25
  });
22
26
  }
23
27
  if ('ws_url' in serverConfig) {
@@ -9,6 +9,7 @@ export interface HttpConnectorOptions extends ConnectorInitOptions {
9
9
  name: string;
10
10
  version: string;
11
11
  };
12
+ preferSse?: boolean;
12
13
  }
13
14
  export declare class HttpConnector extends BaseConnector {
14
15
  private readonly baseUrl;
@@ -16,9 +17,17 @@ export declare class HttpConnector extends BaseConnector {
16
17
  private readonly timeout;
17
18
  private readonly sseReadTimeout;
18
19
  private readonly clientInfo;
20
+ private readonly preferSse;
21
+ private transportType;
19
22
  constructor(baseUrl: string, opts?: HttpConnectorOptions);
20
- /** Establish connection to the MCP implementation via SSE. */
23
+ /** Establish connection to the MCP implementation via HTTP (streamable or SSE). */
21
24
  connect(): Promise<void>;
25
+ private connectWithStreamableHttp;
26
+ private connectWithSse;
22
27
  get publicIdentifier(): Record<string, string>;
28
+ /**
29
+ * Get the transport type being used (streamable-http or sse)
30
+ */
31
+ getTransportType(): 'streamable-http' | 'sse' | null;
23
32
  }
24
33
  //# sourceMappingURL=http.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../src/connectors/http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAIrD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAEzC,MAAM,WAAW,oBAAqB,SAAQ,oBAAoB;IAChE,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,UAAU,CAAC,EAAE;QAAE,IAAI,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AAQ,CAAC,cAAc,CAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmC;IAC9D,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,aAAa,CAAyC;gBAElD,OAAO,EAAE,MAAM,EAAE,IAAI,GAAE,oBAAyB;IAe5D,mFAAmF;IAC7E,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;YAkEhB,yBAAyB;YAmCzB,cAAc;IA4B5B,IAAI,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAM7C;IAED;;OAEG;IACH,gBAAgB,IAAI,iBAAiB,GAAG,KAAK,GAAG,IAAI;CAGrD"}
@@ -1,6 +1,8 @@
1
1
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
2
3
  import { logger } from '../logging.js';
3
4
  import { SseConnectionManager } from '../task_managers/sse.js';
5
+ import { StreamableHttpConnectionManager } from '../task_managers/streamable_http.js';
4
6
  import { BaseConnector } from './base.js';
5
7
  export class HttpConnector extends BaseConnector {
6
8
  baseUrl;
@@ -8,6 +10,8 @@ export class HttpConnector extends BaseConnector {
8
10
  timeout;
9
11
  sseReadTimeout;
10
12
  clientInfo;
13
+ preferSse;
14
+ transportType = null;
11
15
  constructor(baseUrl, opts = {}) {
12
16
  super(opts);
13
17
  this.baseUrl = baseUrl.replace(/\/$/, '');
@@ -18,32 +22,114 @@ export class HttpConnector extends BaseConnector {
18
22
  this.timeout = opts.timeout ?? 5;
19
23
  this.sseReadTimeout = opts.sseReadTimeout ?? 60 * 5;
20
24
  this.clientInfo = opts.clientInfo ?? { name: 'http-connector', version: '1.0.0' };
25
+ this.preferSse = opts.preferSse ?? false;
21
26
  }
22
- /** Establish connection to the MCP implementation via SSE. */
27
+ /** Establish connection to the MCP implementation via HTTP (streamable or SSE). */
23
28
  async connect() {
24
29
  if (this.connected) {
25
30
  logger.debug('Already connected to MCP implementation');
26
31
  return;
27
32
  }
28
- logger.debug(`Connecting to MCP implementation via HTTP/SSE: ${this.baseUrl}`);
33
+ const baseUrl = this.baseUrl;
34
+ // If preferSse is set, skip directly to SSE
35
+ if (this.preferSse) {
36
+ logger.debug(`Connecting to MCP implementation via HTTP/SSE: ${baseUrl}`);
37
+ await this.connectWithSse(baseUrl);
38
+ return;
39
+ }
40
+ // Try streamable HTTP first, then fall back to SSE
41
+ logger.debug(`Connecting to MCP implementation via HTTP: ${baseUrl}`);
42
+ try {
43
+ // Try streamable HTTP transport first
44
+ logger.debug('Attempting streamable HTTP transport...');
45
+ await this.connectWithStreamableHttp(baseUrl);
46
+ }
47
+ catch (err) {
48
+ // Check if this is a 4xx error that indicates we should try SSE fallback
49
+ let fallbackReason = 'Unknown error';
50
+ if (err instanceof StreamableHTTPError) {
51
+ if (err.code === 404 || err.code === 405) {
52
+ fallbackReason = `Server returned ${err.code} - server likely doesn't support streamable HTTP`;
53
+ logger.debug(fallbackReason);
54
+ }
55
+ else {
56
+ fallbackReason = `Server returned ${err.code}: ${err.message}`;
57
+ logger.debug(fallbackReason);
58
+ }
59
+ }
60
+ else if (err instanceof Error) {
61
+ // Check for 404/405 in error message as fallback detection
62
+ const errorStr = err.toString();
63
+ if (errorStr.includes('405 Method Not Allowed') || errorStr.includes('404 Not Found')) {
64
+ fallbackReason = 'Server doesn\'t support streamable HTTP (405/404)';
65
+ logger.debug(fallbackReason);
66
+ }
67
+ else {
68
+ fallbackReason = `Streamable HTTP failed: ${err.message}`;
69
+ logger.debug(fallbackReason);
70
+ }
71
+ }
72
+ // Always try SSE fallback for maximum compatibility
73
+ logger.debug('Falling back to SSE transport...');
74
+ try {
75
+ await this.connectWithSse(baseUrl);
76
+ }
77
+ catch (sseErr) {
78
+ logger.error(`Failed to connect with both transports:`);
79
+ logger.error(` Streamable HTTP: ${fallbackReason}`);
80
+ logger.error(` SSE: ${sseErr}`);
81
+ await this.cleanupResources();
82
+ throw new Error('Could not connect to server with any available transport');
83
+ }
84
+ }
85
+ }
86
+ async connectWithStreamableHttp(baseUrl) {
29
87
  try {
30
- // Build the SSE URL (root of server endpoint)
31
- const sseUrl = this.baseUrl;
32
- // Create and start the connection manager -> returns an SSE transport
33
- this.connectionManager = new SseConnectionManager(sseUrl, {
88
+ // Create and start the streamable HTTP connection manager
89
+ this.connectionManager = new StreamableHttpConnectionManager(baseUrl, {
34
90
  requestInit: {
35
91
  headers: this.headers,
36
92
  },
93
+ // Pass through timeout and other options
94
+ reconnectionOptions: {
95
+ maxReconnectionDelay: 30000,
96
+ initialReconnectionDelay: 1000,
97
+ reconnectionDelayGrowFactor: 1.5,
98
+ maxRetries: 2,
99
+ },
37
100
  });
38
101
  const transport = await this.connectionManager.start();
39
102
  // Create and connect the client
40
103
  this.client = new Client(this.clientInfo, this.opts.clientOptions);
41
104
  await this.client.connect(transport);
42
105
  this.connected = true;
43
- logger.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${this.baseUrl}`);
106
+ this.transportType = 'streamable-http';
107
+ logger.debug(`Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`);
44
108
  }
45
109
  catch (err) {
46
- logger.error(`Failed to connect to MCP implementation via HTTP/SSE: ${err}`);
110
+ // Clean up partial resources before throwing
111
+ await this.cleanupResources();
112
+ throw err;
113
+ }
114
+ }
115
+ async connectWithSse(baseUrl) {
116
+ try {
117
+ // Create and start the SSE connection manager
118
+ this.connectionManager = new SseConnectionManager(baseUrl, {
119
+ requestInit: {
120
+ headers: this.headers,
121
+ },
122
+ });
123
+ const transport = await this.connectionManager.start();
124
+ // Create and connect the client
125
+ this.client = new Client(this.clientInfo, this.opts.clientOptions);
126
+ await this.client.connect(transport);
127
+ this.connected = true;
128
+ this.transportType = 'sse';
129
+ logger.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`);
130
+ }
131
+ catch (err) {
132
+ // Clean up partial resources before throwing
47
133
  await this.cleanupResources();
48
134
  throw err;
49
135
  }
@@ -52,6 +138,13 @@ export class HttpConnector extends BaseConnector {
52
138
  return {
53
139
  type: 'http',
54
140
  url: this.baseUrl,
141
+ transport: this.transportType || 'unknown',
55
142
  };
56
143
  }
144
+ /**
145
+ * Get the transport type being used (streamable-http or sse)
146
+ */
147
+ getTransportType() {
148
+ return this.transportType;
149
+ }
57
150
  }
@@ -1,5 +1,6 @@
1
1
  export { ConnectionManager } from './base.js';
2
2
  export { SseConnectionManager } from './sse.js';
3
3
  export { StdioConnectionManager } from './stdio.js';
4
+ export { StreamableHttpConnectionManager } from './streamable_http.js';
4
5
  export { WebSocketConnectionManager } from './websocket.js';
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/task_managers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAC/C,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AACnD,OAAO,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/task_managers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAC/C,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AACnD,OAAO,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAA;AACtE,OAAO,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAA"}
@@ -1,4 +1,5 @@
1
1
  export { ConnectionManager } from './base.js';
2
2
  export { SseConnectionManager } from './sse.js';
3
3
  export { StdioConnectionManager } from './stdio.js';
4
+ export { StreamableHttpConnectionManager } from './streamable_http.js';
4
5
  export { WebSocketConnectionManager } from './websocket.js';
@@ -0,0 +1,29 @@
1
+ import type { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
2
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
3
+ import { ConnectionManager } from './base.js';
4
+ export declare class StreamableHttpConnectionManager extends ConnectionManager<StreamableHTTPClientTransport> {
5
+ private readonly url;
6
+ private readonly opts?;
7
+ private _transport;
8
+ /**
9
+ * Create a Streamable HTTP connection manager.
10
+ *
11
+ * @param url The HTTP endpoint URL.
12
+ * @param opts Optional transport options (auth, headers, etc.).
13
+ */
14
+ constructor(url: string | URL, opts?: StreamableHTTPClientTransportOptions);
15
+ /**
16
+ * Spawn a new `StreamableHTTPClientTransport` and return it.
17
+ * The Client.connect() method will handle starting the transport.
18
+ */
19
+ protected establishConnection(): Promise<StreamableHTTPClientTransport>;
20
+ /**
21
+ * Close the underlying transport and clean up resources.
22
+ */
23
+ protected closeConnection(_connection: StreamableHTTPClientTransport): Promise<void>;
24
+ /**
25
+ * Get the session ID from the transport if available.
26
+ */
27
+ get sessionId(): string | undefined;
28
+ }
29
+ //# sourceMappingURL=streamable_http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streamable_http.d.ts","sourceRoot":"","sources":["../../../src/task_managers/streamable_http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,oDAAoD,CAAA;AAC9G,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAA;AAElG,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAE7C,qBAAa,+BAAgC,SAAQ,iBAAiB,CAAC,6BAA6B,CAAC;IACnG,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAK;IACzB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAsC;IAC5D,OAAO,CAAC,UAAU,CAA6C;IAE/D;;;;;OAKG;gBACS,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,oCAAoC;IAM1E;;;OAGG;cACa,mBAAmB,IAAI,OAAO,CAAC,6BAA6B,CAAC;IAO7E;;OAEG;cACa,eAAe,CAAC,WAAW,EAAE,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC;IAc1F;;OAEG;IACH,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;CACF"}
@@ -0,0 +1,50 @@
1
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
2
+ import { logger } from '../logging.js';
3
+ import { ConnectionManager } from './base.js';
4
+ export class StreamableHttpConnectionManager extends ConnectionManager {
5
+ url;
6
+ opts;
7
+ _transport = null;
8
+ /**
9
+ * Create a Streamable HTTP connection manager.
10
+ *
11
+ * @param url The HTTP endpoint URL.
12
+ * @param opts Optional transport options (auth, headers, etc.).
13
+ */
14
+ constructor(url, opts) {
15
+ super();
16
+ this.url = typeof url === 'string' ? new URL(url) : url;
17
+ this.opts = opts;
18
+ }
19
+ /**
20
+ * Spawn a new `StreamableHTTPClientTransport` and return it.
21
+ * The Client.connect() method will handle starting the transport.
22
+ */
23
+ async establishConnection() {
24
+ this._transport = new StreamableHTTPClientTransport(this.url, this.opts);
25
+ logger.debug(`${this.constructor.name} created successfully`);
26
+ return this._transport;
27
+ }
28
+ /**
29
+ * Close the underlying transport and clean up resources.
30
+ */
31
+ async closeConnection(_connection) {
32
+ if (this._transport) {
33
+ try {
34
+ await this._transport.close();
35
+ }
36
+ catch (e) {
37
+ logger.warn(`Error closing Streamable HTTP transport: ${e}`);
38
+ }
39
+ finally {
40
+ this._transport = null;
41
+ }
42
+ }
43
+ }
44
+ /**
45
+ * Get the session ID from the transport if available.
46
+ */
47
+ get sessionId() {
48
+ return this._transport?.sessionId;
49
+ }
50
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../../src/telemetry/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAk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hD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA8D;IAC3F,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAA2D;IACjG,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAoD;IACpF,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAA8C;IAChF,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAoB;IAEpD,OAAO,CAAC,WAAW,CAAsB;IACzC,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,YAAY,CAAgC;IACpD,OAAO,CAAC,OAAO,CAAuB;IAEtC,OAAO;IAiDP,MAAM,CAAC,WAAW,IAAI,SAAS;IAO/B;;;;OAIG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAK/B;;OAEG;IACH,SAAS,IAAI,MAAM;IAInB,IAAI,MAAM,IAAI,MAAM,CAsCnB;IAEK,OAAO,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IA4CjD,oBAAoB,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IA0DrE,mBAAmB,CAAC,IAAI,EAAE,0BAA0B,GAAG,OAAO,CAAC,IAAI,CAAC;IAK1E,KAAK,IAAI,IAAI;IAkBb,QAAQ,IAAI,IAAI;CAiBjB"}
@@ -6,6 +6,31 @@ import { v4 as uuidv4 } from 'uuid';
6
6
  import { logger } from '../logging.js';
7
7
  import { MCPAgentExecutionEvent } from './events.js';
8
8
  import { getPackageVersion } from './utils.js';
9
+ // Environment detection function
10
+ function isNodeJSEnvironment() {
11
+ try {
12
+ // Check for Cloudflare Workers specifically
13
+ if (typeof navigator !== 'undefined' && navigator.userAgent?.includes('Cloudflare-Workers')) {
14
+ return false;
15
+ }
16
+ // Check for other edge runtime indicators
17
+ if (typeof globalThis.EdgeRuntime !== 'undefined' || typeof globalThis.Deno !== 'undefined') {
18
+ return false;
19
+ }
20
+ // Check for Node.js specific globals that are not available in edge environments
21
+ const hasNodeGlobals = (typeof process !== 'undefined'
22
+ && typeof process.platform !== 'undefined'
23
+ && typeof __dirname !== 'undefined');
24
+ // Check for Node.js modules
25
+ const hasNodeModules = (typeof fs !== 'undefined'
26
+ && typeof os !== 'undefined'
27
+ && typeof fs.existsSync === 'function');
28
+ return hasNodeGlobals && hasNodeModules;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
9
34
  // Simple Scarf event logger implementation
10
35
  class ScarfEventLogger {
11
36
  endpoint;
@@ -38,6 +63,10 @@ class ScarfEventLogger {
38
63
  }
39
64
  }
40
65
  function getCacheHome() {
66
+ // Return a safe fallback for non-Node.js environments
67
+ if (!isNodeJSEnvironment()) {
68
+ return '/tmp/mcp_use_cache';
69
+ }
41
70
  // XDG_CACHE_HOME for Linux and manually set envs
42
71
  const envVar = process.env.XDG_CACHE_HOME;
43
72
  if (envVar && path.isAbsolute(envVar)) {
@@ -74,13 +103,21 @@ export class Telemetry {
74
103
  _scarfClient = null;
75
104
  _source = 'typescript';
76
105
  constructor() {
77
- const telemetryDisabled = process.env.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === 'false';
106
+ // Check if we're in a Node.js environment first
107
+ const isNodeJS = isNodeJSEnvironment();
108
+ // Safely access environment variables
109
+ const telemetryDisabled = (typeof process !== 'undefined' && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === 'false') || false;
78
110
  // Check for source from environment variable, default to 'typescript'
79
- this._source = process.env.MCP_USE_TELEMETRY_SOURCE || 'typescript';
111
+ this._source = (typeof process !== 'undefined' && process.env?.MCP_USE_TELEMETRY_SOURCE) || 'typescript';
80
112
  if (telemetryDisabled) {
81
113
  this._posthogClient = null;
82
114
  this._scarfClient = null;
83
- logger.debug('Telemetry disabled');
115
+ logger.debug('Telemetry disabled via environment variable');
116
+ }
117
+ else if (!isNodeJS) {
118
+ this._posthogClient = null;
119
+ this._scarfClient = null;
120
+ logger.debug('Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)');
84
121
  }
85
122
  else {
86
123
  logger.info('Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.');
@@ -130,6 +167,11 @@ export class Telemetry {
130
167
  if (this._currUserId) {
131
168
  return this._currUserId;
132
169
  }
170
+ // If we're not in a Node.js environment, just return a static user ID
171
+ if (!isNodeJSEnvironment()) {
172
+ this._currUserId = this.UNKNOWN_USER_ID;
173
+ return this._currUserId;
174
+ }
133
175
  try {
134
176
  const isFirstTime = !fs.existsSync(this.USER_ID_PATH);
135
177
  if (isFirstTime) {
@@ -198,6 +240,10 @@ export class Telemetry {
198
240
  if (!this._scarfClient) {
199
241
  return;
200
242
  }
243
+ // Skip tracking in non-Node.js environments
244
+ if (!isNodeJSEnvironment()) {
245
+ return;
246
+ }
201
247
  try {
202
248
  const currentVersion = getPackageVersion();
203
249
  let shouldTrack = false;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/telemetry/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAA;AAI7E,wBAAgB,iBAAiB,IAAI,MAAM,CAS1C;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAG/D;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAgB3D;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,iBAAiB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAEzE"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/telemetry/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAA;AAI7E,wBAAgB,iBAAiB,IAAI,MAAM,CAc1C;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAG/D;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAgB3D;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,iBAAiB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAEzE"}
@@ -2,6 +2,10 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  export function getPackageVersion() {
4
4
  try {
5
+ // Check if we're in a Node.js environment with file system access
6
+ if (typeof __dirname === 'undefined' || typeof fs === 'undefined') {
7
+ return 'unknown';
8
+ }
5
9
  const packagePath = path.join(__dirname, '../../package.json');
6
10
  const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
7
11
  return packageJson.version || 'unknown';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "0.1.3",
4
+ "version": "0.1.5",
5
5
  "packageManager": "pnpm@10.6.1",
6
6
  "description": "A utility library for integrating Model Context Protocol (MCP) with LangChain, Zod, and related tools. Provides helpers for schema conversion, event streaming, and SDK usage.",
7
7
  "author": "Zane",