> ## 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.

# Environments

> Use MCP client in Node.js, browser, and React applications

The mcp-use client works across different JavaScript environments, each with its own entry point and capabilities. This guide shows you how to use the client in Node.js, browser, and React applications.

## Overview

The library provides four main entry points:

| Env         | Import               | Connection  | Use Cases                                        |
| ----------- | -------------------- | ----------- | ------------------------------------------------ |
| **Node.js** | `mcp-use`            | STDIO, HTTP | Servers, automation scripts, programmatic access |
| **Browser** | `mcp-use/browser`    | HTTP        | Web apps, browser extensions                     |
| **React**   | `mcp-use/react`      | HTTP        | React applications with hooks                    |
| **CLI**     | `npx mcp-use client` | STDIO, HTTP | Terminal usage, testing, debugging, scripting    |

## Node.js

The Node.js environment provides the full feature set, including STDIO connections for local servers, file system operations, and code execution mode.

<Note>
  **Node.js 20.19 or higher, or 22.12 or higher required**. The library supports both ESM
  (`import`) and CommonJS (`require`) syntax.
</Note>

<CodeGroup>
  ```typescript TypeScript / ESM theme={null}
  import { MCPClient } from 'mcp-use'

  // Create client with STDIO server
  const client = new MCPClient({
  mcpServers: {
  filesystem: {
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir']
  }
  }
  })

  // Connect to all servers
  await client.createAllSessions()

  // Get a session and use it
  const session = client.getSession('filesystem')
  const tools = await session.listTools()
  console.log('Available tools:', tools)

  // Cleanup
  await client.closeAllSessions()

  ```

  ```javascript CommonJS theme={null}
  const { MCPClient } = require('mcp-use')

  async function main() {
    // Create client with STDIO server
    const client = new MCPClient({
      mcpServers: {
        filesystem: {
          command: 'npx',
          args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir']
        }
      }
    })

    // Connect to all servers
    await client.createAllSessions()

    // Get a session and use it
    const session = client.getSession('filesystem')
    const tools = await session.listTools()
    console.log('Available tools:', tools)

    // Cleanup
    await client.closeAllSessions()
  }

  main().catch(console.error)
  ```
</CodeGroup>

### Loading from Config File

Node.js supports loading configuration from JSON files:

<CodeGroup>
  ```typescript TypeScript / ESM theme={null}
  import { MCPClient, loadConfigFile } from 'mcp-use'

  // Load configuration from file
  const config = await loadConfigFile('mcp-config.json')
  const client = new MCPClient(config)
  await client.createAllSessions()

  ```

  ```javascript CommonJS theme={null}
  const { MCPClient, loadConfigFile } = require('mcp-use')

  async function main() {
    // Load configuration from file
    const config = await loadConfigFile('mcp-config.json')
    const client = new MCPClient(config)
    await client.createAllSessions()
  }

  main().catch(console.error)
  ```
</CodeGroup>

#### Config File Structure

The configuration file should be a JSON file with an `mcpServers` object containing your server definitions:

<CodeGroup>
  ```json Multiple Server Types theme={null}
  {
    "mcpServers": {
      "python-server": {
        "command": "python",
        "args": ["-m", "my_mcp_server"],
        "env": {
          "DEBUG": "1"
        }
      },
      "uvx-server": {
        "command": "uvx",
        "args": ["blender-mcp"]
      },
      "npx-server": {
        "command": "npx",
        "args": ["-y", "@playwright/mcp@latest"],
        "env": {
          "DISPLAY": ":1"
        }
      },
      "remote-server": {
        "url": "https://api.example.com/mcp",
        "headers": {
          "Authorization": "Bearer YOUR_TOKEN"
        }
      }
    }
  }
  ```

  ```json Simple Example theme={null}
  {
    "mcpServers": {
      "filesystem": {
        "command": "npx",
        "args": [
          "-y",
          "@modelcontextprotocol/server-filesystem",
          "/path/to/directory"
        ]
      }
    }
  }
  ```
</CodeGroup>

<Tip>
  For more configuration options and examples, see the [Client
  Configuration](/typescript/client/client-configuration) documentation.
</Tip>

