Skip to main content
MCPClient stores MCP server configuration and creates MCPSession instances for live connections. Use the client to add or remove servers, open sessions, manage lifecycle, handle client-side callbacks, and enable code mode.
import { MCPClient } from "mcp-use";
// or import { MCPClient } from "mcp-use/client";
In browser bundles, import from mcp-use/browser. The browser entry exports BrowserMCPClient as MCPClient; it supports HTTP servers only and inherits the same session-management methods.
import { MCPClient } from "mcp-use/browser";
A minimal Node.js client:
import { MCPClient } from "mcp-use";

const client = new MCPClient({
  mcpServers: {
    filesystem: {
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
    },
  },
});

const session = await client.createSession("filesystem");
const tools = await session.listTools();

await client.close();

Constructor

Creates a Node.js MCP client. The constructor accepts an inline config object, a path to a JSON config file, or no config. Servers can also be added later with addServer(). Parameters
config
string | MCPClientConfigShape | undefined
default:"undefined"
Inline client configuration, path to a JSON config file, or omitted for an empty client.
options
MCPClientOptions | undefined
default:"undefined"
Client behavior options such as code mode, sampling, elicitation, and notification callbacks.
Signature
constructor(
  config?: string | Record<string, any>,
  options?: MCPClientOptions
)

Static methods

fromDict

Creates an MCPClient from an inline configuration object. Parameters
cfg
Record<string, any>
required
Client configuration with an optional mcpServers map.
options
MCPClientOptions | undefined
default:"undefined"
Client behavior options.
Returns
returns
MCPClient
Example
const client = MCPClient.fromDict({
  mcpServers: {
    api: { url: "https://example.com/mcp" },
  },
});
Signature
static fromDict(
  cfg: Record<string, any>,
  options?: MCPClientOptions
): MCPClient

fromConfigFile

Loads a JSON config file and creates an MCPClient. Parameters
path
string
required
Path to the JSON configuration file.
options
MCPClientOptions | undefined
default:"undefined"
Client behavior options.
Returns
returns
MCPClient
Signature
static fromConfigFile(path: string, options?: MCPClientOptions): MCPClient

getPackageVersion

Returns the installed mcp-use package version. Returns
returns
string
Signature
static getPackageVersion(): string

Session methods

createSession

Creates a new MCPSession for a configured server. If a session already exists for the same server name, the new session replaces it. Parameters
serverName
string
required
Name of the server in config.mcpServers.
autoInitialize
boolean
default:"true"
When true, connects and runs the MCP initialize handshake before resolving.
Returns
returns
Promise<MCPSession>
Throws Throws Error when serverName is not found in the config. Example
const session = await client.createSession("api");
const result = await session.callTool("search", { query: "docs" });
Signature
createSession(serverName: string, autoInitialize?: boolean): Promise<MCPSession>

createAllSessions

Creates sessions for every configured server. Sessions are opened sequentially. Parameters
autoInitialize
boolean
default:"true"
When true, connects and initializes each session before resolving.
Returns
returns
Promise<Record<string, MCPSession>>
Signature
createAllSessions(autoInitialize?: boolean): Promise<Record<string, MCPSession>>

getSession

Returns an existing session or null when the session has not been created. Parameters
serverName
string
required
Name of the server session to retrieve.
Returns
returns
MCPSession | null
Signature
getSession(serverName: string): MCPSession | null

requireSession

Returns an existing session and throws when the session is missing. Parameters
serverName
string
required
Name of the server session to retrieve.
Returns
returns
MCPSession
Throws Throws Error with the available session names when no session exists for serverName. Signature
requireSession(serverName: string): MCPSession

getAllActiveSessions

Returns the active sessions as a map keyed by server name. Returns
returns
Record<string, MCPSession>
Signature
getAllActiveSessions(): Record<string, MCPSession>

closeSession

Disconnects one active session and removes it from the active session list. Calling this method for a missing session logs a warning and resolves. Parameters
serverName
string
required
Name of the session to close.
Returns
returns
Promise<void>
Signature
closeSession(serverName: string): Promise<void>

