Authentication API client for the Mosaia SDK

Provides the authentication flows used to obtain a session:

  • Password-based authentication
  • Client credentials authentication
  • Token refresh operations
  • OAuth token management
  • Sign out / session teardown

The canonical entry point is the auth getter on MosaiaClient. Every getter returns a MosaiaAuth bound to the client's current configuration — you should not normally construct MosaiaAuth directly.

Every sign-in method returns a new MosaiaConfig with the access token populated into apiKey (that's what the request-signing layer reads) and a structured session object carrying refresh token, expiry, and identity. Pass the returned config into a new MosaiaClient to get an authenticated client.

Client credentials (server-side, recommended for backends):

import * as Mosaia from '@mosaia/mosaia-node-sdk';

// 1. Initialize an unauthenticated client — credentials do not need to be
// in config for client credentials; pass them directly to signInWithClient.
const mosaia = new Mosaia.MosaiaClient({
apiURL: 'https://api.mosaia.ai'
});

// 2. Exchange the credentials for a session via the `auth` getter.
const authenticatedConfig = await mosaia.auth.signInWithClient(
process.env.MOSAIA_CLIENT_ID!,
process.env.MOSAIA_CLIENT_SECRET!
);

// 3. Build the authenticated client. Use this one for every subsequent call.
const authedMosaia = new Mosaia.MosaiaClient(authenticatedConfig);

Password grant (requires clientId on the config):

const mosaia = new Mosaia.MosaiaClient({
clientId: process.env.MOSAIA_CLIENT_ID!
});

const authenticatedConfig = await mosaia.auth.signInWithPassword(
'user@example.com',
'password'
);

const authedMosaia = new Mosaia.MosaiaClient(authenticatedConfig);

Token refresh and sign out on the authenticated client:

// Refresh uses the refresh token from `authedMosaia.config.session`
authedMosaia.config = await authedMosaia.auth.refreshToken();

// Tear down the session
await authedMosaia.auth.signOut();

Constructors

  • Creates a new Authentication API client instance

    Initializes the authentication client with an optional configuration. If no configuration is provided, it uses the ConfigurationManager to get the current configuration.

    Parameters

    • Optionalconfig: MosaiaConfig

      Optional configuration object. If omitted, the singleton ConfigurationManager is consulted.

      Configuration interface for the Mosaia SDK

      This interface defines all configuration options available when initializing the Mosaia SDK client. It includes authentication settings, API endpoints, and optional context parameters.

      • OptionalapiKey?: string

        API key for authentication (optional if using OAuth)

      • Optionalversion?: string

        API version to use (defaults to '1')

      • OptionalapiURL?: string

        Base URL for API requests (defaults to https://api.mosaia.ai)

      • OptionalsseURL?: string

        Base URL for the SSE relay server (defaults to https://sse.mosaia.ai)

      • OptionalclientId?: string

        Client ID for client credentials flows (Optional)

      • OptionalclientSecret?: string

        Client secret for client credentials flow (optional)

      • Optionalverbose?: boolean

        Enable verbose HTTP request/response logging (defaults to false)

      • Optionalsession?: SessionCredentials

        Session credentials for OAuth and token-based authentication (optional)

    Returns MosaiaAuth

    Prefer mosaia.auth on an existing MosaiaClient over new MosaiaAuth(...) — the getter wires the correct config automatically. Direct construction is supported for advanced cases (e.g. scripts that don't hold a MosaiaClient reference).

    // Preferred: use the `auth` getter on a MosaiaClient. Credentials are
    // passed as arguments to signInWithClient — no need to put them in config.
    const mosaia = new MosaiaClient({ apiURL: 'https://api.mosaia.ai' });
    const authenticatedConfig = await mosaia.auth.signInWithClient(
    process.env.MOSAIA_CLIENT_ID!,
    process.env.MOSAIA_CLIENT_SECRET!
    );
    const authedMosaia = new MosaiaClient(authenticatedConfig);
    // Direct construction — uses the global ConfigurationManager by default
    const auth = new MosaiaAuth();

    // Or with an explicit config
    const auth = new MosaiaAuth({
    apiURL: 'https://api.mosaia.ai',
    clientId: 'your-client-id'
    });

    When required configuration values are missing

Methods

  • Sign in using email and password authentication

    Authenticates a user with their email and password credentials. Returns a configured Mosaia client instance with the obtained access token.

    Parameters

    • email: string

      The user's email address

    • password: string

      The user's password

    Returns Promise<MosaiaConfig>

    Promise that resolves to a configured Mosaia client instance

    The clientId is automatically retrieved from the configuration. Ensure the configuration has a clientId set before calling this method.

    When authentication fails or network errors occur

    When clientId is not found in configuration

    // 1. Unauthenticated client with clientId in the config
    const mosaia = new MosaiaClient({
    clientId: process.env.MOSAIA_CLIENT_ID!
    });

    try {
    // 2. Exchange email + password for a session via the `auth` getter
    const authenticatedConfig = await mosaia.auth.signInWithPassword(
    'user@example.com',
    'password'
    );

    // 3. Build the authenticated client
    const authedMosaia = new MosaiaClient(authenticatedConfig);
    } catch (error) {
    console.error('Authentication failed:', error.message);
    }
  • Sign in using client credentials authentication

    Authenticates an application using a client ID and client secret. This is the standard flow for server-to-server access (cron jobs, background workers, CI).

    Parameters

    • clientId: string

      The OAuth client ID (the name of a Mosaia Client resource)

    • clientSecret: string

      The OAuth client secret (returned only once on Client create)

    Returns Promise<MosaiaConfig>

    Promise that resolves to a MosaiaConfig carrying the new session

    When authentication fails or network errors occur

    clientId / clientSecret are passed as arguments — you do not need to put them on the MosaiaConfig. Run this three-step flow to get a bearer token:

    1. Initialize an unauthenticated MosaiaClient.
    2. Call mosaia.auth.signInWithClient(clientId, clientSecret).
    3. Construct a new MosaiaClient with the returned authenticated config.
    import * as Mosaia from '@mosaia/mosaia-node-sdk';

    // 1. Initialize an unauthenticated client
    const mosaia = new Mosaia.MosaiaClient({ apiURL: 'https://api.mosaia.ai' });

    try {
    // 2. Exchange the credentials for a session
    const authenticatedConfig = await mosaia.auth.signInWithClient(
    process.env.MOSAIA_CLIENT_ID!,
    process.env.MOSAIA_CLIENT_SECRET!
    );

    // 3. Build the authenticated client — this one carries the bearer token
    const authedMosaia = new Mosaia.MosaiaClient(authenticatedConfig);
    const agents = await authedMosaia.agents.get();
    } catch (error) {
    console.error('Client authentication failed:', error.message);
    }
  • Refresh an access token using a refresh token

    Obtains a new access token using an existing refresh token. This method can be used to extend a user's session without requiring them to re-enter their credentials.

    Parameters

    • Optionaltoken: string

      Optional refresh token. If not provided, attempts to use the refresh token from the current configuration

    Returns Promise<MosaiaConfig>

    Promise that resolves to an updated MosaiaConfig

    When refresh token is missing or refresh fails

    // `authedMosaia` is the authenticated client produced by a prior sign-in
    try {
    // Refresh using the refresh token stored in authedMosaia.config.session
    authedMosaia.config = await authedMosaia.auth.refreshToken();

    // Or provide a specific refresh token
    authedMosaia.config = await authedMosaia.auth.refreshToken('specific-refresh-token');
    } catch (error) {
    console.error('Token refresh failed:', error.message);
    }
  • Refreshes an OAuth access token using a refresh token

    This method exchanges a refresh token for a new access token when the current access token expires. This allows for long-term authentication without requiring user re-authentication.

    Parameters

    • refreshToken: string

      The refresh token received from the initial token exchange

    Returns Promise<MosaiaConfig>

    Promise that resolves to a new OAuth token response

    When the refresh fails (invalid refresh token, expired, etc.)

    // When access token expires, use refresh token to get new tokens
    try {
    const mosaiaConfig = await oauth.refreshToken(refreshToken);
    mosaia.config = mosaiaConfig;
    console.log('New access token:', mosaiaConfig.apiKey);
    console.log('New refresh token:', mosaiaConfig.refreshToken);
    } catch (error) {
    // Refresh token expired, user needs to re-authenticate
    console.error('Token refresh failed:', error);
    }
  • Sign out and invalidate the current session

    Invalidates the current access token and clears the configuration. This method should be called when a user logs out or when you want to ensure the current session is terminated.

    Parameters

    • OptionalapiKey: string

      Optional API key to sign out. If not provided, uses the API key from the current configuration

    Returns Promise<void>

    Promise that resolves when sign out is complete

    When API key is missing or sign out fails

    try {
    // Tear down the session on the authenticated client
    await authedMosaia.auth.signOut();

    // Or sign out a specific token (e.g. during a controlled rotation)
    await authedMosaia.auth.signOut('specific-api-key');
    } catch (error) {
    console.error('Sign out failed:', error.message);
    }