mcp-use 0.0.8 → 0.1.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 (37) hide show
  1. package/README.md +32 -0
  2. package/dist/examples/add_server_tool.d.ts +8 -0
  3. package/dist/examples/add_server_tool.d.ts.map +1 -0
  4. package/dist/examples/add_server_tool.js +65 -0
  5. package/dist/examples/airbnb_use.d.ts +10 -0
  6. package/dist/examples/airbnb_use.d.ts.map +1 -0
  7. package/dist/examples/airbnb_use.js +43 -0
  8. package/dist/examples/blender_use.d.ts +15 -0
  9. package/dist/examples/blender_use.d.ts.map +1 -0
  10. package/dist/examples/blender_use.js +39 -0
  11. package/dist/examples/browser_use.d.ts +10 -0
  12. package/dist/examples/browser_use.d.ts.map +1 -0
  13. package/dist/examples/browser_use.js +46 -0
  14. package/dist/examples/chat_example.d.ts +10 -0
  15. package/dist/examples/chat_example.d.ts.map +1 -0
  16. package/dist/examples/chat_example.js +86 -0
  17. package/dist/examples/filesystem_use.d.ts +11 -0
  18. package/dist/examples/filesystem_use.d.ts.map +1 -0
  19. package/dist/examples/filesystem_use.js +43 -0
  20. package/dist/examples/http_example.d.ts +18 -0
  21. package/dist/examples/http_example.d.ts.map +1 -0
  22. package/dist/examples/http_example.js +36 -0
  23. package/dist/examples/mcp_everything.d.ts +6 -0
  24. package/dist/examples/mcp_everything.d.ts.map +1 -0
  25. package/dist/examples/mcp_everything.js +25 -0
  26. package/dist/examples/multi_server_example.d.ts +10 -0
  27. package/dist/examples/multi_server_example.d.ts.map +1 -0
  28. package/dist/examples/multi_server_example.js +51 -0
  29. package/dist/src/connectors/stdio.d.ts.map +1 -1
  30. package/dist/src/connectors/stdio.js +14 -1
  31. package/dist/src/managers/server_manager.d.ts +1 -0
  32. package/dist/src/managers/server_manager.d.ts.map +1 -1
  33. package/dist/src/managers/server_manager.js +30 -2
  34. package/dist/src/managers/tools/add_server.d.ts +21 -0
  35. package/dist/src/managers/tools/add_server.d.ts.map +1 -0
  36. package/dist/src/managers/tools/add_server.js +40 -0
  37. package/package.json +20 -4
package/README.md CHANGED
@@ -126,6 +126,38 @@ const client = MCPClient.fromConfigFile('./mcp-config.json')
126
126
 
127
127
  ---
128
128
 
129
+ ## 📚 Examples
130
+
131
+ We provide a comprehensive set of examples demonstrating various use cases. All examples are located in the `examples/` directory with a dedicated README.
132
+
133
+ ### Running Examples
134
+
135
+ ```bash
136
+ # Install dependencies
137
+ npm install
138
+
139
+ # Run any example
140
+ npm run example:airbnb # Search accommodations with Airbnb
141
+ npm run example:browser # Browser automation with Playwright
142
+ npm run example:chat # Interactive chat with memory
143
+ npm run example:filesystem # File system operations
144
+ npm run example:http # HTTP server connection
145
+ npm run example:everything # Test MCP functionalities
146
+ npm run example:multi # Multiple servers in one session
147
+ ```
148
+
149
+ ### Example Highlights
150
+
151
+ - **Browser Automation**: Control browsers to navigate websites and extract information
152
+ - **File Operations**: Read, write, and manipulate files through MCP
153
+ - **Multi-Server**: Combine multiple MCP servers (Airbnb + Browser) in a single task
154
+ - **Sandboxed Execution**: Run MCP servers in isolated E2B containers
155
+ - **OAuth Flows**: Authenticate with services like Linear using OAuth2
156
+
157
+ See the [examples README](./examples/README.md) for detailed documentation and prerequisites.
158
+
159
+ ---
160
+
129
161
  ## 🔄 Multi-Server Example
130
162
 
