Skip to main content

OAuth Client

The @leanmcp/auth/client module provides a complete OAuth 2.1 client implementation for MCP applications. It handles browser-based authentication flows with PKCE, secure token storage, and automatic token refresh.

Features

OAuth 2.1 with PKCE

Secure authorization code flow with Proof Key for Code Exchange

Token Storage

Pluggable storage backends: memory, file, or OS keychain

Auto Refresh

Automatic token refresh before expiration

Dynamic Registration

RFC 7591 Dynamic Client Registration support

Installation

For file-based storage with encryption:
For OS keychain storage:

Quick Start


OAuthClient

The main client class for OAuth 2.1 flows.

Constructor Options

Methods

authenticate()

Initiates the OAuth flow by opening a browser window for user authentication.
Flow:
  1. Generates PKCE code verifier and challenge (if enabled)
  2. Opens browser to authorization endpoint
  3. Starts local HTTP server to receive callback
  4. Exchanges authorization code for tokens
  5. Stores tokens in configured storage

getValidToken()

Returns a valid access token, refreshing if necessary.
If the current token is expired and a refresh token is available, it will automatically refresh. Throws if no valid token is available.

getTokens()

Returns the current stored tokens without refreshing.

logout()

Clears stored tokens.

Token Storage

The @leanmcp/auth/storage module provides pluggable storage backends for tokens.

MemoryStorage

Stores tokens in memory. Tokens are lost when the process exits.
Use cases:
  • Development and testing
  • Short-lived CLI commands
  • Serverless functions (tokens passed externally)

FileStorage

Stores tokens in a JSON file with optional encryption.
Example with encryption:
If using encryption, store the encryption key securely (e.g., environment variable). Losing the key means losing access to stored tokens.

KeychainStorage

Stores tokens in the OS secure keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service).
Requires the keytar package: npm install keytar
Use cases:
  • Desktop CLI applications
  • Developer tools
  • Any application where OS-level security is preferred

Custom Storage

Implement the TokenStorage interface for custom backends:

PKCE Flow

PKCE (Proof Key for Code Exchange) is enabled by default and required by the MCP OAuth specification. The client automatically:
  1. Generates a cryptographically random code_verifier
  2. Creates the code_challenge using SHA-256
  3. Sends the challenge with the authorization request
  4. Sends the verifier with the token exchange

Token Refresh

Automatic Refresh

When autoRefresh is enabled, getValidToken() automatically refreshes expired tokens:

Manual Refresh

You can also manually refresh tokens:

Complete Example

Here’s a complete CLI application that authenticates with an OAuth server:

API Reference

TokenSet

TokenStorage Interface