> ## Documentation Index
> Fetch the complete documentation index at: https://mcp-use.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

<AgentInstructions>

## Submitting Feedback

If you encounter incorrect, outdated, or confusing documentation on this page, submit feedback:

POST https://mcp-use.com/docs/feedback

```json
{
  "path": "/python/api-reference/mcp_use_client_client",
  "feedback": "Description of the issue"
}
```

Only submit feedback when you have something specific and actionable to report.

</AgentInstructions>

# Client

> Client for managing MCP servers and sessions API Documentation

export const RandomGradientBackground = ({className, color, children, grayscaled = false}) => {
  const saturation = useMemo(() => {
    if (color) {
      const values = color.split("(")[1].split(")")[0].trim().split(/\s+/);
      return parseFloat(values[1] || "0");
    }
    return grayscaled ? 0 : 0.2;
  }, [color, grayscaled]);
  const lightness = useMemo(() => {
    if (color) {
      const values = color.split("(")[1].split(")")[0].trim().split(/\s+/);
      return parseFloat(values[0] || "0.5");
    }
    return grayscaled ? 0.3 : 0.4;
  }, [color, grayscaled]);
  const randomHue = useMemo(() => {
    if (color) {
      const values = color.split("(")[1].split(")")[0].trim().split(/\s+/);
      return parseFloat(values[2] || "0");
    }
    return Math.floor(Math.random() * 360);
  }, [color]);
  const randomColor = useMemo(() => {
    if (color) {
      return color;
    }
    return `oklch(${Math.min(lightness, 1)} ${saturation} ${randomHue})`;
  }, [randomHue, saturation, lightness]);
  const lightColor = useMemo(() => {
    return `oklch(${Math.min(lightness * 2, 1)} ${saturation} ${randomHue})`;
  }, [randomHue, saturation, lightness, color]);
  const direction = useMemo(() => {
    return Math.floor(Math.random() * 360);
  }, [randomHue]);
  const brightnessFilter = useMemo(() => {
    return "1000%";
  }, []);
  return <div className={`relative overflow-hidden ${className || ""}`} style={{
    background: `${lightColor}`,
    minHeight: '100%',
    width: '100%'
  }}>
      <div className="absolute inset-0 w-full h-full" style={{
    background: `linear-gradient(${direction}deg, ${randomColor}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,
    filter: `contrast(120%) brightness(${brightnessFilter})`,
    backgroundSize: 'cover',
    backgroundRepeat: 'no-repeat'
  }} />
      {children && <div className="relative z-10 w-full h-full">{children}</div>}
    </div>;
};

<Callout type="info" title="Source Code">
  View the source code for this module on GitHub: <a href="https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp_use/client/client.py" target="_blank" rel="noopener noreferrer">[https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp\_use/client/client.py](https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp_use/client/client.py)</a>
</Callout>

Client for managing MCP servers and sessions.

This module provides a high-level client that manages MCP servers, connectors,
and sessions from configuration.

## MCPClient

<div>
  <RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
    <div className="text-black">
      <div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> MCPClient</div>

      Client for managing MCP servers and sessions.

      This class provides a unified interface for working with MCP servers,
      handling configuration, connector creation, and session management.
    </div>
  </RandomGradientBackground>

  ```python theme={null}
  from mcp_use.client.client import MCPClient
  ```

  <Card type="info">
    ### `method` **init**

    Initialize a new MCP client.

    **Parameters**

    > <ParamField body="config" type="str | dict[str, typing.Any] | None" default="None">   Either a dict containing configuration or a path to a JSON config file. </ParamField>
    > <ParamField body="allowed_servers" type="list[str] | None" default="None">   Server name or configuration </ParamField>
    > <ParamField body="sandbox" type="bool" default="False">   Whether to use sandboxed execution mode for running MCP servers. </ParamField>
    > <ParamField body="sandbox_options" type="mcp_use.client.connectors.sandbox.SandboxOptions | None" default="None">   Optional sandbox configuration options. </ParamField>
    > <ParamField body="sampling_callback" type="mcp.client.session.SamplingFnT | None" default="None">   Optional sampling callback function. </ParamField>
    > <ParamField body="elicitation_callback" type="mcp.client.session.ElicitationFnT | None" default="None">   Callback function </ParamField>
    > <ParamField body="message_handler" type="mcp.client.session.MessageHandlerFnT | None" default="None">   Parameter value </ParamField>
    > <ParamField body="logging_callback" type="mcp.client.session.LoggingFnT | None" default="None">   Callback function </ParamField>
    > <ParamField body="middleware" type="list[mcp_use.client.middleware.middleware.Middleware] | None" default="None">   Middleware instance </ParamField>
    > <ParamField body="roots" type="list[mcp.types.Root] | None" default="None">   Optional list of Root objects to advertise to servers. </ParamField>
    > <ParamField body="list_roots_callback" type="mcp.client.session.ListRootsFnT | None" default="None">   Optional custom callback for roots/list requests. </ParamField>
    > <ParamField body="code_mode" type="bool" default="False">   Whether to enable code execution mode for tools. </ParamField>
    > <ParamField body="verify" type="bool | None" default="True">   Boolean flag </ParamField>

    **Signature**

    ```python wrap theme={null}
    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):
    ```
  </Card>

  <Card type="info">
    ### `method` add\_middleware

    Add a middleware.

    **Parameters**

    > <ParamField body="middleware" type="mcp_use.client.middleware.middleware.Middleware" required="True">   The middleware to add </ParamField>

    **Signature**

    ```python wrap theme={null}
    def add_middleware(middleware: mcp_use.client.middleware.middleware.Middleware):
    ```
  </Card>

  <Card type="info">
    ### `method` add\_server

    Add a server configuration.

    **Parameters**

    > <ParamField body="name" type="str" required="True">   The name to identify this server. </ParamField>
    > <ParamField body="server_config" type="dict[str, Any]" required="True">   The server configuration. </ParamField>

    **Signature**

    ```python wrap theme={null}
    def add_server(name: str, server_config: dict[str, Any]):
    ```
  </Card>

  <Card type="info">
    ### `method` close\_all\_sessions

    Close all active sessions.

    This method ensures all sessions are closed even if some fail.

    **Signature**

    ```python wrap theme={null}
    def close_all_sessions():
    ```
  </Card>

  <Card type="info">
    ### `method` close\_session

    Close a session.

    **Parameters**

    > <ParamField body="server_name" type="str" required="True">   The name of the server to close the session for. </ParamField>

    **Signature**

    ```python wrap theme={null}
    def close_session(server_name: str):
    ```
  </Card>

  <Card type="info">
    ### `method` create\_all\_sessions

    Create sessions for all configured servers.

    **Parameters**

    > <ParamField body="auto_initialize" type="bool" default="True">   Whether to automatically initialize the sessions. </ParamField>

    **Returns**

    > <ResponseField name="returns" type="dict[str, mcp_use.client.session.MCPSession]">Dictionary mapping server names to their MCPSession instances.</ResponseField>

    **Signature**

    ```python wrap theme={null}
    def create_all_sessions(auto_initialize: bool = True):
    ```
  </Card>

  <Card type="info">
    ### `method` create\_session

    Create a session for the specified server.

    **Parameters**

    > <ParamField body="server_name" type="str" required="True">   The name of the server to create a session for. </ParamField>
    > <ParamField body="auto_initialize" type="bool" default="True">   Whether to automatically initialize the session. </ParamField>

    **Returns**

    > <ResponseField name="returns" type="mcp_use.client.session.MCPSession | None">The created MCPSession.</ResponseField>

    **Signature**

    ```python wrap theme={null}
    def create_session(server_name: str, auto_initialize: bool = True):
    ```
  </Card>

  <Card type="info">
    ### `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:

    ```python theme={null}
    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']
    ```

    **Parameters**

    > <ParamField body="code" type="str" required="True">   Python code to execute with tool access. </ParamField>
    > <ParamField body="timeout" type="float" default="30.0">   Execution timeout in seconds. </ParamField>

    **Returns**

    >     <ResponseField name="returns" type="dict[str, Any]" />

    **Signature**

    ```python wrap theme={null}
    def execute_code(code: str, timeout: float = 30.0):
    ```
  </Card>

  <Card type="info">
    ### `method` get\_all\_active\_sessions

    Get all active sessions.

    **Returns**

    > <ResponseField name="returns" type="dict[str, mcp_use.client.session.MCPSession]">Dictionary mapping server names to their MCPSession instances.</ResponseField>

    **Signature**

    ```python wrap theme={null}
    def get_all_active_sessions():
    ```
  </Card>

  <Card type="info">
    ### `method` get\_server\_names

    Get the list of configured server names.

    **Returns**

    > <ResponseField name="returns" type="list[str]">List of server names (excludes internal code mode server).</ResponseField>

    **Signature**

    ```python wrap theme={null}
    def get_server_names():
    ```
  </Card>

  <Card type="info">
    ### `method` get\_session

    Get an existing session.

    **Parameters**

    > <ParamField body="server_name" type="str" required="True">   The name of the server to get the session for. </ParamField>

    **Returns**

    > <ResponseField name="returns" type="mcp_use.client.session.MCPSession">The MCPSession for the specified server.</ResponseField>

    **Signature**

    ```python wrap theme={null}
    def get_session(server_name: str):
    ```
  </Card>

  <Card type="info">
    ### `method` remove\_server

    Remove a server configuration.

    **Parameters**

    > <ParamField body="name" type="str" required="True">   The name of the server to remove. </ParamField>

    **Signature**

    ```python wrap theme={null}
    def remove_server(name: str):
    ```
  </Card>

  <Card type="info">
    ### `method` save\_config

    Save the current configuration to a file.

    **Parameters**

    > <ParamField body="filepath" type="str" required="True">   The path to save the configuration to. </ParamField>

    **Signature**

    ```python wrap theme={null}
    def save_config(filepath: str):
    ```
  </Card>

  <Card type="info">
    ### `method` search\_tools

    Search available MCP tools across all active sessions.

    Example:

    ```python theme={null}
    # 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']\}")
    ```

    **Parameters**

    > <ParamField body="query" type="str" default="">   Search query to filter tools by name or description. </ParamField>
    > <ParamField body="detail_level" type="str" default="full">   Level of detail to return: </ParamField>

    **Returns**

    > <ResponseField name="returns" type="dict[str, Any]">Level of detail to return: - "names": Only tool names and server - "descriptions": Names, server, and descriptions - "full": Complete tool information including schemas</ResponseField>

    **Signature**

    ```python wrap theme={null}
    def search_tools(query: str = "", detail_level: str = "full"):
    ```
  </Card>
</div>
