# mcp-use

> MCP Server

**Concise Descriptions:**

* **MCP client library for custom agent integration. Simplifies server interaction.** (79 chars)
* **Easy MCP interaction with custom agents. Client library.** (55 chars)
* 

## Overview

- **Category:** AI
- **Language:** Python
- **Stars:** 10405
- **Forks:** 499
- **Owner:** mcp-use
- **GitHub:** https://github.com/mcp-use/mcp-use
- **Homepage:** https://mcp-use.com
- **Created:** 2025-03-28T10:06:31+00:00
- **Updated:** 2025-07-07T16:19:36+00:00
- **Source:** https://model-context-protocol.com/servers/mcp-use

## Setup

## Setup

### Prerequisites

*   **Python 3.11 or higher:** MCP-Use requires Python 3.11 or a later version.
*   **MCP Implementation:** You'll need an MCP server implementation, such as Playwright MCP or a custom MCP server.
*   **LangChain Provider:** Choose an LLM provider supported by LangChain (e.g., OpenAI, Anthropic, Groq, Llama).
*   **E2B Account (Optional):** If you plan to use sandboxed execution, sign up for an E2B account at [e2b.dev](https://e2b.dev) to obtain an API key.

### Installation

1.  **Install MCP-Use:**

    ```bash
    pip install mcp-use
    ```

    Alternatively, install from source:

    ```bash
    git clone https://github.com/pietrozullo/mcp-use.git
    cd mcp-use
    pip install -e .
    ```

2.  **Install LangChain Provider:**

    Install the LangChain package for your chosen LLM provider.  Here are a few examples:

    ```bash
    # For OpenAI
    pip install langchain-openai

    # For Anthropic
    pip install langchain-anthropic

    # For Groq
    pip install langchain-groq
    ```

    Refer to the [LangChain chat models documentation](https://python.langchain.com/docs/integrations/chat/) for other providers.

3.  **Install E2B (Optional):**

    If you want to use sandboxed execution, install the `e2b-code-interpreter` package:

    ```bash
    pip install "mcp-use[e2b]"
    # Or
    pip install e2b-code-interpreter
    ```

### Configuration

1.  **Environment Variables:**

    Create a `.env` file in your project directory and add the API keys for your chosen LLM provider(s) and E2B (if using sandboxing).

    ```
    OPENAI_API_KEY=<your_openai_api_key>
    ANTHROPIC_API_KEY=<your_anthropic_api_key>
    GROQ_API_KEY=<your_groq_api_key>
    E2B_API_KEY=<your_e2b_api_key>  # Required for sandboxed execution
    ```

    Load the environment variables in your Python script:

    ```python
    from dotenv import load_dotenv

    load_dotenv()
    ```

2.  **MCP Server Configuration:**

    Configure your MCP servers either programmatically or using a JSON configuration file.  Here's an example `browser_mcp.json` file:

    ```json
    {
      "mcpServers": {
        "playwright": {
          "command": "npx",
          "args": ["@playwright/mcp@latest"],
          "env": {
            "DISPLAY": ":1"
          }
        }
      }
    }
    ```

    Load the configuration in your Python script:

    ```python
    from mcp_use import MCPClient
    import os

    client = MCPClient.from_config_file(os.path.join("browser_mcp.json"))
    ```

    Alternatively, configure the MCP servers directly in your Python code:

    ```python
    from mcp_use import MCPClient

    config = {
        "mcpServers": {
            "playwright": {
                "command": "npx",
                "args": ["@playwright/mcp@latest"],
                "env": {
                    "DISPLAY": ":1"
                }
            }
        }
    }

    client = MCPClient.from_dict(config)
    ```

3.  **Sandboxed Execution Configuration (Optional):**

    If using sandboxed execution, configure the `SandboxOptions` when creating the `MCPClient`:

    ```python
    import os
    from mcp_use import MCPClient
    from mcp_use.types.sandbox import SandboxOptions

    sandbox_options: SandboxOptions = {
        "api_key": os.getenv("E2B_API_KEY"),  # API key can also be provided directly
        "sandbox_template_id": "base",  # Use base template
    }

    client = MCPClient(
        config=server_config,
        sandbox=True,
        sandbox_options=sandbox_options,
    )
    ```

### Important Considerations

*   **Tool Calling Capability:** Ensure that the LLM you choose supports tool calling (also known as function calling).  This is essential for MCP-Use to function correctly.
*   **MCP Server Availability:** Make sure your MCP server(s) are running and accessible before running your MCP-Use agent.
*   **Display Environment Variable:** If using Playwright MCP or similar tools that require a display, ensure the `DISPLAY` environment variable is set correctly (e.g., `DISPLAY=:1`).

## Tools

## Available Tools

MCP-Use provides the following tools and features to connect LLMs to MCP servers and build custom agents:

*   **Ease of Use:** Create an MCP-capable agent with just a few lines of code.
    *   **Usage:** See the Quick Start section for a code example.

*   **LLM Flexibility:** Works with any LangChain-supported LLM that supports tool calling (e.g., OpenAI, Anthropic, Groq, Llama).
    *   **Usage:** Install the appropriate LangChain provider package (e.g., `pip install langchain-openai`).

*   **Code Builder:** Explore MCP capabilities and generate starter code with the interactive [code builder](https://mcp-use.com/builder).

*   **HTTP Support:** Connect directly to MCP servers running on specific HTTP ports.
    *   **Usage:** Configure the `MCPClient` with the server's URL.
        ```python
        config = {
            "mcpServers": {
                "http": {
                    "url": "http://localhost:8931/sse"
                }
            }
        }
        client = MCPClient.from_dict(config)
        ```

*   **Dynamic Server Selection (Server Manager):** Agents can dynamically choose the most appropriate MCP server for a given task from the available pool. This is enabled by setting `use_server_manager=True` during `MCPAgent` initialization.
    *   **Usage:**
        ```python
        agent = MCPAgent(
            llm=llm,
            client=client,
            use_server_manager=True
        )
        ```

*   **Multi-Server Support:** Use multiple MCP servers simultaneously in a single agent.
    *   **Usage:** Configure multiple servers in the `MCPClient` and optionally specify the `server_name` when calling `agent.run()`.
        ```python
        result = await agent.run(
            "Search for Airbnb listings in Barcelona",
            server_name="airbnb"
        )
        ```

*   **Tool Restrictions:** Restrict potentially dangerous tools like file system or network access.
    *   **Usage:** Provide a list of disallowed tools when creating an `MCPAgent`.
        ```python
        agent = MCPAgent(
            llm=llm,
            client=client,
            disallowed_tools=["file_system", "network"]
        )
        ```

*   **Custom Agents:** Build your own agents with any framework using the LangChain adapter or create new adapters.
    *   **Usage:** Use the `LangChainAdapter` to create LangChain tools from the MCP client.

*   **Sandboxed Execution:** Run MCP servers in a sandboxed environment using E2B's cloud infrastructure, eliminating the need for local dependency installation.
    *   **Usage:** Install the `e2b-code-interpreter` dependency and configure the `MCPClient` with `sandbox=True` and `sandbox_options`.

*   **Streaming Agent Output:** Asynchronously stream agent output using the `astream` method on `MCPAgent` for real-time feedback.
    *   **Usage:**
        ```python
        async for chunk in agent.astream("Find the best restaurant in San Francisco"):
            print(chunk["messages"], end="", flush=True)
        ```

*   **Configuration File Support:** Initialize `MCPClient` from configuration files for easy management of MCP server setups.
    *   **Usage:**
        ```python
        client = MCPClient.from_config_file("mcp-config.json")
        ```

*   **Debugging:** Use debug mode to increase log verbosity and diagnose issues.  Enable via environment variable (`DEBUG=1` or `DEBUG=2`) or programmatically (`mcp_use.set_debug(1)` or `mcp_use.set_debug(2)`). Agent-specific verbosity can be enabled with `verbose=True` in `MCPAgent`.

## Related Articles

- [mcp-use MCP Server: Simplifies Custom Agent Integration with MCP](https://model-context-protocol.com/blog/mcp-use-mcp-server-simplifies-custom-agent-integration-with-mcp-mcp-server-guide)
