---
title: API Reference
description: "Complete mcp_use API Documentation"
---

# API Reference

This section provides comprehensive documentation for the mcp_use API, including all components, methods, their arguments, and when to use different options.

## MCPClient

The `MCPClient` is the core class for interacting with MCP servers. It handles connection management, session creation, and communication with MCP servers.

### Initialization Methods

#### From Config File

```python
from mcp_use import MCPClient

client = MCPClient.from_config_file(config_path="config.json")
```

| Parameter     | Type | Required | Description                         |
| ------------- | ---- | -------- | ----------------------------------- |
| `config_path` | str  | Yes      | Path to the JSON configuration file |

#### From Dictionary

```python
from mcp_use import MCPClient

config = {
  "mcpServers": {
    "my_server": {
      "command": "npx",
      "args": ["@my-mcp/server"],
      "env": {
        "PORT": "3000"
      }
    }
  }
}

client = MCPClient.from_dict(config=config)
```

| Parameter | Type | Required | Description                                    |
| --------- | ---- | -------- | ---------------------------------------------- |
| `config`  | dict | Yes      | Dictionary containing MCP server configuration |

### Core Methods

#### create_session

Creates a new session with an MCP server.

```python
session = await client.create_session(server_name="my_server")
```

| Parameter     | Type  | Required | Default | Description                             |
| ------------- | ----- | -------- | ------- | --------------------------------------- |
| `server_name` | str   | Yes      | -       | Name of the server as defined in config |
| `timeout`     | float | No       | 30.0    | Connection timeout in seconds           |
| `retry_count` | int   | No       | 3       | Number of connection retry attempts     |

**When to use**:

- Use a longer `timeout` for servers that take more time to initialize
- Increase `retry_count` in unstable network environments
- Use specific `server_name` when working with multiple servers in the same config

#### close_session

Closes a specific session.

```python
await client.close_session(session_id="session_id")
```

| Parameter    | Type | Required | Description                |
| ------------ | ---- | -------- | -------------------------- |
| `session_id` | str  | Yes      | ID of the session to close |

#### close_all_sessions

Closes all active sessions.

```python
await client.close_all_sessions()
```

**When to use**:

- Always call this at the end of your application to clean up resources
- Use when switching between different tasks that require different servers

#### get_server

Gets a server instance by name.

```python
server = client.get_server(name="my_server")
```

| Parameter | Type | Required | Description                             |
| --------- | ---- | -------- | --------------------------------------- |
| `name`    | str  | Yes      | Name of the server as defined in config |

## MCPAgent

The `MCPAgent` class combines an LLM with an MCPClient to create an intelligent agent capable of using MCP tools.

### Initialization

```python
from mcp_use import MCPAgent, MCPClient
from langchain_openai import ChatOpenAI

agent = MCPAgent(
    llm=ChatOpenAI(model="gpt-4o", temperature=0.7),
    client=MCPClient.from_config_file("config.json"),
    max_steps=30,
    session_options={"timeout": 60.0},
    auto_initialize=True,
    memory_enabled=True,
    system_prompt=None,
    system_prompt_template=None,
    additional_instructions=None,
    disallowed_tools=None,
    use_server_manager=False
)
```

| Parameter                 | Type                | Required | Default | Description                                                  |
| ------------------------- | ------------------- | -------- | ------- | ------------------------------------------------------------ |
| `llm`                     | BaseLanguageModel   | Yes      | -       | Any LangChain-compatible language model                      |
| `client`                  | MCPClient           | No       | None    | The MCPClient instance                                       |
| `connectors`              | list[BaseConnector] | No       | None    | List of connectors if not using client                       |
| `server_name`             | str                 | No       | None    | Name of the server to use                                    |
| `max_steps`               | int                 | No       | 5       | Maximum number of steps the agent can take                   |
| `auto_initialize`         | bool                | No       | False   | Whether to initialize automatically                          |
| `memory_enabled`          | bool                | No       | True    | Whether to enable memory                                     |
| `system_prompt`           | str                 | No       | None    | Custom system prompt                                         |
| `system_prompt_template`  | str                 | No       | None    | Custom system prompt template                                |
| `additional_instructions` | str                 | No       | None    | Additional instructions for the agent                        |
| `session_options`         | dict                | No       | {}      | Additional options for session creation                      |
| `output_parser`           | OutputParser        | No       | None    | Custom output parser for LLM responses                       |
| `use_server_manager`      | bool                | No       | False   | If `True`, enables automatic selection of the appropriate server based on the chosen tool when multiple servers are configured via `MCPClient`. |
| `disallowed_tools`        | list[str]           | No       | None    | List of tool names that should not be available to the agent |

