Documentation Index
Fetch the complete documentation index at: https://docs.mcp-use.com/llms.txt
Use this file to discover all available pages before exploring further.
View the source code for this module on GitHub: https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp_use/client/client.py
MCPClient
from mcp_use.client.client import MCPClient
method init
Initialize a new MCP client.ParametersSignatureEither a dict containing configuration or a path to a JSON config file.Server name or configurationWhether to use sandboxed execution mode for running MCP servers.Optional sandbox configuration options.Optional sampling callback function.Callback functionParameter valueCallback functionMiddleware instanceOptional list of Root objects to advertise to servers.Optional custom callback for roots/list requests.Whether to enable code execution mode for tools.Boolean flag
def __init__(config: str | dict[str, typing.Any] | None = None, allowed_servers: list[str] | None = None, sandbox: bool = False, sandbox_options: mcp_use.client.connectors.sandbox.SandboxOptions | None = None, sampling_callback: mcp.client.session.SamplingFnT | None = None, elicitation_callback: mcp.client.session.ElicitationFnT | None = None, message_handler: mcp.client.session.MessageHandlerFnT | None = None, logging_callback: mcp.client.session.LoggingFnT | None = None, middleware: list[mcp_use.client.middleware.middleware.Middleware] | None = None, roots: list[mcp.types.Root] | None = None, list_roots_callback: mcp.client.session.ListRootsFnT | None = None, code_mode: bool = False, verify: bool | None = True):
method close_all_sessions
Close all active sessions.This method ensures all sessions are closed even if some fail.Signaturedef close_all_sessions():
method create_all_sessions
Create sessions for all configured servers.ParametersReturnsWhether to automatically initialize the sessions.
SignatureDictionary mapping server names to their MCPSession instances.
def create_all_sessions(auto_initialize: bool = True):
method create_session
Create a session for the specified server.ParametersReturnsThe name of the server to create a session for.Whether to automatically initialize the session.
SignatureThe created MCPSession.
def create_session(server_name: str, auto_initialize: bool = True):
method execute_code
Execute Python code with access to MCP tools (code mode).This method allows agents to interact with MCP tools through Python code
instead of direct tool calls, enabling more efficient context usage and
data processing.Example:client = MCPClient(config="config.json", code_mode=True)
await client.create_all_sessions()
result = await client.execute_code('''
tools = await search_tools("github")
print(f"Found \{len(tools)\} tools")
pr = await github.get_pull_request(
owner="facebook",
repo="react",
number=12345
)
return \{"title": pr["title"]\}
''')
print(result['result']) # \{'title': 'Fix bug in...'\}
print(result['logs']) # ['Found 5 tools']
ReturnsPython code to execute with tool access.Execution timeout in seconds.
Signature
def execute_code(code: str, timeout: float = 30.0):
method search_tools
Search available MCP tools across all active sessions.Example:# Search for GitHub-related tools
result = await client.search_tools("github pull")
print(f"Found \{result['meta']['result_count']\} tools out of \{result['meta']['total_tools']\} total")
for tool in result['results']:
print(f"\{tool['server']\}.\{tool['name']\}: \{tool['description']\}")
ReturnsSearch query to filter tools by name or description.Level of detail to return:
SignatureLevel of detail to return: - “names”: Only tool names and server - “descriptions”: Names, server, and descriptions - “full”: Complete tool information including schemas
def search_tools(query: str = "", detail_level: str = "full"):