Skip to main content

Quick Start

from mcp_use import MCPClient

# From config file
client = MCPClient("config.json")

# From dictionary
client = MCPClient({
    "mcpServers": {
        "playwright": {
            "command": "npx",
            "args": ["@playwright/mcp@latest"]
        }
    }
})

# Create sessions and use
await client.create_all_sessions()
session = client.get_session("playwright")
tools = await session.list_tools()

# Clean up when done
await client.close_all_sessions()

MCPClient Parameters

MCPClient is the main entry point for connecting to MCP servers. It provides flexible configuration for SSL, sandboxing, middleware, and server-initiated callbacks.

MCPClient Constructor Parameters

config
str | dict | None
default:"None"
Path to a JSON configuration file or a configuration dictionary containing server definitions
allowed_servers
list[str] | None
default:"None"
Restrict which servers from the config to use. When set, only the specified servers will be available
verify
bool | None
default:"True"
SSL certificate verification for HTTP/HTTPS servers. Set to False for self-signed certificates or internal servers
sandbox
bool
default:"False"
Run MCP servers in an isolated E2B sandbox environment. See Sandbox for configuration
sandbox_options
SandboxOptions | None
default:"None"
E2B sandbox configuration including api_key and sandbox_template_id. Required when sandbox=True. See Sandbox
code_mode
bool
default:"False"
Enable Python code execution mode for interacting with MCP tools programmatically. See Code Mode
middleware
list[Middleware] | None
default:"None"
Custom middleware for intercepting and processing tool calls. See Middleware
roots
list[Root] | None
default:"None"
Directories or files to advertise to servers. Roots inform servers about accessible filesystem locations. See Roots
list_roots_callback
ListRootsFnT | None
default:"None"
Custom callback to handle roots/list requests from servers. Overrides the static roots parameter with dynamic responses
sampling_callback
SamplingFnT | None
default:"None"
Handle server-initiated sampling requests (LLM completions). Required for servers that use sampling. See Sampling
elicitation_callback
ElicitationFnT | None
default:"None"
Handle server requests for user input or decisions. See Elicitation
message_handler
MessageHandlerFnT | None
default:"None"
Handle server notifications and messages. See Notifications
logging_callback
LoggingFnT | None
default:"None"
Handle server log messages. See Logging

Server Configuration

MCP servers are configured in the mcpServers object. Each server has a unique name and connection settings.

STDIO Servers (Local)

Servers that run as local processes:
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"],
      "env": {"DISPLAY": ":1"}
    }
  }
}
FieldRequiredDescription
commandYesExecutable to run (npx, python, etc.)
argsNoArguments to pass to the command
envNoEnvironment variables for the process

HTTP Servers (Remote)

Servers accessible via HTTP/HTTPS:
{
  "mcpServers": {
    "remote_server": {
      "url": "https://api.example.com/mcp",
      "headers": {"Authorization": "Bearer token123"}
    }
  }
}
FieldRequiredDescription
urlYesServer URL (supports SSE and Streamable HTTP)
headersNoHTTP headers for authentication
timeoutNoConnection timeout in seconds (default: 5)
sse_read_timeoutNoSSE read timeout in seconds (default: 300)
authNoAuthentication config (see Authentication)

WebSocket Servers

Servers accessible via WebSocket:
{
  "mcpServers": {
    "ws_server": {
      "ws_url": "wss://api.example.com/mcp",
      "headers": {"Authorization": "Bearer token123"}
    }
  }
}
FieldRequiredDescription
ws_urlYesWebSocket URL
headersNoHTTP headers for the upgrade request
authNoBearer token string

Multiple Servers

Configure multiple servers for different capabilities:
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"]
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {"GITHUB_TOKEN": "ghp_..."}
    }
  }
}
client = MCPClient("config.json")
await client.create_all_sessions()

# Access specific server
playwright = client.get_session("playwright")
github = client.get_session("github")
See Multi-Server Setup for details.

Alternative Constructors

from_dict

client = MCPClient.from_dict(
    config={"mcpServers": {...}},
    verify=False,
    sandbox=True
)

from_config_file

client = MCPClient.from_config_file(
    filepath="config.json",
    verify=False,
    sandbox=True
)
Both accept the same parameters as MCPClient().

Common Issues

ErrorCauseSolution
Server 'x' not foundServer name not in configCheck spelling, verify config file
SSL certificate errorSelf-signed cert or internal serverSet verify=False
Connection timeoutServer not running or unreachableCheck server URL/command, network
Permission deniedMissing permissions for commandCheck file permissions, PATH