mcp-use TypeScript API
    Preparing search index...

    Browser-compatible MCP client for HTTP servers.

    Hierarchy

    • BaseMCPClient
      • MCPClient
    Index
    • Creates a browser MCP client.

      Parameters

      • Optionalconfig: Record<string, any>

        Client configuration containing an optional mcpServers map.

      Returns MCPClient

    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(', ')}`);
    
    • 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');
    • Close every active MCP connection.

      Returns Promise<void>

    • 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();
    • 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.

      Returns string[]

      Array of server names defined in the configuration

      const serverNames = client.getServerNames();
      console.log(`Configured servers: ${serverNames.join(', ')}`);

      // Create sessions for all servers
      for (const name of serverNames) {
      await client.createSession(name);
      }

      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);
      }
    • Creates a browser client from an inline configuration object.

      Parameters

      • cfg: Record<string, any>

        Client configuration containing an optional mcpServers map.

      Returns MCPClient

      A browser client initialized with cfg.

    • Returns the installed @mcp-use/client package version.

      Returns string

      The package version string.