### Supported Connection Types

Node.js supports all connection types:

<CodeGroup>
  ```typescript STDIO (ESM) theme={null}
  // Local process via stdin/stdout
  import { MCPClient } from 'mcp-use'

  const client = new MCPClient({
  mcpServers: {
  myServer: {
  command: 'npx',
  args: ['-y', '@my-mcp/server'],
  env: { PORT: '3000' }
  }
  }
  })

  ```

  ```javascript STDIO (CommonJS) theme={null}
  // Local process via stdin/stdout
  const { MCPClient } = require('mcp-use')

  const client = new MCPClient({
    mcpServers: {
      myServer: {
        command: 'npx',
        args: ['-y', '@my-mcp/server'],
        env: { PORT: '3000' }
      }
    }
  })
  ```

  ```typescript HTTP (ESM) theme={null}
  // Remote HTTP server with SSE
  import { MCPClient } from "mcp-use";

  const client = new MCPClient({
    mcpServers: {
      myServer: {
        url: "https://api.example.com/mcp",
        headers: {
          Authorization: "Bearer YOUR_TOKEN",
        },
      },
    },
  });
  ```

  ```javascript HTTP (CommonJS) theme={null}
  // Remote HTTP server with SSE
  const { MCPClient } = require("mcp-use");

  const client = new MCPClient({
    mcpServers: {
      myServer: {
        url: "https://api.example.com/mcp",
        headers: {
          Authorization: "Bearer YOUR_TOKEN",
        },
      },
    },
  });
  ```
</CodeGroup>

### Node.js-Specific Features

Node.js environment includes additional capabilities:

* **File System Operations**: Load config files, save configurations
* **Code Mode**: Execute code in sandboxed environments (VM or E2B)
* **STDIO Connections**: Connect to local MCP servers via child processes
* **HTTP Support**: Full support for HTTP and Server-Sent Events

## Browser

The browser version is optimized for client-side JavaScript, excluding Node.js-specific APIs like file system and child processes.

```typescript theme={null}
import { MCPClient } from "mcp-use/browser";

// Create client with HTTP server
const client = new MCPClient({
  mcpServers: {
    myServer: {
      url: "https://api.example.com/mcp",
      headers: {
        Authorization: "Bearer YOUR_TOKEN",
      },
    },
  },
});

// Connect to all servers
await client.createAllSessions();

// Use the session
const session = client.getSession("myServer");
const result = await session.callTool("tool_name", { param: "value" });
console.log(result);

// Cleanup
await client.closeAllSessions();
```

### Supported Connection Types

<Warning>
  **No STDIO Support**: Browser environments cannot spawn child processes, so
  STDIO connections are not available. Use HTTP connections instead.
</Warning>

```typescript theme={null}
// HTTP with automatic SSE fallback
const client = new MCPClient({
  mcpServers: {
    myServer: {
      url: "https://api.example.com/mcp",
      preferSse: false, // Set to true to force SSE
    },
  },
});
```

### Browser Limitations

The browser client has some limitations compared to Node.js:

* ❌ **No STDIO**: Cannot spawn child processes
* ❌ **No File System**: Cannot read/write config files
* ❌ **No Code Mode**: Sandboxed code execution not available
* ✅ **HTTP**: Full support for remote connections
* ✅ **OAuth**: Complete OAuth flow support

### OAuth in Browser

The browser client fully supports OAuth authentication:

```typescript theme={null}
import { MCPClient, BrowserOAuthClientProvider } from "mcp-use/browser";

// Create OAuth provider
const authProvider = new BrowserOAuthClientProvider({
  clientId: "your-client-id",
  authorizationUrl: "https://api.example.com/oauth/authorize",
  tokenUrl: "https://api.example.com/oauth/token",
  callbackUrl: window.location.origin + "/oauth/callback",
});

// Create client with OAuth
const client = new MCPClient({
  mcpServers: {
    myServer: {
      url: "https://api.example.com/mcp",
      authProvider: authProvider,
    },
  },
});

await client.createAllSessions();
```

## React

The React integration provides a hook-based API that automatically manages connections, state, and authentication.

### Installation

```bash theme={null}
yarn add mcp-use react
```

