mcp-use TypeScript API
    Preparing search index...

    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 BaseMCPClient with platform-specific capabilities:

    • All Connector Types: Supports Stdio, HTTP, and WebSocket connectors
    • Code Execution Mode: Execute code dynamically using VM or E2B sandboxes
    • File System Operations: Load and save configurations from/to files
    • Sampling & Elicitation: Handle advanced MCP protocol features
    • Session Management: Create and manage multiple server connections
    // Basic usage with config file
    const client = new MCPClient('./mcp-config.json');
    const session = await client.createSession('my-server');
    const tools = await session.listTools();
    // With inline configuration
    const client = new MCPClient({
    mcpServers: {
    'filesystem': {
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp']
    }
    }
    });
    // With code execution mode
    const client = new MCPClient('./config.json', {
    codeMode: {
    enabled: true,
    executor: 'e2b',
    executorOptions: { apiKey: process.env.E2B_API_KEY }
    }
    });

    const result = await client.executeCode('console.log("Hello!")');

    MCPSession for session management

    Hierarchy

    • BaseMCPClient
      • MCPClient
    Index
    • 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).

      Parameters

      • 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.

      Returns MCPClient

      // From config file
      const client = new MCPClient('./mcp-config.json');
      // From inline config
      const client = new MCPClient({
      mcpServers: {
      'my-server': {
      command: 'node',
      args: ['server.js']
      }
      }
      });
      // With code mode enabled
      const client = new MCPClient('./config.json', {
      codeMode: true
      });
      // With sampling callback
      const client = new MCPClient('./config.json', {
      onSampling: async (params) => {
      // Call your LLM here
      return anthropic.messages.create(params);
      }
      });
      • fromDict for creating from config object (alternative syntax)
      • fromConfigFile for creating from file (alternative syntax)
    activeSessions: string[] = []

    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.

    console.log(`Active servers: ${client.activeSessions.join(', ')}`);
    
    codeMode: boolean = false

    Indicates whether code execution mode is enabled.

    When true, the client provides special tools for executing code dynamically through the executeCode and searchTools methods.

    if (client.codeMode) {
    const result = await client.executeCode('return 2 + 2');
    console.log(result.output); // "4"
    }
    • 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.

      Parameters

      • name: string

        Unique name for the server

      • serverConfig: ServerConfig

        Server configuration object (connector type, command, args, etc.)

      Returns void

      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:

      1. Shutting down code executors (VM or E2B sandboxes)
      2. Closing all active MCP sessions
      3. Releasing any other held resources

      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.

      Returns Promise<void>

      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.

      Returns Promise<void>

      // 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.

      Parameters

      • serverName: string

        Name of the server whose session should be closed

      Returns Promise<void>

      // 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.

      Parameters

      • serverName: string

        The configured server name.

      Returns Promise<MCPConnection>

    • 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.

      Returns Promise<Record<string, MCPConnection>>

    • 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.

      Parameters

      • autoInitialize: boolean = true

        Whether to automatically initialize each session (default: true)

      Returns Promise<Record<string, MCPConnection>>

      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.

      Parameters

      • serverName: string

        The name of the server as defined in the client configuration

      • autoInitialize: boolean = true

        Whether to automatically initialize the session (default: true)

      Returns Promise<MCPConnection>

      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.

      If the server is not found in the configuration

      // 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.

      Parameters

      • code: string

        JavaScript/TypeScript code to execute

      • Optionaltimeout: number

        Optional execution timeout in milliseconds

      Returns Promise<ExecutionResult>

      Execution result with output, errors, and return value

      If code mode is not enabled

      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.

      Returns Record<string, MCPConnection>

      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.

      Returns MCPClientConfigShape

      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.

      Parameters

      • name: string

        Name of the server

      Returns ServerConfig | undefined

      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.

      Returns string[]

      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.

      Parameters

      • serverName: string

        Name of the server

      Returns MCPConnection | null

      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.

      Parameters

      • name: string

        Name of the server to remove

      Returns Promise<void>

      // 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.

      Parameters

      • serverName: string

        Name of the server

      Returns MCPConnection

      The session instance

      If the session is not found

      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.

      Parameters

      • filepath: string

        Path where the configuration file should be saved

      Returns void

      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.

      Parameters

      • query: string = ""

        Optional search query to filter tools (defaults to empty string for all tools)

      • detailLevel: "names" | "descriptions" | "full" = "full"

        Level of detail to return: "names", "descriptions", or "full"

      Returns Promise<ToolSearchResponse>

      Tool search results with matching tools

      If code mode is not enabled

      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

    • Creates 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.

      Parameters

      • path: string

        Path to the JSON configuration file

      • Optionaloptions: MCPClientOptions

        Optional client behavior configuration

      Returns MCPClient

      New MCPClient instance

      If the file cannot be read or parsed

      const client = MCPClient.fromConfigFile('./mcp-config.json');
      await client.createAllSessions();
      // With code mode
      const client = MCPClient.fromConfigFile('./config.json', {
      codeMode: true
      });
    • Creates a client instance from a configuration dictionary.

      This static factory method provides an alternative syntax for creating a client from an inline configuration object.

      Parameters

      • cfg: Record<string, any>

        Configuration dictionary with server definitions

      • Optionaloptions: MCPClientOptions

        Optional client behavior configuration

      Returns MCPClient

      New MCPClient instance

      const client = MCPClient.fromDict({
      mcpServers: {
      'filesystem': {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp']
      }
      }
      });
    • Gets 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.

      Returns string

      The package version string (e.g., "1.13.2")

      console.log(`mcp-use version: ${MCPClient.getPackageVersion()}`);