Auth API
Theclient.auth namespace manages the OAuth PKCE flow. Here is the full interface:
How it works
- You call
client.connect()(orclient.auth.signIn()). - If the user has no valid tokens, the client fires
onAuthRequiredwith the OAuth URL. - The user authorizes in the browser. The OAuth server redirects to your
redirectUri. - You pass the callback URL to
client.auth.handleCallback()to exchange the code for tokens. - The client reconnects and transitions to
ready.
onAuthRequired and route the callback URL back to the client.
The onAuthRequired callback
This callback controls how your application opens the OAuth page. It receives aURL and can return in three ways:
- Return the callback URL (string or URL): The client completes the flow inline, no separate
handleCallback()call needed. - Return void: You handle the callback yourself by calling
client.auth.handleCallback()later. - Return a Promise: Same options, but async.
Browser redirect
The most common pattern for web applications. The user leaves the page, authorizes, and comes back to your redirect URI.Use persistent storage (for example
localStorage) for browser redirect flows.
MemoryStorage resets on reload, which can drop PKCE state before the callback
is handled. See Storage.Popup window
Open OAuth in a popup and listen for the callback. The main page stays loaded.CLI / Node.js
For command-line tools, open the browser and start a local HTTP server to catch the callback.onAuthRequired returns the callback URL as a string. The client exchanges the authorization code for tokens internally, so you do not need to call handleCallback() separately.
Sign out
client.auth.signOut() clears stored tokens and moves the client back to the idle state. The next connect() call will trigger onAuthRequired again.
Check authentication status
client.auth.isAuthenticated returns true when the client is in the ready state or has an active MCP connection. Use this to conditionally render sign-in UI.
Next steps
- Storage — Persist tokens across page reloads and process restarts.
- Tools — Discover and execute MCP tools.
- Client Types — Full type reference for
KontextClientand auth interfaces.