The `useMcp` hook is the simplest way to integrate MCP in React applications:

```typescript theme={null}
import { useMcp } from "mcp-use/react";

function MyComponent() {
  const mcp = useMcp({
    url: "https://api.example.com/mcp",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
    },
  });

  // Wait for connection
  if (mcp.state !== "ready") {
    return <div>Connecting to MCP server...</div>;
  }

  // Show available tools
  return (
    <div>
      <h2>Available Tools</h2>
      <ul>
        {mcp.tools.map((tool) => (
          <li key={tool.name}>
            <strong>{tool.name}</strong>: {tool.description}
          </li>
        ))}
      </ul>
    </div>
  );
}
```

### Connection States

The hook manages connection state automatically:

```typescript theme={null}
function ConnectionStatus() {
  const mcp = useMcp({ url: "https://api.example.com/mcp" });

  return (
    <div>
      {mcp.state === "discovering" && <p>🔍 Discovering server...</p>}
      {mcp.state === "authenticating" && <p>🔐 Authenticating...</p>}
      {mcp.state === "pending_auth" && <p>⏳ Waiting for authorization...</p>}
      {mcp.state === "ready" && <p>✅ Connected and ready!</p>}
      {mcp.state === "failed" && (
        <div>
          <p>❌ Connection failed</p>
          <p>{mcp.error}</p>
          <button onClick={mcp.retry}>Retry</button>
        </div>
      )}
    </div>
  );
}
```

### Calling Tools

```typescript theme={null}
function ToolExecutor() {
  const mcp = useMcp({ url: "https://api.example.com/mcp" });
  const [result, setResult] = React.useState(null);

  const handleCallTool = async () => {
    try {
      const result = await mcp.callTool("send-email", {
        to: "user@example.com",
        subject: "Hello",
        body: "Test message",
      });
      setResult(result);
    } catch (error) {
      console.error("Tool call failed:", error);
    }
  };

  return (
    <div>
      <button onClick={handleCallTool} disabled={mcp.state !== "ready"}>
        Send Email
      </button>
      {result && <pre>{JSON.stringify(result, null, 2)}</pre>}
    </div>
  );
}
```

### OAuth Authentication

The hook provides complete OAuth flow management:

```typescript theme={null}
function OAuthApp() {
  const mcp = useMcp({
    url: "https://api.example.com/mcp",
    // OAuth is auto-detected from server metadata
  });

  if (mcp.state === "pending_auth") {
    return (
      <div>
        <h2>Authorization Required</h2>
        <p>Please authorize the application to continue.</p>
        <a href={mcp.authUrl} target="_blank">
          Authorize Now
        </a>
      </div>
    );
  }

  return <div>Ready to use!</div>;
}
```

### React Hook Features

The `useMcp` hook provides:

* ✅ **Automatic Connection**: Manages connect, disconnect, and reconnect
* ✅ **State Management**: Reactive state updates for UI synchronization
* ✅ **OAuth Support**: Complete OAuth flow with token management
* ✅ **Tool Execution**: Call tools with automatic error handling
* ✅ **Type Safety**: Full TypeScript support with type inference
* ✅ **Resource Access**: Read resources and prompts from servers

## CLI Client

The CLI client provides a command-line interface for interacting with MCP servers directly from your terminal, without writing any code. It's perfect for testing, debugging, and quick server interactions.

<Note>
  **No installation required**: Use `npx mcp-use client` to run commands
  directly. Or install globally with `npm install -g mcp-use`.
</Note>

### Quick Start

```bash theme={null}
# Connect to an HTTP server, saved under the name "my-server"
npx mcp-use client connect my-server http://localhost:3000/mcp

# Connect to a stdio server
npx mcp-use client connect fs "npx -y @modelcontextprotocol/server-filesystem /tmp" --stdio

# Every subsequent command names the client it operates on
npx mcp-use client my-server tools list
npx mcp-use client my-server tools call read_file path=/tmp/test.txt
npx mcp-use client my-server interactive
```

### Command Structure

Top-level shapes:

