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.
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.
A minimal Node.js client:

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

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
Signature

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

getPackageVersion

Returns the installed mcp-use package version. Returns
returns
string
Signature

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
Signature

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

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

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

getAllActiveSessions

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

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

closeAllSessions

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

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
Signature

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
Signature

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

getServerNames

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

getServerConfig

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

getConfig

Returns the complete client configuration. Returns
returns
Record<string, any>
Signature

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

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

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

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

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

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

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

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:
Handle sampling and elicitation with global defaults:
Enable code mode with the default VM executor:
  • 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.