Skip to main content

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 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>;
}

Custom OAuth Provider (Headless/Testing)

If you run in non-browser environments (tests, headless runners, custom redirects), you can inject your own OAuth provider.
import { useMcp } from "mcp-use/react";
import { MyOAuthClientProvider } from "./my-oauth-provider";

const mcp = useMcp({
  url: "http://localhost:3000/mcp",
  authProvider: new MyOAuthClientProvider(),
});
When authProvider is provided, useMcp uses that provider directly instead of creating the default browser OAuth provider internally.

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, saved under the name "my-server"
npx mcp-use client connect my-server https://api.example.com/mcp \
  --auth sk-your-api-key

# List tools on that saved server
npx mcp-use client my-server tools list

# Call a tool
npx mcp-use client my-server tools call send_email to=user@example.com

# Disconnect
npx mcp-use client my-server disconnect
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)

OAuth options are passed to useMcp (and to addServer on McpClientProvider) at the top level for transport/callback settings, plus a nested oauth object for pre-registered client credentials.
ParameterTypeRequiredDescription
callbackUrlstringNoOAuth redirect URL (defaults to /oauth/callback on the current origin)
useRedirectFlowbooleanNoUse full-page redirect instead of popup (default: false)
preventAutoAuthbooleanNoWait for authenticate() instead of auto-triggering OAuth (default: true)
oauth.clientIdstringNo*Pre-registered OAuth client ID. When set, the SDK skips Dynamic Client Registration.
oauth.clientSecretstringNoPre-registered OAuth client secret for confidential clients without PKCE. Requires clientId.
oauth.scopestringNoOAuth scopes string included in the authorize request

Pre-registered Client Credentials

Some MCP servers strip the registration_endpoint from their auth-server metadata, which means Dynamic Client Registration is unavailable. For these servers, register a client with the provider yourself and pass the credentials through oauth:
import { useMcp } from "mcp-use/react";

const mcp = useMcp({
  url: "https://mcp.example.com",
  oauth: {
    clientId: "my-preregistered-client-id",
    clientSecret: "my-preregistered-client-secret",
    scope: "openid profile email",
  },
});
When clientSecret is also set, the SDK auto-switches token-endpoint authentication from none to client_secret_basic or client_secret_post (whichever the auth server advertises in token_endpoint_auth_methods_supported). Drop clientSecret for public clients using PKCE.
clientSecret is persisted in the browser’s localStorage so it can be reused across page loads and during the OAuth callback. Only ship pre-registered secrets to first-party UIs where exposing the secret to the end user is acceptable.

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.