Skip to main content
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.

Supported Authentication Methods

  • OAuth 2.1: Complete OAuth flow with automatic Dynamic Client Registration (DCR)
  • Bearer Tokens: API key and token-based authentication
  • Custom Headers: Flexible authentication header support

OAuth Authentication

OAuth provides secure, token-based authentication with automatic token refresh and user consent flows.
import { useMcp } from "mcp-use/react";

function MyComponent() {
  const mcp = useMcp({
    url: "http://localhost:3000/mcp",
    callbackUrl: "http://localhost:3000/callback",
  });

  // Handle authentication states
  if (mcp.state === "pending_auth") {
    return <button onClick={mcp.authenticate}>Authenticate with OAuth</button>;
  }

  if (mcp.state === "authenticating") {
    return <div>Authenticating...</div>;
  }

  if (mcp.state === "ready") {
    return <div>Connected! {mcp.tools.length} tools available</div>;
  }

  return <div>Connecting...</div>;
}

Bearer Token Authentication

For servers requiring API keys or bearer tokens:
import { useMcp } from 'mcp-use/react'

function MyComponent() {
const mcp = useMcp({
url: 'http://localhost:3000/mcp',
headers: {
Authorization: 'Bearer sk-your-api-key-here'
}
})

// Use mcp.tools, mcp.callTool, etc.
}

Node.js Client Authentication

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.

Bearer Token Authentication

The simplest way to authenticate with API-based MCP servers:
import { MCPClient } from 'mcp-use'

const config = {
mcpServers: {
"my-server": {
url: "https://api.example.com/mcp",
authToken: "sk-your-api-key-here"
}
}
}

const client = MCPClient.fromDict(config)

Custom Headers

For servers requiring custom authentication headers or additional metadata:
import { MCPClient } from "mcp-use";

const config = {
  mcpServers: {
    "my-server": {
      url: "https://api.example.com/mcp",
      headers: {
        Authorization: "Bearer sk-your-api-key",
        "X-API-Version": "2024-01-01",
        "X-Custom-Header": "value",
      },
    },
  },
};

const client = MCPClient.fromDict(config);

Configuration File

Load authentication settings from a JSON configuration file:
import { MCPClient } from 'mcp-use'

// Constructor accepts file path directly
const client = new MCPClient('./mcp-config.json')

// Or use fromDict with imported config
import 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.

CLI Authentication

The mcp-use CLI client supports bearer token authentication for connecting to secured MCP servers:
# Connect with bearer token
npx mcp-use client connect https://api.example.com/mcp \
  --name my-server \
  --auth sk-your-api-key

# List tools (uses saved authentication)
npx mcp-use client tools list

# Call a tool
npx mcp-use client tools call send_email '{"to":"user@example.com"}'

# Disconnect
npx mcp-use client disconnect my-server
The CLI automatically saves authentication tokens in ~/.mcp-use/cli-sessions.json for future sessions.
For complete CLI documentation including stdio connections, session management, and interactive mode, see the CLI Client Guide.

OAuth Flow Modes

mcp-use supports two OAuth flow modes for client applications: Opens OAuth authorization in a popup window. Best for desktop and web applications. Advantages:
  • User stays on the same page
  • Better UX for web applications
  • No navigation interruption
Usage:
const mcp = useMcp({
  url: "http://localhost:3000/mcp",
  callbackUrl: "http://localhost:3000/callback",
  // Popup flow is the default
});

Redirect Flow

Redirects the current window to the OAuth provider, then back to your app. Advantages:
  • Works in all browsers (popup blockers won’t interfere)
  • Better for mobile browsers
  • More reliable across different environments
Usage:
const mcp = useMcp({
  url: "http://localhost:3000/mcp",
  callbackUrl: "http://localhost:3000/callback",
  useRedirectFlow: true, // Enable redirect flow
});
Setup for Redirect Flow:
  1. Create a callback page in your app:
// pages/callback.tsx or app/callback/page.tsx
import { onMcpAuthorization } from "mcp-use/auth";
import { useEffect, useState } from "react";

export default function OAuthCallback() {
  const [status, setStatus] = useState<"processing" | "success" | "error">(
    "processing"
  );

  useEffect(() => {
    onMcpAuthorization()
      .then(() => {
        setStatus("success");
        // Redirect back to main app
        setTimeout(() => (window.location.href = "/"), 1000);
      })
      .catch((err) => {
        setStatus("error");
        console.error("Auth failed:", err);
      });
  }, []);

  if (status === "processing") {
    return <div>Completing authentication...</div>;
  }
  if (status === "success") {
    return <div>Success! Redirecting...</div>;
  }
  return <div>Authentication failed</div>;
}
  1. Configure your callback URL to match this route:
const mcp = useMcp({
  url: "http://localhost:3000/mcp",
  callbackUrl: "http://localhost:3000/callback", // Your callback page
  useRedirectFlow: true,
});

Manual Authentication Control

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:
const mcp = useMcp({
  url: "http://localhost:3000/mcp",
  // preventAutoAuth: true is the default
});

// Manually trigger authentication when ready
if (mcp.state === "pending_auth") {
  return <button onClick={mcp.authenticate}>Sign in to continue</button>;
}
To enable automatic OAuth flow (legacy behavior), set preventAutoAuth: false:
const mcp = useMcp({
  url: "http://localhost:3000/mcp",
  preventAutoAuth: false, // Auto-trigger OAuth popup
});

OAuth Flow Process

When OAuth authentication is required:

Configuration Options

Node.js Client Configuration Parameters

ParameterTypeRequiredDescription
urlstringYesMCP server endpoint URL
authTokenstringNoBearer token for authentication (added to Authorization header)
auth_tokenstringNoAlternative snake_case form of authToken (for Python config compatibility)
headersobjectNoCustom 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.

OAuth Configuration Parameters (Browser Only)

ParameterTypeRequiredDescription
client_idstringNo*OAuth client ID (required if not using DCR)
client_secretstringNoOAuth client secret (required if not using DCR)
scopestringNoOAuth scopes to request
callback_portintegerNoPort for OAuth callback (default: 8080)
oauth_providerobjectNoOAuth provider metadata
*Required unless using Dynamic Client Registration

Port Configuration

  • Default Port: 8080
  • Custom Ports: Any available port (e.g., 8081, 8082, 3000)
  • Port Conflicts: mcp-use will check if the port is available before starting OAuth flow

Example Servers that support OAuth

OAuth with DCR Support

  • Linear: https://mcp.linear.app/mcp

OAuth with Manual Registration

  • GitHub: https://api.githubcopilot.com/mcp/

Bearer Token

  • Most API-based MCP servers
Check your server’s documentation for specific authentication requirements and supported methods.