```bash theme={null}
# Save an MCP server under a short name
npx mcp-use client connect <name> <url>

# List saved servers
npx mcp-use client list

# Run any command against a saved server
npx mcp-use client <name> <scope> <action> [args...]
```

The per-server scopes are `tools`, `resources`, `prompts`, `auth`, and `screenshot`, plus the top-level `interactive` and `disconnect`:

```bash theme={null}
# Tools
npx mcp-use client my-server tools list
npx mcp-use client my-server tools call <tool> [args]
npx mcp-use client my-server tools call <tool> [args] --screenshot   # widget PNG when the tool renders a UI resource
npx mcp-use client my-server tools describe <tool>

# Resources
npx mcp-use client my-server resources list
npx mcp-use client my-server resources read <uri>

# Prompts
npx mcp-use client my-server prompts list
npx mcp-use client my-server prompts get <prompt> [args]

# Auth (OAuth servers only)
npx mcp-use client my-server auth status
npx mcp-use client my-server auth refresh
npx mcp-use client my-server auth logout

# Widget screenshot (saved-server form — reuses OAuth/bearer auth)
npx mcp-use client my-server screenshot --tool <tool> [args]

# Interactive mode for one server
npx mcp-use client my-server interactive
```

For ad-hoc screenshots against a server you haven't saved, use the top-level form with `--mcp <url>` and optional `-H` headers — see the [CLI Client guide](/typescript/client/cli#screenshot).

### Managing Multiple Servers

Saved servers are persisted to `~/.mcp-use/cli-sessions.json`:

```bash theme={null}
# Connect to multiple servers
npx mcp-use client connect server1 http://localhost:3000/mcp
npx mcp-use client connect server2 http://localhost:4000/mcp

# List them
npx mcp-use client list

# Run against either, by name
npx mcp-use client server1 tools list
npx mcp-use client server2 tools list
```

There is no "active" server — every command names its target explicitly.

### Interactive Mode

For exploration and testing, drop into a REPL against a specific server:

```bash theme={null}
npx mcp-use client my-server interactive

mcp> tools list
mcp> tools call read_file
Arguments (JSON): {"path": "/tmp/test.txt"}
✓ Success
...
mcp> exit
```

### Scripting with the CLI

Use the CLI in automation scripts with the `--json` flag for machine-readable output:

```bash theme={null}
#!/bin/bash

# Connect to server (saves it under the name "automation")
npx mcp-use client connect automation http://localhost:3000/mcp

# Get data as JSON and process with jq
RESULT=$(npx mcp-use client automation tools call get_data --json 2>/dev/null)
VALUE=$(echo "$RESULT" | jq -r '.content[0].text')

echo "Retrieved value: $VALUE"

# Cleanup
npx mcp-use client automation disconnect
```

### CLI Features

* ✅ **No Code Required**: Interact with MCP servers from the terminal
* ✅ **Both Transports**: Supports HTTP and STDIO connections
* ✅ **Session Persistence**: Sessions saved and restored automatically
* ✅ **Interactive Mode**: REPL-style interface for exploration
* ✅ **Scripting Support**: JSON output for automation
* ✅ **Multi-Session**: Manage multiple server connections
* ✅ **Testing & Debugging**: Perfect for server development

<Tip>
  For complete CLI documentation, examples, and advanced usage, see the [CLI
  Client Guide](/typescript/client/cli).
</Tip>

## Environment Comparison

### Feature Support Matrix

| Feature                    | Node.js | Browser | React | CLI |
| -------------------------- | ------- | ------- | ----- | --- |
| STDIO Connections          | ✅       | ❌       | ❌     | ✅   |
| HTTP Connections           | ✅       | ✅       | ✅     | ✅   |
| OAuth Authentication       | ✅       | ✅       | ✅     | ✅   |
| File System Operations     | ✅       | ❌       | ❌     | ✅   |
| Code Mode                  | ✅       | ❌       | ❌     | ❌   |
| Config File Loading        | ✅       | ❌       | ❌     | ✅   |
| Automatic State Management | ❌       | ❌       | ✅     | ❌   |
| React Hooks                | ❌       | ❌       | ✅     | ❌   |
| Interactive REPL           | ❌       | ❌       | ❌     | ✅   |
| Session Persistence        | ❌       | ❌       | ❌     | ✅   |