131
163
  ```ts
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Dynamic server management example for mcp-use.
3
+ *
4
+ * This example demonstrates how to equip an MCPAgent with a tool
5
+ * to dynamically add and connect to MCP servers during a run.
6
+ */
7
+ export {};
8
+ //# sourceMappingURL=add_server_tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"add_server_tool.d.ts","sourceRoot":"","sources":["../../examples/add_server_tool.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Dynamic server management example for mcp-use.
3
+ *
4
+ * This example demonstrates how to equip an MCPAgent with a tool
5
+ * to dynamically add and connect to MCP servers during a run.
6
+ */
7
+ import { ChatOpenAI } from '@langchain/openai';
8
+ import { config } from 'dotenv';
9
+ import { MCPAgent, MCPClient } from '../index.js';
10
+ import { LangChainAdapter } from '../src/adapters/langchain_adapter.js';
11
+ import { ServerManager } from '../src/managers/server_manager.js';
12
+ // Load environment variables from .env file
13
+ config();
14
+ async function main() {
15
+ // Create an empty MCPClient. It has no servers to start with.
16
+ const client = new MCPClient();
17
+ // The LLM to power the agent
18
+ const llm = new ChatOpenAI({ model: 'gpt-4o', temperature: 0 });
19
+ // Create the agent, enabling the ServerManager
20
+ const agent = new MCPAgent({
21
+ llm,
22
+ client,
23
+ maxSteps: 30,
24
+ useServerManager: true,
25
+ serverManagerFactory: client => new ServerManager(client, new LangChainAdapter()),
26
+ autoInitialize: true,
27
+ });
28
+ // Define the server configuration that the agent will be asked to add.
29
+ const serverConfigA = {
30
+ command: 'npx',
31
+ args: ['@playwright/mcp@latest'],
32
+ env: {
33
+ DISPLAY: ':1',
34
+ },
35
+ };
36
+ const serverConfigB = {
37
+ command: 'npx',
38
+ args: ['-y', '@openbnb/mcp-server-airbnb', '--ignore-robots-txt'],
39
+ };
40
+ // We'll pass the config as a JSON string in the prompt.
41
+ const serverConfigStringA = JSON.stringify(serverConfigA, null, 2);
42
+ const serverConfigStringB = JSON.stringify(serverConfigB, null, 2);
43
+ const query = `I need to browse the web. To do this, please add and connect to a new MCP server for Playwright.
44
+ The server name is 'playwright' and its configuration is:
45
+ \`\`\`json
46
+ ${serverConfigStringA}
47
+ \`\`\`
48
+ Once the server is ready, navigate to https://github.com/mcp-use/mcp-use, give a star to the project, and then provide a concise summary of the project's README.
49
+
50
+ Then, please add and connect to a new MCP server for Airbnb.
51
+ The server name is 'airbnb' and its configuration is:
52
+ \`\`\`json
53
+ ${serverConfigStringB}
54
+ \`\`\`
55
+ and give me a house in the location of the company mcp-use.
56
+ `;
57
+ // Run the agent. It will first use the AddMCPServerTool, then the tools from the new server.
58
+ const result = await agent.run(query);
59
+ console.log(`\n✅ Final Result:\n${result}`);
60
+ // Clean up the session created by the agent
61
+ await client.closeAllSessions();
62
+ }
63
+ if (import.meta.url === `file://${process.argv[1]}`) {
64
+ main().catch(console.error);
65
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Example demonstrating how to use mcp-use with Airbnb.
3
+ *
4
+ * This example shows how to connect an LLM to Airbnb through MCP tools
5
+ * to perform tasks like searching for accommodations.
6
+ *
7
+ * Special Thanks to https://github.com/openbnb-org/mcp-server-airbnb for the server.
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=airbnb_use.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"airbnb_use.d.ts","sourceRoot":"","sources":["../../examples/airbnb_use.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Example demonstrating how to use mcp-use with Airbnb.
3
+ *
4
+ * This example shows how to connect an LLM to Airbnb through MCP tools
5
+ * to perform tasks like searching for accommodations.
6
+ *
7
+ * Special Thanks to https://github.com/openbnb-org/mcp-server-airbnb for the server.
8
+ */
9
+ import { ChatOpenAI } from '@langchain/openai';
10
+ import { config } from 'dotenv';
11
+ import { MCPAgent, MCPClient } from '../index.js';
12
+ // Load environment variables from .env file
13
+ config();
14
+ async function runAirbnbExample() {
15
+ // Create MCPClient with Airbnb configuration
16
+ const config = {
17
+ mcpServers: {
18
+ airbnb: {
19
+ command: 'npx',
20
+ args: ['-y', '@openbnb/mcp-server-airbnb', '--ignore-robots-txt'],
21
+ },
22
+ },
23
+ };
24
+ const client = new MCPClient(config);
25
+ // Create LLM - you can choose between different models
26
+ const llm = new ChatOpenAI({ model: 'gpt-4o' });
27
+ // Create agent with the client
28
+ const agent = new MCPAgent({ llm, client, maxSteps: 30 });
29
+ try {
30
+ // Run a query to search for accommodations
31
+ const result = await agent.run('Find me a nice place to stay in Barcelona for 2 adults '
32
+ + 'for a week in August. I prefer places with a pool and '
33
+ + 'good reviews. Show me the top 3 options.', 30);
34
+ console.error(`\nResult: ${result}`);
35
+ }
36
+ finally {
37
+ // Ensure we clean up resources properly
38
+ await client.closeAllSessions();
39
+ }
40
+ }
41
+ if (import.meta.url === `file://${process.argv[1]}`) {
42
+ runAirbnbExample().catch(console.error);
43
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Blender MCP example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect an LLM to Blender through MCP tools via WebSocket.
6
+ * The example assumes you have installed the Blender MCP addon from:
7
+ * https://github.com/ahujasid/blender-mcp
8
+ *
9
+ * Make sure the addon is enabled in Blender preferences and the WebSocket
10
+ * server is running before executing this script.
11
+ *
12
+ * Special thanks to https://github.com/ahujasid/blender-mcp for the server.
13
+ */
14
+ export {};
15
+ //# sourceMappingURL=blender_use.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blender_use.d.ts","sourceRoot":"","sources":["../../examples/blender_use.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Blender MCP example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect an LLM to Blender through MCP tools via WebSocket.
6
+ * The example assumes you have installed the Blender MCP addon from:
7
+ * https://github.com/ahujasid/blender-mcp
8
+ *
9
+ * Make sure the addon is enabled in Blender preferences and the WebSocket
10
+ * server is running before executing this script.
11
+ *
12
+ * Special thanks to https://github.com/ahujasid/blender-mcp for the server.
13
+ */
14
+ import { ChatAnthropic } from '@langchain/anthropic';
15
+ import { config } from 'dotenv';
16
+ import { MCPAgent, MCPClient } from '../index.js';
17
+ // Load environment variables from .env file
18
+ config();
19
+ async function runBlenderExample() {
20
+ // Create MCPClient with Blender MCP configuration
21
+ const config = { mcpServers: { blender: { command: 'uvx', args: ['blender-mcp'] } } };
22
+ const client = MCPClient.fromDict(config);
23
+ // Create LLM
24
+ const llm = new ChatAnthropic({ model: 'claude-3-5-sonnet-20240620' });
25
+ // Create agent with the client
26
+ const agent = new MCPAgent({ llm, client, maxSteps: 30 });
27
+ try {
28
+ // Run the query
29
+ const result = await agent.run('Create an inflatable cube with soft material and a plane as ground.', 30);
30
+ console.error(`\nResult: ${result}`);
31
+ }
32
+ finally {
33
+ // Ensure we clean up resources properly
34
+ await client.closeAllSessions();
35
+ }
36
+ }
37
+ if (import.meta.url === `file://${process.argv[1]}`) {
38
+ runBlenderExample().catch(console.error);
39
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Basic usage example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect any LLM to MCP tools through a unified interface.
6
+ *
7
+ * Special thanks to https://github.com/microsoft/playwright-mcp for the server.
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=browser_use.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser_use.d.ts","sourceRoot":"","sources":["../../examples/browser_use.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Basic usage example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect any LLM to MCP tools through a unified interface.
6
+ *
7
+ * Special thanks to https://github.com/microsoft/playwright-mcp for the server.
8
+ */
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { ChatOpenAI } from '@langchain/openai';
12
+ import { config } from 'dotenv';
13
+ import { MCPAgent, MCPClient } from '../index.js';
14
+ // Load environment variables from .env file
15
+ config();
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = path.dirname(__filename);
18
+ async function main() {
19
+ const config = {
20
+ mcpServers: {
21
+ playwright: {
22
+ command: 'npx',
23
+ args: ['@playwright/mcp@latest'],
24
+ env: {
25
+ DISPLAY: ':1',
26
+ },
27
+ },
28
+ },
29
+ };
30
+ // Create MCPClient from config file
31
+ const client = new MCPClient(config);
32
+ // Create LLM
33
+ const llm = new ChatOpenAI({ model: 'gpt-4o' });
34
+ // const llm = init_chat_model({ model: "llama-3.1-8b-instant", model_provider: "groq" })
35
+ // const llm = new ChatAnthropic({ model: "claude-3-" })
36
+ // const llm = new ChatGroq({ model: "llama3-8b-8192" })
37
+ // Create agent with the client
38
+ const agent = new MCPAgent({ llm, client, maxSteps: 30 });
39
+ // Run the query
40
+ const result = await agent.run(`Navigate to https://github.com/mcp-use/mcp-use, give a star to the project and write
41
+ a summary of the project.`, 30);
42
+ console.error(`\nResult: ${result}`);
43
+ }
44
+ if (import.meta.url === `file://${process.argv[1]}`) {
45
+ main().catch(console.error);
46
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Simple chat example using MCPAgent with built-in conversation memory.
3
+ *
4
+ * This example demonstrates how to use the MCPAgent with its built-in
5
+ * conversation history capabilities for better contextual interactions.
6
+ *
7
+ * Special thanks to https://github.com/microsoft/playwright-mcp for the server.
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=chat_example.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat_example.d.ts","sourceRoot":"","sources":["../../examples/chat_example.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Simple chat example using MCPAgent with built-in conversation memory.
3
+ *
4
+ * This example demonstrates how to use the MCPAgent with its built-in
5
+ * conversation history capabilities for better contextual interactions.
6
+ *
7
+ * Special thanks to https://github.com/microsoft/playwright-mcp for the server.
8
+ */
9
+ import readline from 'node:readline';
10
+ import { ChatOpenAI } from '@langchain/openai';
11
+ import { config } from 'dotenv';
12
+ import { MCPAgent, MCPClient } from '../index.js';
13
+ // Load environment variables from .env file
14
+ config();
15
+ async function runMemoryChat() {
16
+ // Config file path - change this to your config file
17
+ const config = {
18
+ mcpServers: {
19
+ airbnb: {
20
+ command: 'npx',
21
+ args: ['-y', '@openbnb/mcp-server-airbnb', '--ignore-robots-txt'],
22
+ },
23
+ },
24
+ };
25
+ console.error('Initializing chat...');
26
+ // Create MCP client and agent with memory enabled
27
+ const client = new MCPClient(config);
28
+ const llm = new ChatOpenAI({ model: 'gpt-4o-mini' });
29
+ // Create agent with memory_enabled=true
30
+ const agent = new MCPAgent({
31
+ llm,
32
+ client,
33
+ maxSteps: 15,
34
+ memoryEnabled: true, // Enable built-in conversation memory
35
+ });
36
+ console.error('\n===== Interactive MCP Chat =====');
37
+ console.error('Type \'exit\' or \'quit\' to end the conversation');
38
+ console.error('Type \'clear\' to clear conversation history');
39
+ console.error('==================================\n');
40
+ // Create readline interface for user input
41
+ const rl = readline.createInterface({
42
+ input: process.stdin,
43
+ output: process.stdout,
44
+ });
45
+ const question = (prompt) => {
46
+ return new Promise((resolve) => {
47
+ rl.question(prompt, resolve);
48
+ });
49
+ };
50
+ try {
51
+ // Main chat loop
52
+ while (true) {
53
+ // Get user input
54
+ const userInput = await question('\nYou: ');
55
+ // Check for exit command
56
+ if (userInput.toLowerCase() === 'exit' || userInput.toLowerCase() === 'quit') {
57
+ console.error('Ending conversation...');
58
+ break;
59
+ }
60
+ // Check for clear history command
61
+ if (userInput.toLowerCase() === 'clear') {
62
+ agent.clearConversationHistory();
63
+ console.error('Conversation history cleared.');
64
+ continue;
65
+ }
66
+ // Get response from agent
67
+ process.stdout.write('\nAssistant: ');
68
+ try {
69
+ // Run the agent with the user input (memory handling is automatic)
70
+ const response = await agent.run(userInput);
71
+ console.error(response);
72
+ }
73
+ catch (error) {
74
+ console.error(`\nError: ${error}`);
75
+ }
76
+ }
77
+ }
78
+ finally {
79
+ // Clean up
80
+ rl.close();
81
+ await client.closeAllSessions();
82
+ }
83
+ }
84
+ if (import.meta.url === `file://${process.argv[1]}`) {
85
+ runMemoryChat().catch(console.error);
86
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Basic usage example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect any LLM to MCP tools through a unified interface.
6
+ *
7
+ * Special Thanks to https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem
8
+ * for the server.
9
+ */
10
+ export {};
11
+ //# sourceMappingURL=filesystem_use.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filesystem_use.d.ts","sourceRoot":"","sources":["../../examples/filesystem_use.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Basic usage example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect any LLM to MCP tools through a unified interface.
6
+ *
7
+ * Special Thanks to https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem
8
+ * for the server.
9
+ */
10
+ import { ChatOpenAI } from '@langchain/openai';
11
+ import { config } from 'dotenv';
12
+ import { MCPAgent, MCPClient } from '../index.js';
13
+ // Load environment variables from .env file
14
+ config();
15
+ const serverConfig = {
16
+ mcpServers: {
17
+ filesystem: {
18
+ command: 'npx',
19
+ args: [
20
+ '-y',
21
+ '@modelcontextprotocol/server-filesystem',
22
+ 'THE_PATH_TO_YOUR_DIRECTORY',
23
+ ],
24
+ },
25
+ },
26
+ };
27
+ async function main() {
28
+ // Create MCPClient from config
29
+ const client = MCPClient.fromDict(serverConfig);
30
+ // Create LLM
31
+ const llm = new ChatOpenAI({ model: 'gpt-4o' });
32
+ // const llm = init_chat_model({ model: "llama-3.1-8b-instant", model_provider: "groq" })
33
+ // const llm = new ChatAnthropic({ model: "claude-3-" })
34
+ // const llm = new ChatGroq({ model: "llama3-8b-8192" })
35
+ // Create agent with the client
36
+ const agent = new MCPAgent({ llm, client, maxSteps: 30 });
37
+ // Run the query
38
+ const result = await agent.run('Hello can you give me a list of files and directories in the current directory', 30);
39
+ console.log(`\nResult: ${result}`);
40
+ }
41
+ if (import.meta.url === `file://${process.argv[1]}`) {
42
+ main().catch(console.error);
43
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * HTTP Example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect to an MCP server running on a specific HTTP port.
6
+ *
7
+ * Before running this example, you need to start the Playwright MCP server
8
+ * in another terminal with:
9
+ *
10
+ * npx @playwright/mcp@latest --port 8931
11
+ *
12
+ * This will start the server on port 8931. Resulting in the config you find below.
13
+ * Of course you can run this with any server you want at any URL.
14
+ *
15
+ * Special thanks to https://github.com/microsoft/playwright-mcp for the server.
16
+ */
17
+ export {};
18
+ //# sourceMappingURL=http_example.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http_example.d.ts","sourceRoot":"","sources":["../../examples/http_example.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * HTTP Example for mcp-use.
3
+ *
4
+ * This example demonstrates how to use the mcp-use library with MCPClient
5
+ * to connect to an MCP server running on a specific HTTP port.
6
+ *
7
+ * Before running this example, you need to start the Playwright MCP server
8
+ * in another terminal with:
9
+ *
10
+ * npx @playwright/mcp@latest --port 8931
11
+ *
12
+ * This will start the server on port 8931. Resulting in the config you find below.
13
+ * Of course you can run this with any server you want at any URL.
14
+ *
15
+ * Special thanks to https://github.com/microsoft/playwright-mcp for the server.
16
+ */
17
+ import { ChatOpenAI } from '@langchain/openai';
18
+ import { config } from 'dotenv';
19
+ import { MCPAgent, MCPClient } from '../index.js';
20
+ // Load environment variables from .env file
21
+ config();
22
+ async function main() {
23
+ const config = { mcpServers: { http: { url: 'https://hf.com/mcp' } } };
24
+ // Create MCPClient from config
25
+ const client = MCPClient.fromDict(config);
26
+ // Create LLM
27
+ const llm = new ChatOpenAI({ model: 'gpt-4o' });
28
+ // Create agent with the client
29
+ const agent = new MCPAgent({ llm, client, maxSteps: 30 });
30
+ // Run the query
31
+ const result = await agent.run('Find the best restaurant in San Francisco USING GOOGLE SEARCH', 30);
32
+ console.log(`\nResult: ${result}`);
33
+ }
34
+ if (import.meta.url === `file://${process.argv[1]}`) {
35
+ main().catch(console.error);
36
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * This example shows how to test the different functionalities of MCPs using the MCP server from
3
+ * anthropic.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=mcp_everything.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp_everything.d.ts","sourceRoot":"","sources":["../../examples/mcp_everything.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * This example shows how to test the different functionalities of MCPs using the MCP server from
3
+ * anthropic.
4
+ */
5
+ import { ChatOpenAI } from '@langchain/openai';
6
+ import { config } from 'dotenv';
7
+ import { MCPAgent, MCPClient } from '../index.js';
8
+ // Load environment variables from .env file
9
+ config();
10
+ const everythingServer = {
11
+ mcpServers: { everything: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-everything'] } },
12
+ };
13
+ async function main() {
14
+ const client = new MCPClient(everythingServer);
15
+ const llm = new ChatOpenAI({ model: 'gpt-4o', temperature: 0 });
16
+ const agent = new MCPAgent({ llm, client, maxSteps: 30 });
17
+ const result = await agent.run(`Hello, you are a tester can you please answer the follwing questions:
18
+ - Which resources do you have access to?
19
+ - Which prompts do you have access to?
20
+ - Which tools do you have access to?`, 30);
21
+ console.log(`\nResult: ${result}`);
22
+ }
23
+ if (import.meta.url === `file://${process.argv[1]}`) {
24
+ main().catch(console.error);
25
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Example demonstrating how to use MCPClient with multiple servers.
3
+ *
4
+ * This example shows how to:
5
+ * 1. Configure multiple MCP servers
6
+ * 2. Create and manage sessions for each server
7
+ * 3. Use tools from different servers in a single agent
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=multi_server_example.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multi_server_example.d.ts","sourceRoot":"","sources":["../../examples/multi_server_example.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Example demonstrating how to use MCPClient with multiple servers.
3
+ *
4
+ * This example shows how to:
5
+ * 1. Configure multiple MCP servers
6
+ * 2. Create and manage sessions for each server
7
+ * 3. Use tools from different servers in a single agent
8
+ */
9
+ import { ChatAnthropic } from '@langchain/anthropic';
10
+ import { config } from 'dotenv';
11
+ import { MCPAgent, MCPClient } from '../index.js';
12
+ // Load environment variables from .env file
13
+ config();
14
+ async function runMultiServerExample() {
15
+ // Create a configuration with multiple servers
16
+ const config = {
17
+ mcpServers: {
18
+ airbnb: {
19
+ command: 'npx',
20
+ args: ['-y', '@openbnb/mcp-server-airbnb', '--ignore-robots-txt'],
21
+ },
22
+ playwright: {
23
+ command: 'npx',
24
+ args: ['@playwright/mcp@latest'],
25
+ env: { DISPLAY: ':1' },
26
+ },
27
+ filesystem: {
28
+ command: 'npx',
29
+ args: [
30
+ '-y',
31
+ '@modelcontextprotocol/server-filesystem',
32
+ 'YOUR_DIRECTORY_HERE',
33
+ ],
34
+ },
35
+ },
36
+ };
37
+ // Create MCPClient with the multi-server configuration
38
+ const client = MCPClient.fromDict(config);
39
+ // Create LLM
40
+ const llm = new ChatAnthropic({ model: 'claude-3-5-sonnet-20240620' });
41
+ // Create agent with the client
42
+ const agent = new MCPAgent({ llm, client, maxSteps: 30 });
43
+ // Example 1: Using tools from different servers in a single query
44
+ const result = await agent.run('Search for a nice place to stay in Barcelona on Airbnb, '
45
+ + 'then use Google to find nearby restaurants and attractions.'
46
+ + 'Write the result in the current directory in restarant.txt', 30);
47
+ console.log(result);
48
+ }
49
+ if (import.meta.url === `file://${process.argv[1]}`) {
50
+ runMultiServerExample().catch(console.error);
51
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/connectors/stdio.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAMrD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAEzC,MAAM,WAAW,qBAAsB,SAAQ,oBAAoB;IACjE,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAC/C;AAED,qBAAa,cAAe,SAAQ,aAAa;IAC/C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAU;IAC/B,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAwB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAU;IACjC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmC;gBAG5D,EACE,OAAe,EACf,IAAS,EACT,GAAG,EACH,MAAuB,EACvB,GAAG,IAAI,EACR,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAA;QAChB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;QACf,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAC5B,MAAM,CAAC,EAAE,QAAQ,CAAA;KAClB,GAAG,qBAA0B;IAWhC,sDAAsD;IAChD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAiC/B"}
1
+ {"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/connectors/stdio.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAMrD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAEzC,MAAM,WAAW,qBAAsB,SAAQ,oBAAoB;IACjE,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAC/C;AAED,qBAAa,cAAe,SAAQ,aAAa;IAC/C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAU;IAC/B,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAwB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAU;IACjC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmC;gBAG5D,EACE,OAAe,EACf,IAAS,EACT,GAAG,EACH,MAAuB,EACvB,GAAG,IAAI,EACR,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAA;QAChB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;QACf,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAC5B,MAAM,CAAC,EAAE,QAAQ,CAAA;KAClB,GAAG,qBAA0B;IAWhC,sDAAsD;IAChD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CA+C/B"}
@@ -26,10 +26,23 @@ export class StdioConnector extends BaseConnector {
26
26
  logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`);
27
27
  try {
28
28
  // 1. Build server parameters for the transport
29
+ // Merge env with process.env, filtering out undefined values
30
+ let mergedEnv;
31
+ if (this.env) {
32
+ mergedEnv = {};
33
+ // First add process.env values (excluding undefined)
34
+ for (const [key, value] of Object.entries(process.env)) {
35
+ if (value !== undefined) {
36
+ mergedEnv[key] = value;
37
+ }
38
+ }
39
+ // Then override with provided env
40
+ Object.assign(mergedEnv, this.env);
41
+ }
29
42
  const serverParams = {
30
43
  command: this.command,
31
44
  args: this.args,
32
- env: this.env,
45
+ env: mergedEnv,
33
46
  };
34
47
  // 2. Start the connection manager -> returns a live transport
35
48
  this.connectionManager = new StdioConnectionManager(serverParams, this.errlog);
@@ -8,6 +8,7 @@ export declare class ServerManager {
8
8
  readonly adapter: LangChainAdapter;
9
9
  activeServer: string | null;
10
10
  constructor(client: MCPClient, adapter: LangChainAdapter);
11
+ logState(context: string): void;
11
12
  initialize(): void;
12
13
  prefetchServerTools(): Promise<void>;
13
14
  get tools(): StructuredToolInterface[];
@@ -1 +1 @@
1
- {"version":3,"file":"server_manager.d.ts","sourceRoot":"","sources":["../../../src/managers/server_manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAA;AACpE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAA;AACxE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAU7C,qBAAa,aAAa;IACxB,SAAgB,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAK;IAChE,SAAgB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,EAAE,CAAC,CAAK;IAE3E,SAAgB,MAAM,EAAE,SAAS,CAAA;IACjC,SAAgB,OAAO,EAAE,gBAAgB,CAAA;IAClC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAO;gBAE7B,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB;IAKxD,UAAU,IAAI,IAAI;IAOZ,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC;IAoD1C,IAAI,KAAK,IAAI,uBAAuB,EAAE,CAOrC;CACF"}
1
+ {"version":3,"file":"server_manager.d.ts","sourceRoot":"","sources":["../../../src/managers/server_manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAA;AACpE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAA;AACxE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAW7C,qBAAa,aAAa;IACxB,SAAgB,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAK;IAChE,SAAgB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,EAAE,CAAC,CAAK;IAE3E,SAAgB,MAAM,EAAE,SAAS,CAAA;IACjC,SAAgB,OAAO,EAAE,gBAAgB,CAAA;IAClC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAO;gBAE7B,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB;IAKjD,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAqBtC,UAAU,IAAI,IAAI;IAOZ,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC;IAoD1C,IAAI,KAAK,IAAI,uBAAuB,EAAE,CAsBrC;CACF"}
@@ -1,6 +1,7 @@
1
1
  import { isEqual } from 'lodash-es';
2
2
  import { logger } from '../logging.js';
3
3
  import { AcquireActiveMCPServerTool } from './tools/acquire_active_mcp_server.js';
4
+ import { AddMCPServerTool } from './tools/add_server.js';
4
5
  import { ConnectMCPServerTool } from './tools/connect_mcp_server.js';
5
6
  import { ListMCPServersTool } from './tools/list_mcp_servers.js';
6
7
  import { ReleaseMCPServerConnectionTool } from './tools/release_mcp_server_connection.js';
@@ -14,10 +15,27 @@ export class ServerManager {
14
15
  this.client = client;
15
16
  this.adapter = adapter;
16
17
  }
18
+ logState(context) {
19
+ const allServerNames = this.client.getServerNames();
20
+ const activeSessionNames = Object.keys(this.client.getAllActiveSessions());
21
+ if (allServerNames.length === 0) {
22
+ logger.info('Server Manager State: No servers configured.');
23
+ return;
24
+ }
25
+ const tableData = allServerNames.map(name => ({
26
+ 'Server Name': name,
27
+ 'Connected': activeSessionNames.includes(name) ? '✅' : '❌',
28
+ 'Initialized': this.initializedServers[name] ? '✅' : '❌',
29
+ 'Tool Count': this.serverTools[name]?.length ?? 0,
30
+ 'Active': this.activeServer === name ? '✅' : '❌',
31
+ }));
32
+ logger.info(`Server Manager State: [${context}]`);
33
+ console.table(tableData); // eslint-disable-line no-console
34
+ }
17
35
  initialize() {
18
36
  const serverNames = this.client.getServerNames?.();
19
37
  if (serverNames.length === 0) {
20
- logger.warning('No MCP servers defined in client configuration');
38
+ logger.warn('No MCP servers defined in client configuration');
21
39
  }
22
40
  }
23
41
  async prefetchServerTools() {
@@ -62,11 +80,21 @@ export class ServerManager {
62
80
  }
63
81
  }
64
82
  get tools() {
65
- return [
83
+ if (logger.level === 'debug') {
84
+ this.logState('Providing tools to agent');
85
+ }
86
+ const managementTools = [
87
+ new AddMCPServerTool(this),
66
88
  new ListMCPServersTool(this),
67
89
  new ConnectMCPServerTool(this),
68
90
  new AcquireActiveMCPServerTool(this),
69
91
  new ReleaseMCPServerConnectionTool(this),
70
92
  ];
93
+ if (this.activeServer && this.serverTools[this.activeServer]) {
94
+ const activeTools = this.serverTools[this.activeServer];
95
+ logger.debug(`Adding ${activeTools.length} tools from active server '${this.activeServer}'`);
96
+ return [...managementTools, ...activeTools];
97
+ }
98
+ return managementTools;
71
99
  }
72
100
  }
@@ -0,0 +1,21 @@
1
+ import type { ServerManager } from '../server_manager.js';
2
+ import { StructuredTool } from 'langchain/tools';
3
+ import { z } from 'zod';
4
+ export declare class AddMCPServerTool extends StructuredTool {
5
+ name: string;
6
+ description: string;
7
+ schema: z.ZodObject<{
8
+ serverName: z.ZodString;
9
+ serverConfig: z.ZodAny;
10
+ }, "strip", z.ZodTypeAny, {
11
+ serverName: string;
12
+ serverConfig?: any;
13
+ }, {
14
+ serverName: string;
15
+ serverConfig?: any;
16
+ }>;
17
+ private manager;
18
+ constructor(manager: ServerManager);
19
+ protected _call({ serverName, serverConfig, }: z.infer<typeof this.schema>): Promise<string>;
20
+ }
21
+ //# sourceMappingURL=add_server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"add_server.d.ts","sourceRoot":"","sources":["../../../../src/managers/tools/add_server.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAGvB,qBAAa,gBAAiB,SAAQ,cAAc;IAClD,IAAI,SAAmB;IACvB,WAAW,SAC8E;IAEzF,MAAM;;;;;;;;;OAOJ;IAEF,OAAO,CAAC,OAAO,CAAe;gBAElB,OAAO,EAAE,aAAa;cAKlB,KAAK,CAAC,EACpB,UAAU,EACV,YAAY,GACb,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;CA6BjD"}
@@ -0,0 +1,40 @@
1
+ import { StructuredTool } from 'langchain/tools';
2
+ import { z } from 'zod';
3
+ import { logger } from '../../logging.js';
4
+ export class AddMCPServerTool extends StructuredTool {
5
+ name = 'add_mcp_server';
6
+ description = 'Adds a new MCP server to the client and connects to it, making its tools available.';
7
+ schema = z.object({
8
+ serverName: z.string().describe('The name for the new MCP server.'),
9
+ serverConfig: z
10
+ .any()
11
+ .describe('The configuration object for the server. This should not include the top-level "mcpServers" key.'),
12
+ });
13
+ manager;
14
+ constructor(manager) {
15
+ super();
16
+ this.manager = manager;
17
+ }
18
+ async _call({ serverName, serverConfig, }) {
19
+ try {
20
+ this.manager.client.addServer(serverName, serverConfig);
21
+ let result = `Server '${serverName}' added to the client.`;
22
+ logger.debug(`Connecting to new server '${serverName}' and discovering tools.`);
23
+ const session = await this.manager.client.createSession(serverName);
24
+ const connector = session.connector;
25
+ const tools = await this.manager.adapter.createToolsFromConnectors([connector]);
26
+ this.manager.serverTools[serverName] = tools;
27
+ this.manager.initializedServers[serverName] = true;
28
+ this.manager.activeServer = serverName; // Set as active server
29
+ const numTools = tools.length;
30
+ result += ` Session created and connected. '${serverName}' is now the active server with ${numTools} tools available.`;
31
+ result += `\n\n${tools.map(t => t.name).join('\n')}`;
32
+ logger.info(result);
33
+ return result;
34
+ }
35
+ catch (e) {
36
+ logger.error(`Failed to add or connect to server '${serverName}': ${e.message}`);
37
+ return `Failed to add or connect to server '${serverName}': ${e.message}`;
38
+ }
39
+ }
40
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "0.0.8",
4
+ "version": "0.1.0",
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",
@@ -55,13 +55,27 @@
55
55
  "release": "npm version patch --tag-version-prefix=v && git push --follow-tags",
56
56
  "release:minor": "npm version minor --tag-version-prefix=v && git push --follow-tags",
57
57
  "release:major": "npm version major --tag-version-prefix=v && git push --follow-tags",
58
- "prepare": "husky"
58
+ "prepare": "husky",
59
+ "example:airbnb": "npm run build && node dist/examples/airbnb_use.js",
60
+ "example:browser": "npm run build && node dist/examples/browser_use.js",
61
+ "example:chat": "npm run build && node dist/examples/chat_example.js",
62
+ "example:filesystem": "npm run build && node dist/examples/filesystem_use.js",
63
+ "example:http": "npm run build && node dist/examples/http_example.js",
64
+ "example:everything": "npm run build && node dist/examples/mcp_everything.js",
65
+ "example:multi": "npm run build && node dist/examples/multi_server_example.js",
66
+ "example:sandbox": "npm run build && node dist/examples/sandbox_everything.js",
67
+ "example:oauth": "npm run build && node dist/examples/simple_oauth_example.js",
68
+ "example:blender": "npm run build && node dist/examples/blender_use.js",
69
+ "example:add_server": "npm run build && node dist/examples/add_server_tool.js"
59
70
  },
60
71
  "dependencies": {
61
72
  "@dmitryrechkin/json-schema-to-zod": "^1.0.1",
73
+ "@langchain/anthropic": "^0.3.14",
62
74
  "@langchain/community": "0.3.45",
63
75
  "@langchain/core": "0.3.58",
76
+ "@langchain/openai": "^0.5.15",
64
77
  "@modelcontextprotocol/sdk": "1.12.1",
78
+ "dotenv": "^16.5.0",
65
79
  "eventsource": "^3.0.6",
66
80
  "fastembed": "^1.14.4",
67
81
  "langchain": "^0.3.27",
@@ -85,8 +99,10 @@
85
99
  },
86
100
  "lint-staged": {
87
101
  "*.{js,ts}": [
88
- "eslint --fix",
89
- "git add"
102
+ "npm run lint"
103
+ ],
104
+ "**/*.ts": [
105
+ "npm run build"
90
106
  ]
91
107
  }
92
108
  }