Secure your MCP connections with OAuth and bearer tokens
The mcp-use client supports multiple authentication methods for secure connections to MCP servers, including OAuth 2.1 with automatic token management, bearer token authentication, and custom authentication providers.
For server-side Node.js applications, use MCPClient with bearer tokens or custom headers. OAuth flows are browser-only and not available in Node.js environments.
Load authentication settings from a JSON configuration file:
Copy
Ask AI
import { MCPClient } from 'mcp-use'// Constructor accepts file path directlyconst client = new MCPClient('./mcp-config.json')// Or use fromDict with imported configimport config from './mcp-config.json'const client = MCPClient.fromDict(config)
Best Practice: Store sensitive tokens in environment variables and
reference them in your configuration instead of hardcoding them in files.
By default, mcp-use requires explicit user action to trigger OAuth authentication. When a server requires authentication, the connection enters pending_auth state and you must call the authenticate() method:
Copy
Ask AI
const mcp = useMcp({ url: "http://localhost:3000/mcp", // preventAutoAuth: true is the default});// Manually trigger authentication when readyif (mcp.state === "pending_auth") { return <button onClick={mcp.authenticate}>Sign in to continue</button>;}
To enable automatic OAuth flow (legacy behavior), set preventAutoAuth: false:
Bearer token for authentication (added to Authorization header)
auth_token
string
No
Alternative snake_case form of authToken (for Python config compatibility)
headers
object
No
Custom HTTP headers including authentication headers
Configuration Compatibility: Both authToken (camelCase) and auth_token
(snake_case) are accepted for token-based authentication. Use authToken for
TypeScript conventions; auth_token is supported for compatibility with
Python-style configurations.