closeAllSessions

Closes every active session. Errors are logged and remaining sessions continue closing. Returns
returns
Promise<void>
Signature
closeAllSessions(): Promise<void>

close

Closes the client. This cleans up any code executor first, then closes all active sessions. Prefer this for application shutdown. Returns
returns
Promise<void>
Example
process.on("SIGINT", async () => {
  await client.close();
  process.exit(0);
});
Signature
close(): Promise<void>

Configuration methods

addServer

Adds or replaces a server configuration. The server can be used by createSession() after it is added. Parameters
name
string
required
Unique server name.
serverConfig
ServerConfig
required
Server transport configuration.
Returns
returns
void
Example
client.addServer("weather", {
  url: "https://weather.example.com/mcp",
  headers: { Authorization: `Bearer ${process.env.WEATHER_TOKEN}` },
});
Signature
addServer(name: string, serverConfig: Record<string, any>): void

removeServer

Removes a server configuration and removes the server name from activeSessions. Close the session first when you need to disconnect the transport. Parameters
name
string
required
Server name to remove.
Returns
returns
void
Signature
removeServer(name: string): void

getServerNames

Returns configured server names. In Node.js code mode, the internal code_mode server is excluded. Returns
returns
string[]
Signature
getServerNames(): string[]

getServerConfig

Returns the configuration for a single server. Parameters
name
string
required
Server name.
Returns
returns
Record<string, any> | undefined
Signature
getServerConfig(name: string): Record<string, any>

getConfig

Returns the complete client configuration. Returns
returns
Record<string, any>
Signature
getConfig(): Record<string, any>

saveConfig

Writes the current client configuration to a JSON file. This method is only available on the Node.js MCPClient. Parameters
filepath
string
required
Destination file path. Missing parent directories are created.
Returns
returns
void
Signature
saveConfig(filepath: string): void

Code mode methods

executeCode

Executes JavaScript or TypeScript code with access to connected MCP tools. This method is only available when options.codeMode is enabled. Parameters
code
string
required
Code to execute.
timeout
number | undefined
default:"undefined"
Execution timeout in milliseconds.
Returns
returns
Promise<ExecutionResult>
Throws Throws Error when code mode is not enabled. Signature
executeCode(code: string, timeout?: number): Promise<ExecutionResult>

searchTools

Searches tools across active MCP sessions. This method is only available when options.codeMode is enabled. Parameters
query
string
default:"\"\""
Search query. Empty string returns all tools.
detailLevel
"names" | "descriptions" | "full"
default:"\"full\""
Amount of tool detail to return.
Returns
returns
Promise<ToolSearchResponse>
Throws Throws Error when code mode is not enabled. Signature
searchTools(
  query?: string,
  detailLevel?: "names" | "descriptions" | "full"
): Promise<ToolSearchResponse>

Types

MCPClientConfigShape

Top-level client configuration. The mcpServers map holds named server configs. Root callback fields and clientInfo are used as defaults when a server config omits them. Fields
mcpServers
Record<string, ServerConfig>
Optional map of server names to transport configs.
clientInfo
ClientInfo
Optional default client metadata sent during initialization.
onSampling
OnSamplingCallback
Optional default callback for server sampling requests.
onElicitation
OnElicitationCallback
Optional default callback for server elicitation requests.
onNotification
OnNotificationCallback
Optional default callback for server notifications.
Signature
interface MCPClientConfigShape {
  clientInfo?: ClientInfo;
  mcpServers?: Record<string, ServerConfig>;
  onSampling?: OnSamplingCallback;
  onElicitation?: OnElicitationCallback;
  onNotification?: OnNotificationCallback;
  /** @deprecated Use onSampling. */
  samplingCallback?: OnSamplingCallback;
  /** @deprecated Use onElicitation. */
  elicitationCallback?: OnElicitationCallback;
}

ServerConfig

