Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/mcp-use/mcp-use/llms.txt

Use this file to discover all available pages before exploring further.

Overview

There are multiple ways to connect to MCP servers depending on your use case:

Local Processes (stdio)

Connect to servers running as local processes

HTTP/SSE Servers

Connect to servers over HTTP with Server-Sent Events

WebSocket Servers

Real-time bidirectional communication

Sandboxed (E2B)

Run servers in isolated cloud containers

Connection Methods

1. stdio Transport (Local Processes)

The simplest way to connect to MCP servers running as local processes:
import { MCPClient } from "mcp-use/client";

const config = {
  mcpServers: {
    filesystem: {
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
      env: {
        DEBUG: "true",  // Optional environment variables
      },
    },
    playwright: {
      command: "npx",
      args: ["@playwright/mcp@latest"],
    },
  },
};

const client = MCPClient.fromDict(config);
await client.createAllSessions();

// Use the client
const tools = await client.getTools();
console.log("Available tools:", tools.map(t => t.name));
When to use:
  • Local development
  • Command-line tools
  • No network setup needed
  • Process isolation

2. HTTP/SSE Transport

Connect to MCP servers running as HTTP services:
import { MCPClient } from "mcp-use/client";

const config = {
  mcpServers: {
    weather: {
      url: "http://localhost:3000/mcp",  // HTTP URL
    },
    remote: {
      url: "https://api.example.com/mcp",  // Remote server
      headers: {  // Optional custom headers
        "Authorization": "Bearer token",
      },
    },
  },
};

const client = MCPClient.fromDict(config);
await client.createAllSessions();
When to use:
  • Remote servers
  • Cloud deployments
  • Browser-based clients
  • Need HTTP features (caching, load balancing)

3. Configuration from File

Store configuration in a JSON file: config.json:
{
  "mcpServers": {
    "local-server": {
      "command": "node",
      "args": ["./dist/server.js"]
    },
    "remote-server": {
      "url": "http://localhost:3000/mcp"
    }
  }
}
import { MCPClient } from "mcp-use/client";

const client = MCPClient.fromConfigFile("./config.json");
await client.createAllSessions();

4. Sandboxed Execution (E2B)

Run MCP servers in isolated cloud containers:
import os
from mcp_use import MCPClient
from mcp_use.types.sandbox import SandboxOptions

config = {
    "mcpServers": {
        "everything": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-everything"],
        }
    }
}

sandbox_options: SandboxOptions = {
    "api_key": os.getenv("E2B_API_KEY"),
    "sandbox_template_id": "base",
}

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

await client.create_all_sessions()
Benefits:
  • No local dependencies
  • Secure isolation
  • Consistent environment
  • Cloud-based execution
Setup:
pip install "mcp-use[e2b]"
export E2B_API_KEY=your_api_key

Using MCPClient

Basic Operations

import { MCPClient } from "mcp-use/client";

const client = MCPClient.fromDict(config);

// Create sessions
await client.createAllSessions();

// List available tools
const tools = await client.getTools();
console.log("Tools:", tools);

// Get a specific session
const session = client.getSession("filesystem");

// Call a tool
const result = await session.callTool("read_file", {
  path: "/tmp/test.txt",
});
console.log("File content:", result.content[0].text);

// List resources
const resources = await session.listResources();
console.log("Resources:", resources);

// Read a resource
const data = await session.readResource("app://config");
console.log("Config:", data);

// Close sessions
await client.closeAllSessions();

Session Management

// Create specific sessions
await client.createSession("filesystem");

// Check if session exists
if (client.hasSession("filesystem")) {
  const session = client.getSession("filesystem");
}

// Get all sessions
const sessions = client.getSessions();

// Close specific session
await client.closeSession("filesystem");

// Close all sessions
await client.closeAllSessions();

Multi-Server Setup