### Import Reference

<CodeGroup>
  ```typescript ESM (TypeScript / Modern JS) theme={null}
  // Node.js - Full feature set
  import { MCPClient } from 'mcp-use'

  // Browser - No STDIO, no file system
  import { MCPClient } from 'mcp-use/browser'

  // React - Hook-based API
  import { useMcp } from 'mcp-use/react'

  // OAuth helpers (available in all environments)
  import { BrowserOAuthClientProvider, onMcpAuthorization } from 'mcp-use/browser'
  import { onMcpAuthorization } from 'mcp-use/react'

  ```

  ```javascript CommonJS (Node.js) theme={null}
  // Node.js - Full feature set
  const { MCPClient } = require('mcp-use')

  // Server utilities
  const { MCPServer } = require('mcp-use/server')

  // Agent utilities
  const { MCPAgent } = require('mcp-use/agent')

  // OAuth helpers
  const { BrowserOAuthClientProvider } = require('mcp-use/auth')

  // Browser and React exports are not available in CommonJS
  // as they require ESM module resolution
  ```
</CodeGroup>

<Info>
  **CommonJS Support**: All Node.js features of `mcp-use` work with CommonJS
  (`require`). Browser and React modules should use ESM (`import`) instead.
</Info>

### Security Considerations

<Warning>
  **Browser Security**: Never expose sensitive tokens or credentials in
  client-side code. Use OAuth flows or secure proxy servers for authentication.
</Warning>

```typescript theme={null}
// ❌ Bad: Hardcoded credentials in browser
const client = new MCPClient({
  mcpServers: {
    myServer: {
      url: "https://api.example.com/mcp",
      headers: {
        Authorization: "Bearer SECRET_TOKEN", // Don't do this!
      },
    },
  },
});

// ✅ Good: Use OAuth or environment-based tokens
const client = new MCPClient({
  mcpServers: {
    myServer: {
      url: "https://api.example.com/mcp",
      authProvider: oauthProvider, // OAuth flow
    },
  },
});
```

## Examples

Client examples live in the package under `examples/client/`. Run them from the **package root** (e.g. `libraries/typescript/packages/mcp-use`):

* **Node**: `examples/client/node/`  -  full-features (tool calls, sampling, elicitation, notifications) and communication examples (sampling, notification).
* **Browser**: `examples/client/browser/`  -  full-features and CommonJS (`browser/commonjs/`).

```bash theme={null}
# From package root (libraries/typescript/packages/mcp-use)
pnpm run example:node:full      # Node client with onSampling, onElicitation, onNotification
pnpm run example:browser:full   # Browser client (same features)
pnpm run example:client:notification   # Notification client (start notification server first)
pnpm run example:client:sampling       # Sampling client (start sampling server first)
pnpm run example:commonjs             # Browser CommonJS build
pnpm run example:with-conformance      # Starts conformance server, then node + browser full-features
```

Minimal client setup with root-level callbacks (as in [full-features-example.ts](https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/mcp-use/examples/client/node/full-features-example.ts)):

```typescript theme={null}
import { acceptWithDefaults, MCPClient } from "mcp-use";

const client = new MCPClient(
  { mcpServers: { myServer: { url: "http://localhost:3000/mcp" } } },
  {
    onElicitation: async (params) => acceptWithDefaults(params),
    onNotification: (n) => console.log(n.method),
    // onSampling: see Sampling docs
  }
);
```

## Next Steps

<CardGroup cols={2}>
  <Card title="CLI Client" icon="terminal" href="/typescript/client/cli">
    Complete CLI client guide with examples
  </Card>

  <Card title="Configuration" icon="cog" href="/typescript/client/client-configuration">
    Learn about client configuration options
  </Card>

  <Card title="Tools" icon="wrench" href="/typescript/client/tools">
    Call tools and handle results
  </Card>

  <Card title="OAuth" icon="shield" href="/typescript/client/authentication">
    Set up OAuth authentication
  </Card>

  <Card title="useMcp Hook" icon="react" href="/typescript/client/usemcp">
    Detailed React hook documentation
  </Card>
</CardGroup>