Transport configuration for one MCP server. Node.js clients support HTTP and Standard I/O configs. Browser clients support HTTP configs only. Fields
url
string
HTTP or SSE MCP endpoint URL.
headers
Record<string, string>
Optional request headers for HTTP servers.
authToken
string
Bearer token for HTTP servers.
authProvider
unknown
Optional SDK-compatible auth provider.
transport
"http" | "sse"
Optional transport preference. Defaults to streamable HTTP with SSE fallback.
preferSse
boolean
Prefer SSE transport when connecting.
disableSseFallback
boolean
Disable automatic SSE fallback for streamable HTTP.
command
string
Stdio command for Node.js clients.
args
string[]
Stdio arguments for Node.js clients.
env
Record<string, string>
Optional environment variables for Standard I/O servers.
Signature
type ServerConfig = HttpServerConfig | StdioServerConfig;

MCPClientOptions

Options passed as the second constructor argument. These values are global defaults. Per-server callback fields override them. Fields
codeMode
boolean | CodeModeConfig
Enable code execution mode.
onSampling
OnSamplingCallback
Handle sampling/createMessage requests from servers.
onElicitation
OnElicitationCallback
Handle elicitation/create requests from servers.
onNotification
OnNotificationCallback
Handle server notifications when a server config does not provide its own handler.
samplingCallback
OnSamplingCallback
Deprecated alias for onSampling.
elicitationCallback
OnElicitationCallback
Deprecated alias for onElicitation.
Signature
interface MCPClientOptions {
  codeMode?: boolean | CodeModeConfig;
  onSampling?: OnSamplingCallback;
  samplingCallback?: OnSamplingCallback;
  onElicitation?: OnElicitationCallback;
  elicitationCallback?: OnElicitationCallback;
  onNotification?: OnNotificationCallback;
}

CodeModeConfig

Advanced code execution configuration. Fields
enabled
boolean
Enable or disable code mode.
executor
"vm" | "e2b" | CodeExecutorFunction | BaseCodeExecutor
Executor implementation. Defaults to "vm".
executorOptions
VMExecutorOptions | E2BExecutorOptions
Executor-specific options.
Signature
interface CodeModeConfig {
  enabled: boolean;
  executor?: "vm" | "e2b" | CodeExecutorFunction | BaseCodeExecutor;
  executorOptions?: VMExecutorOptions | E2BExecutorOptions;
}

ExecutionResult

Result returned by executeCode(). Fields
result
unknown
Return value from the executed code.
logs
string[]
Console output captured during execution.
error
string | null
Error message when execution failed, otherwise null.
execution_time
number
Execution duration in seconds.

Usage

Use an initialized session for MCP protocol calls:
import { MCPClient } from "mcp-use";

const client = new MCPClient({
  mcpServers: {
    demo: { url: "http://localhost:3000/mcp" },
  },
});

try {
  const session = await client.createSession("demo");
  const tools = await session.listTools();
  console.log(tools.map((tool) => tool.name));
} finally {
  await client.close();
}
Handle sampling and elicitation with global defaults:
import { acceptWithDefaults, MCPClient } from "mcp-use";

const client = new MCPClient(
  {
    mcpServers: {
      assistant: { url: "https://assistant.example.com/mcp" },
    },
  },
  {
    onSampling: async (params) => {
      return callYourModel(params);
    },
    onElicitation: async (params) => {
      return acceptWithDefaults(params);
    },
  }
);
Enable code mode with the default VM executor:
const client = new MCPClient("./mcp-config.json", {
  codeMode: true,
});

const result = await client.executeCode(`
  const tools = await searchTools("file", "descriptions");
  return tools.meta.result_count;
`);
  • MCPSession: live MCP protocol calls for tools, resources, prompts, roots, and notifications.
  • MCP Client overview: choose the right client entry point and make a first tool call.
  • Code mode: guide to code execution mode and executors.
  • Sampling: guide to handling server sampling requests.
  • Elicitation: guide to handling user input requests.