Creates a new MCPClient instance.
The client can be initialized with either a configuration object, a path to a configuration file, or no configuration at all (servers can be added later using addServer).
Optionalconfig: string | Record<string, any>
Configuration object or path to JSON config file. If omitted, starts with empty configuration
Optionaloptions: MCPClientOptions
Optional client behavior configuration Options can enable code mode or provide sampling and elicitation callbacks.
// From inline config
const client = new MCPClient({
mcpServers: {
'my-server': {
command: 'node',
args: ['server.js']
}
}
});
// With sampling callback
const client = new MCPClient('./config.json', {
onSampling: async (params) => {
// Call your LLM here
return anthropic.messages.create(params);
}
});
List of server names that have active sessions. This array is kept in sync with the sessions map and can be used to iterate over active connections.
Indicates whether code execution mode is enabled.
When true, the client provides special tools for executing code dynamically through the executeCode and searchTools methods.
Adds a new MCP server configuration to the client.
This method adds or updates a server configuration dynamically without needing to restart the client. The server can then be used to create new sessions.
Unique name for the server
Server configuration object (connector type, command, args, etc.)
client.addServer('new-server', {
command: 'python',
args: ['server.py']
});
// Now you can create a session
const session = await client.createSession('new-server');
Closes the client and cleans up all resources.
This method performs a complete cleanup by:
Always call this method when you're done with the client to ensure proper resource cleanup, especially when using E2B sandboxes which have associated costs.
const client = new MCPClient('./config.json', { codeMode: true });
await client.createAllSessions();
// Do work...
// Clean up
await client.close();
// Use in shutdown handler
process.on('SIGINT', async () => {
console.log('Shutting down...');
await client.close();
process.exit(0);
});
closeAllSessions for closing just the sessions
Closes all active sessions and cleans up their resources.
This method iterates through all sessions and attempts to close each one gracefully. If any session fails to close, the error is logged but the method continues to close remaining sessions.
This is particularly useful for cleanup on application shutdown.
// Clean shutdown
try {
await client.closeAllSessions();
console.log('All sessions closed successfully');
} catch (error) {
console.error('Error during cleanup:', error);
}
// Use in application shutdown handler
process.on('SIGINT', async () => {
console.log('Shutting down...');
await client.closeAllSessions();
process.exit(0);
});
Closes a session and cleans up its resources.
This method gracefully disconnects from the server and removes the session from the active sessions list. It's safe to call even if the session doesn't exist.
Name of the server whose session should be closed
// Close a specific session
await client.closeSession('my-server');
// Verify it's closed
console.log(client.activeSessions.includes('my-server')); // false
Connect to a configured MCP server and return a ready, protocol-neutral connection.
The returned connection represents either a legacy sessionful server or a modern sessionless server uniformly. Inspect MCPConnection.info for the negotiated protocol version and normalized server metadata.
The configured server name.
Connect to every configured server sequentially.
Each result uses the same MCPConnection API regardless of whether the negotiated protocol is legacy/sessionful or modern/sessionless.
Creates sessions for all configured MCP servers.
This is a convenience method that iterates through all servers in the configuration and creates a session for each one. Sessions are created sequentially to avoid overwhelming the system.
Whether to automatically initialize each session (default: true)
A promise that resolves to a map of server names to sessions
// Create sessions for all configured servers
const sessions = await client.createAllSessions();
console.log(`Created ${Object.keys(sessions).length} sessions`);
// List tools from all servers
for (const [name, session] of Object.entries(sessions)) {
const tools = await session.listTools();
console.log(`${name}: ${tools.length} tools`);
}
Creates a new session for connecting to an MCP server.
The name of the server as defined in the client configuration
Whether to automatically initialize the session (default: true)
A promise that resolves to the created MCPSession instance
Use connect; modern MCP servers are sessionless.
This method initializes a connection to the specified server using the configuration provided during client construction. Sessions manage the lifecycle of connections and provide methods for calling tools, listing resources, and more.
If a session already exists for the server, it will be replaced with a new one.
// Create and initialize a session
const session = await client.createSession('my-server');
const tools = await session.listTools();
// Create without auto-initialization
const session = await client.createSession('my-server', false);
await session.connect();
await session.initialize();
Executes JavaScript/TypeScript code in a sandboxed environment.
This method is only available when code mode is enabled. It executes the provided code in an isolated environment (VM or E2B sandbox) and returns the results including stdout, stderr, and return value.
JavaScript/TypeScript code to execute
Optionaltimeout: number
Optional execution timeout in milliseconds
Execution result with output, errors, and return value
const client = new MCPClient('./config.json', { codeMode: true });
const result = await client.executeCode(`
console.log('Hello, world!');
return 2 + 2;
`);
console.log(result.stdout); // "Hello, world!\n"
console.log(result.returnValue); // 4
// With timeout
try {
const result = await client.executeCode('while(true) {}', 1000);
} catch (error) {
console.log('Execution timed out');
}
searchTools for discovering available tools in code mode
Gets all active sessions as a map of server names to sessions.
Map of server names to their active sessions
const sessions = client.getAllActiveSessions();
// Iterate over all active sessions
for (const [name, session] of Object.entries(sessions)) {
console.log(`Server: ${name}`);
const tools = await session.listTools();
console.log(` Tools: ${tools.length}`);
}
Gets the complete client configuration.
Complete configuration object including all server definitions
const config = client.getConfig();
console.log(`Total servers: ${Object.keys(config.mcpServers).length}`);
getServerConfig for retrieving individual server configurations
Gets the configuration for a specific MCP server.
Name of the server
Server configuration object, or undefined if not found
const config = client.getServerConfig('my-server');
if (config) {
console.log(`Command: ${config.command}`);
console.log(`Args: ${config.args.join(' ')}`);
}
getConfig for retrieving the entire configuration
Gets the names of all configured MCP servers (excluding internal servers).
This method overrides the base implementation to filter out internal meta-servers like the code mode server, which is an implementation detail not intended for direct user interaction.
Array of user-configured server names
const names = client.getServerNames();
console.log(`User servers: ${names.join(', ')}`);
// Note: 'code_mode' is excluded even if code mode is enabled
activeSessions for servers with active sessions
Retrieves an existing session by server name.
This method returns null if no session exists, making it safe for checking session existence without throwing errors.
Name of the server
The session instance or null if not found
const session = client.getSession('my-server');
if (session) {
const tools = await session.listTools();
} else {
console.log('Session not found, creating...');
await client.createSession('my-server');
}
Removes an MCP server configuration from the client.
This method removes a server configuration and cleans up any active sessions associated with that server. If there's an active session, it will be removed from the active sessions list.
Name of the server to remove
// Remove a server configuration
await client.removeServer('old-server');
// The server name will no longer appear in getServerNames()
console.log(client.getServerNames()); // 'old-server' is gone
Retrieves an existing session by server name, throwing if not found.
This method is useful when you need to ensure a session exists before proceeding. It throws a descriptive error if the session is not found.
Name of the server
The session instance
try {
const session = client.requireSession('my-server');
const tools = await session.listTools();
} catch (error) {
console.error('Session not found:', error.message);
}
Saves the current configuration to a file.
This Node.js-specific method writes the client's current configuration (including all server definitions) to a JSON file. The directory will be created if it doesn't exist.
Path where the configuration file should be saved
const client = new MCPClient();
client.addServer('my-server', {
command: 'node',
args: ['server.js']
});
// Save configuration for later use
client.saveConfig('./mcp-config.json');
fromConfigFile for loading configurations
Searches for available tools across all MCP servers.
This method is only available when code mode is enabled. It searches through tools from all active servers and returns matching tools based on the query and detail level.
Optional search query to filter tools (defaults to empty string for all tools)
Level of detail to return: "names", "descriptions", or "full"
Tool search results with matching tools
const client = new MCPClient('./config.json', { codeMode: true });
await client.createAllSessions();
// Search for all tools
const allTools = await client.searchTools();
console.log(`Found ${allTools.tools.length} tools`);
// Search for specific tools
const fileTools = await client.searchTools('file', 'descriptions');
executeCode for executing code in code mode
StaticfromCreates a client instance from a configuration file.
This static factory method loads MCP server configurations from a JSON file and creates a new client instance.
Path to the JSON configuration file
Optionaloptions: MCPClientOptions
Optional client behavior configuration
New MCPClient instance
StaticfromCreates a client instance from a configuration dictionary.
This static factory method provides an alternative syntax for creating a client from an inline configuration object.
Configuration dictionary with server definitions
Optionaloptions: MCPClientOptions
Optional client behavior configuration
New MCPClient instance
const client = MCPClient.fromDict({
mcpServers: {
'filesystem': {
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp']
}
}
});
StaticgetGets the mcp-use package version.
This static method returns the version string of the installed mcp-use package, which is useful for debugging and compatibility checks.
The package version string (e.g., "1.13.2")
Node.js-specific MCP client implementation with advanced features.
The MCPClient class provides a complete MCP client implementation for Node.js environments, extending the runtime-neutral
BaseMCPClientwith platform-specific capabilities:Example
Example
Example
See
MCPSession for session management