**When to use different parameters**:

- **llm**:

  - mcp_use supports ANY LLM that is compatible with LangChain
  - You can use models from OpenAI, Anthropic, Google, Mistral, Groq, Cohere, or any other provider with a LangChain integration
  - You can even use open source models via LlamaCpp, HuggingFace, or other interfaces
  - Custom or self-hosted models are also supported as long as they implement LangChain's interface

- **max_steps**:

  - Increase for complex tasks that require many interactions
  - Decrease for simpler tasks to improve efficiency
  - Use higher values (50+) for web browsing or multi-stage tasks
  - Use lower values (10-20) for targeted, specific tasks

- **system_prompt / system_prompt_template**:

  - Use to customize the initial instructions given to the LLM
  - Helps shape the agent's behavior and capabilities
  - Use for specialized tasks or custom interaction patterns

- **memory_enabled**:

  - Enable to maintain conversation history
  - Disable for stateless operation or to save on token usage

- **session_options**:
  - Customize timeout for long-running server operations
  - Set retry parameters for unstable connections
- **use_server_manager**:
  - Set to `True` when using an `MCPClient` configured with multiple servers to enable efficient, automatic server selection per tool call. This can reduce agent confusion and minimize unnecessary server connections.
  - Keep as `False` (default) if using a single server or if you prefer to manually specify the target server using the `server_name` parameter in `agent.run()` or rely on the agent to handle tool availability across all connected servers.
- **disallowed_tools**:
  - Use to restrict which tools the agent can access
  - Helpful for security or to limit agent capabilities
  - Useful when certain tools might be dangerous or unnecessary for a specific task
  - Can be updated after initialization using `set_disallowed_tools()`

### Core Methods

#### run

Runs the agent with a given query.

```python
result = await agent.run(
    query="Find information about Python libraries",
    max_steps=25,
    stop_on_first_result=False
)
```

| Parameter              | Type | Required | Default | Description                      |
| ---------------------- | ---- | -------- | ------- | -------------------------------- |
| `query`                | str  | Yes      | -       | The query to run                 |
| `max_steps`            | int  | No       | None    | Overrides the instance max_steps |
| `stop_on_first_result` | bool | No       | False   | Whether to stop at first result  |
| `server_name`          | str  | No       | None    | Specific server to use           |
| `callbacks`            | list | No       | None    | Callback functions for events    |

**When to use different parameters**:

- **max_steps**: Override the instance default for specific queries
- **stop_on_first_result**: Use True for simple lookups, False for thorough exploration
- **server_name**: Specify when using multiple servers for different tasks
- **callbacks**: Add for monitoring or logging specific runs

#### reset

Resets the agent state.

```python
agent.reset()
```

**When to use**:

- Between different tasks to clear context
- When starting a new conversation thread
- When agent gets stuck in a particular strategy

#### get_history

Gets the agent's interaction history.

```python
history = agent.get_history()
```

**When to use**:

- For debugging agent behavior
- When implementing custom logging
- To provide context for follow-up queries

#### set_disallowed_tools

Sets the list of tools that should not be available to the agent.

```python
agent.set_disallowed_tools(["tool1", "tool2"])
```

| Parameter          | Type      | Required | Description                                     |
| ------------------ | --------- | -------- | ----------------------------------------------- |
| `disallowed_tools` | list[str] | Yes      | List of tool names that should not be available |

**When to use**:

- To restrict access to specific tools for security reasons
- To limit agent capabilities for specific tasks
- To prevent the agent from using potentially dangerous tools
- Note: Changes take effect on next initialization

#### get_disallowed_tools

Gets the list of tools that are not available to the agent.

```python
disallowed = agent.get_disallowed_tools()
```

**When to use**:

- To check which tools are currently restricted
- For debugging or auditing purposes
- To verify tool restrictions before running the agent

## Configuration Details

### MCP Server Configuration Schema

```json
{
  "mcpServers": {
    "server_name": {
      "command": "command_to_run",
      "args": ["arg1", "arg2"],
      "env": {
        "ENV_VAR": "value"
      },
      "timeout": 30.0,
      "retry": {
        "max_attempts": 3,
        "backoff_factor": 1.5
      }
    }
  }
}
```