Connect to multiple servers simultaneously:
const config = {
  mcpServers: {
    // Local process
    filesystem: {
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
    },
    // HTTP server
    weather: {
      url: "http://localhost:3000/mcp",
    },
    // Another local process
    airbnb: {
      command: "npx",
      args: ["-y", "@openbnb/mcp-server-airbnb"],
    },
  },
};

const client = MCPClient.fromDict(config);
await client.createAllSessions();

// Use tools from any server
const allTools = await client.getTools();
// Tools from all three servers are available

Authentication

OAuth Configuration

For servers requiring OAuth:
const config = {
  mcpServers: {
    linear: {
      url: "http://localhost:3000/mcp",
      oauth: {
        clientId: process.env.LINEAR_CLIENT_ID,
        clientSecret: process.env.LINEAR_CLIENT_SECRET,
        authorizationUrl: "https://linear.app/oauth/authorize",
        tokenUrl: "https://api.linear.app/oauth/token",
        scopes: ["read", "write"],
      },
    },
  },
};

Custom Headers

Add authentication headers:
const config = {
  mcpServers: {
    api: {
      url: "https://api.example.com/mcp",
      headers: {
        "Authorization": `Bearer ${process.env.API_TOKEN}`,
        "X-API-Key": process.env.API_KEY,
      },
    },
  },
};

Error Handling

try {
  const client = MCPClient.fromDict(config);
  await client.createAllSessions();
  
  const session = client.getSession("filesystem");
  const result = await session.callTool("read_file", {
    path: "/nonexistent.txt",
  });
  
  console.log(result);
} catch (error) {
  if (error.code === "FILE_NOT_FOUND") {
    console.error("File not found");
  } else if (error.code === "PERMISSION_DENIED") {
    console.error("Permission denied");
  } else {
    console.error("Error:", error.message);
  }
} finally {
  await client.closeAllSessions();
}

Best Practices

try {
  const client = MCPClient.fromDict(config);
  await client.createAllSessions();
  // ... use client ...
} finally {
  await client.closeAllSessions();
}
try {
  await client.createSession("remote-server");
} catch (error) {
  console.error("Failed to connect:", error);
  // Fall back to alternative server or cached data
}
  • Store configs in version control
  • Use environment variables for secrets
  • Different configs for dev/staging/prod
  • Document available servers
const result = await session.callTool("process_data", {
  input: validateInput(userInput),
});

Testing Connections

Using the Inspector

The easiest way to test connections:
# For HTTP servers
npx @mcp-use/inspector --url http://localhost:3000/mcp

# For built-in servers
# Just open http://localhost:3000/inspector

Programmatic Testing

async function testConnection() {
  const client = MCPClient.fromDict({
    mcpServers: {
      test: {
        url: "http://localhost:3000/mcp",
      },
    },
  });
  
  try {
    await client.createAllSessions();
    const tools = await client.getTools();
    
    console.log("✅ Connection successful");
    console.log(`Found ${tools.length} tools`);
    
    return true;
  } catch (error) {
    console.error("❌ Connection failed:", error);
    return false;
  } finally {
    await client.closeAllSessions();
  }
}

testConnection();

Common Issues

Problem: Cannot connect to serverSolutions:
  • Verify server is running
  • Check port is correct
  • Ensure no firewall blocking
  • For HTTP, check URL is reachable
Problem: Tool exists on server but not accessibleSolutions:
  • Verify server registered the tool
  • Check tool name spelling
  • Ensure session is created
  • Check server logs for errors
Problem: Operations timing outSolutions:
  • Increase timeout in client config
  • Check network latency
  • Optimize slow server operations
  • Use progress callbacks for long ops
Problem: Session not found or closedSolutions:
  • Always create sessions before use
  • Don’t close sessions while using them
  • Handle connection drops gracefully
  • Implement retry logic

Next Steps

Build AI Agents

Use MCPClient to build intelligent AI agents

Build Servers

Create your own MCP servers

API Reference

Complete client API documentation

Examples

Browse client examples

Build docs developers (and LLMs) love