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
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.- Generates PKCE code verifier and challenge (if enabled)
- Opens browser to authorization endpoint
- Starts local HTTP server to receive callback
- Exchanges authorization code for tokens
- Stores tokens in configured storage
getValidToken()
Returns a valid access token, refreshing if necessary.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.- Development and testing
- Short-lived CLI commands
- Serverless functions (tokens passed externally)
FileStorage
Stores tokens in a JSON file with optional encryption.KeychainStorage
Stores tokens in the OS secure keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service).Requires the
keytar package: npm install keytar- Desktop CLI applications
- Developer tools
- Any application where OS-level security is preferred
Custom Storage
Implement theTokenStorage 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:- Generates a cryptographically random
code_verifier - Creates the
code_challengeusing SHA-256 - Sends the challenge with the authorization request
- Sends the verifier with the token exchange
Token Refresh
Automatic Refresh
WhenautoRefresh 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
Related
- Authentication Overview - Server-side authentication with
@Authenticateddecorator - OAuth Server - Build OAuth authorization servers with proxy support
- GPT Apps Authentication - Client-side auth in ChatGPT Apps