| Field                  | Type   | Required | Description                          |
| ---------------------- | ------ | -------- | ------------------------------------ |
| `command`              | string | Yes      | The command to start the MCP server  |
| `args`                 | array  | No       | Arguments to pass to the command     |
| `env`                  | object | No       | Environment variables for the server |
| `timeout`              | number | No       | Connection timeout in seconds        |
| `retry`                | object | No       | Retry configuration                  |
| `retry.max_attempts`   | number | No       | Maximum retry attempts               |
| `retry.backoff_factor` | number | No       | Backoff multiplier between retries   |

**When to use different options**:

- **command & args**: Vary based on the specific MCP server implementation
- **env**:

  - Set environment-specific variables needed by the server
  - Override default server settings (ports, directories)
  - Set display settings for GUI-based servers

- **timeout**:

  - Increase for servers with longer startup times
  - Lower for simpler servers to fail fast

- **retry configuration**:
  - Adjust for different network conditions
  - Increase max_attempts in unstable environments
  - Adjust backoff_factor based on server behavior

## Error Handling

mcp_use provides several exception types to handle different error scenarios:

| Exception                | Description                       | When It Occurs                      |
| ------------------------ | --------------------------------- | ----------------------------------- |
| `MCPConnectionError`     | Connection to MCP server failed   | Network issues, server not running  |
| `MCPAuthenticationError` | Authentication with server failed | Invalid credentials or tokens       |
| `MCPTimeoutError`        | Operation timed out               | Server takes too long to respond    |
| `MCPServerError`         | Server returned an error          | Internal server error               |
| `MCPClientError`         | Client-side error                 | Invalid configuration or parameters |
| `MCPError`               | Generic MCP-related error         | Any other MCP-related issue         |

**Handling Strategies**:

```python
from mcp_use.exceptions import MCPConnectionError, MCPTimeoutError

try:
    result = await agent.run("Find information")
except MCPConnectionError:
    # Handle connection issues
    print("Failed to connect to the MCP server")
except MCPTimeoutError:
    # Handle timeout issues
    print("Operation timed out")
except Exception as e:
    # Handle other exceptions
    print(f"An error occurred: {e}")
```

## Advanced Usage

### Multi-Server Configuration

Configure and use multiple MCP servers in a single application:

```python
from mcp_use import MCPClient, MCPAgent
from langchain_openai import ChatOpenAI

# Create client with multiple servers
client = MCPClient.from_dict({
    "mcpServers": {
        "browser": {
            "command": "npx",
            "args": ["@playwright/mcp@latest"]
        },
        "custom_server": {
            "command": "python",
            "args": ["-m", "my_custom_mcp_server"]
        }
    }
})

# Create agent
agent = MCPAgent(llm=ChatOpenAI(model="gpt-4o"), client=client)

# Run with specific server
result_browser = await agent.run(
    "Search the web for Python libraries",
    server_name="browser"
)

# Run with different server
result_custom = await agent.run(
    "Perform custom operation",
    server_name="custom_server"
)
```

### Custom Output Parsing

Implement custom output parsers for specialized MCP servers:

```python
from langchain.schema import OutputParser
from mcp_use import MCPAgent, MCPClient

class CustomOutputParser(OutputParser):
    def parse(self, text):
        # Custom parsing logic
        return processed_result

# Use the custom parser
agent = MCPAgent(
    llm=llm,
    client=client,
    output_parser=CustomOutputParser()
)
```

This approach is useful when:

- The MCP server returns structured data that needs special handling
- You need to extract specific information from responses
- You're integrating with custom or specialized MCP servers

### Restricting Tool Access

Control which tools are available to the agent:

```python
from mcp_use import MCPAgent, MCPClient
from langchain_openai import ChatOpenAI

# Create agent with restricted tools
agent = MCPAgent(
    llm=ChatOpenAI(model="gpt-4o"),
    client=client,
    disallowed_tools=["file_system", "network", "shell"]  # Restrict potentially dangerous tools
)

# Update restrictions after initialization
agent.set_disallowed_tools(["file_system", "network", "shell", "database"])
await agent.initialize()  # Reinitialize to apply changes

# Check current restrictions
restricted_tools = agent.get_disallowed_tools()
print(f"Restricted tools: {restricted_tools}")
```

This approach is useful when:

- You need to restrict access to sensitive operations
- You want to limit the agent's capabilities for specific tasks
- You're concerned about security implications of certain tools
- You want to focus the agent on specific functionality
