mcp-use 0.1.2 → 0.1.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.
@@ -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,oBA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A;IAC9C,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB;AAED,qBAAa,aAAc,SAAQ,aAAa;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwB;IAChD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,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
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "0.1.2",
4
+ "version": "0.1.4",
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",
@@ -71,7 +71,6 @@
71
71
  "dependencies": {
72
72
  "@dmitryrechkin/json-schema-to-zod": "^1.0.1",
73
73
  "@langchain/anthropic": "^0.3.14",
74
- "@langchain/community": "0.3.45",
75
74
  "@langchain/core": "0.3.58",
76
75
  "@langchain/openai": "^0.5.15",
77
76
  "@modelcontextprotocol/sdk": "1.12.1",