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.
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-useSTDIO, HTTP Servers, automation scripts, programmatic access Browser mcp-use/browserHTTP Web apps, browser extensions React mcp-use/reactHTTP React applications with hooks CLI npx mcp-use clientSTDIO, 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.
Node.js 18.0.0 or higher required . The library supports both ESM
(import) and CommonJS (require) syntax.
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 ()
Loading from Config File
Node.js supports loading configuration from JSON files:
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 ()
Config File Structure
The configuration file should be a JSON file with an mcpServers object containing your server definitions:
Multiple Server Types
Simple Example
{
"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"
}
}
}
}
Supported Connection Types
Node.js supports all connection types:
STDIO (ESM)
STDIO (CommonJS)
HTTP (ESM)
HTTP (CommonJS)
// 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' }
}
}
})
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.
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
No STDIO Support : Browser environments cannot spawn child processes, so
STDIO connections are not available. Use HTTP connections instead.
// 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:
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
The useMcp hook is the simplest way to integrate MCP in React applications:
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:
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 >
);
}
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:
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.
No installation required : Use npx mcp-use client to run commands
directly. Or install globally with npm install -g mcp-use.
Quick Start
# 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:
# Save an MCP server under a short name
npx mcp-use client connect < nam e > < ur l >
# List saved servers
npx mcp-use client list
# Run any command against a saved server
npx mcp-use client < nam e > < scop e > < actio n > [args...]
The per-server scopes are tools, resources, prompts, auth, and screenshot, plus the top-level interactive and disconnect:
# Tools
npx mcp-use client my-server tools list
npx mcp-use client my-server tools call < too l > [args]
npx mcp-use client my-server tools call < too l > [args] --screenshot # widget PNG when the tool renders a UI resource
npx mcp-use client my-server tools describe < too l >
# Resources
npx mcp-use client my-server resources list
npx mcp-use client my-server resources read < ur i >
# Prompts
npx mcp-use client my-server prompts list
npx mcp-use client my-server prompts get < promp t > [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 < too l > [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 .
Managing Multiple Servers
Saved servers are persisted to ~/.mcp-use/cli-sessions.json:
# 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:
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:
#!/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
For complete CLI documentation, examples, and advanced usage, see the CLI
Client Guide .
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
ESM (TypeScript / Modern JS)
CommonJS (Node.js)
// 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'
CommonJS Support : All Node.js features of mcp-use work with CommonJS
(require). Browser and React modules should use ESM (import) instead.
Security Considerations
Browser Security : Never expose sensitive tokens or credentials in
client-side code. Use OAuth flows or secure proxy servers for authentication.
// ❌ 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/).
# 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 ):
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
CLI Client Complete CLI client guide with examples
Configuration Learn about client configuration options
Tools Call tools and handle results
OAuth Set up OAuth authentication
useMcp Hook Detailed React hook documentation