Skip to content
Connect a user’s account

Connect a user’s account

Let each user authorize an integration, then make its tools available to their agent.

Before you start#

You need a server-side API key, a signed-in user in your application, and an enabled integration in Integrations. Enable that integration in the world where the agent will use it, too.

Read the integration catalog to offer the available connection options. Its authScheme is oauth2, api_key, or none. Providers such as GitHub can use either OAuth or API keys depending on your workspace setup. Integrations with none need no user connection.

1. Open the hosted connection flow#

The same connect-session endpoint handles both OAuth consent and API-key entry. OAuth users sign in with the provider; API-key users enter their credentials on Smallworld’s hosted form.

Use the following functions in your backend handlers. Pass the user ID from your application’s authenticated session. Choose a return URL on your application; use HTTPS in production or HTTP on loopback for local development.

Connection helpers · server-side TypeScript
const baseUrl = "https://api.smallworld.sh/api/v1";
const apiKey = process.env.SMALLWORLD_API_KEY;
if (!apiKey) throw new Error("Set SMALLWORLD_API_KEY on your server");

async function request<T>(path: string, body?: unknown): Promise<T> {
  const response = await fetch(baseUrl + path, {
    method: body === undefined ? "GET" : "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      ...(body === undefined ? {} : { "Content-Type": "application/json" }),
    },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
  const data = await response.json();
  if (!response.ok) throw new Error(`${response.status} ${data.code}: ${data.message}`);
  return data as T;
}

type Connection = {
  integration: string;
  userId: string;
  status: "connected" | "needs_reauth" | "not_connected";
  accountName: string | null;
};
type ConnectSession = {
  id: string;
  userId: string;
  status: "pending" | "awaiting_confirmation" | "completed" | "failed" | "expired" | "cancelled";
  connectUrl?: string;
  expiresAt: string;
  connection: Connection | null;
  error: { code: string; message: string } | null;
};

// Call from your authenticated backend; choose returnUrl in server configuration.
async function beginConnection(userId: string, integration: string, returnUrl: string) {
  const session = await request<ConnectSession>(
    `/users/${encodeURIComponent(userId)}/connect-sessions`,
    { integration, redirectUrl: returnUrl, requireConfirmation: true },
  );
  if (!session.connectUrl) throw new Error("Missing hosted connection URL");
  return { sessionId: session.id, connectUrl: session.connectUrl };
}

// savedSessionId comes from your backend's record of beginConnection's result.
// userId comes from the login session after the browser returns.
async function finishConnection(userId: string, savedSessionId: string) {
  const path = `/connect-sessions/${encodeURIComponent(savedSessionId)}`;
  let session = await request<ConnectSession>(path);
  if (session.userId !== userId) throw new Error("This connection belongs to another user");
  if (session.status === "awaiting_confirmation")
    session = await request<ConnectSession>(path + "/confirm", { userId });
  return session;
}

Call beginConnection(userId, integration, returnUrl), save the returned sessionId against that user in your backend, and send their browser to connectUrl. Creation also registers a new user automatically. The URL is sensitive and is returned only once; keep it out of analytics and logs.

2. Verify the returning user and activate the connection#

When the user returns, authenticate them again and load their saved connect-session ID. Call finishConnection with those server-side values. Redirect query parameters such as status and connectSessionId are hints; the session read is authoritative.

With requireConfirmation: true, credentials stay inactive at awaiting_confirmation until your backend confirms the signed-in user. A completed attempt returns status: "completed" and its connection. Show the connected account name to the user.

  • pending: the flow is unfinished; read again after a short delay rather than creating another attempt.
  • failed, expired, or cancelled: show the returned error and offer a new attempt. A successful HTTP read can still report a failed connection.
  • Use the session’s expiresAt for its deadline. A new attempt for the same user and integration supersedes earlier pending attempts.

If confirmation returns a conflict or its response is lost, read the session again before deciding what to show. Confirm only awaiting_confirmation; a second confirmation of an already completed session returns a conflict.

3. Refresh the user’s tools#

Reload the user’s world tool catalog and pass it to your agent. Execute with the same application userId, following the Quick start. Connections belong to the user and integration and work across worlds whose policies allow them.

To share one account with everyone at a customer, connect it for a group instead; see Connect a group. A user’s own connection replaces a group’s connection to the same integration in all of their sessions.

Use Get a connection to show ongoing connection state. If it becomes needs_reauth, ask the user to connect again. Disconnect when the user removes access.

Collect an API key in your own application#

You can also collect the catalog’s credentialFields in your own form and send their string values from your backend. Use each field’s nameas the key, and follow credentialInstructions. This route supports api_key integrations only.

Save credentials from your backend
// Reuse request<T> from the example above.
// userId is your authenticated application user, not a browser-supplied ID.
async function saveApiKey(userId: string, integration: string, credentials: Record<string, string>) {
  const catalog = await request<{
    items: { key: string; enabled: boolean; authScheme: string }[];
  }>("/integrations");
  const option = catalog.items.find((item) => item.key === integration);
  if (!option?.enabled || option.authScheme !== "api_key")
    throw new Error("Choose an enabled API-key integration");
  return request<Connection>(
    `/users/${encodeURIComponent(userId)}/connections/${encodeURIComponent(integration)}`,
    { credentials },
  );
}

Saving credentials verifies them with the provider and returns the connection without secret values. Handle integration_credentials_invalid by asking the user to check their input; integration_provider_unavailable means verification could not reach the provider. Keep user credentials out of model messages, application logs, and client storage.

Use your own OAuth app#

OAuth app setup belongs to your workspace, before users connect. In Integrations, choose the provider and follow its setup. For providers with connection-method options, choose Custom branding, register an app using the displayed callback URL, and enter its client ID and client secret. Follow the provider-specific scope and setup instructions shown there.

If the provider already uses Quick setup, open its Settings tab, choose Change connection method, and configure your OAuth app. That switch applies to new connections; existing token connections continue to work. For an MCP server, use its OAuth app settings when the server requires your own app.

Your application’s return URL and the provider callback URL serve different steps: use the exact callback shown in integration setup for the OAuth app. For your own API tools, follow Build a custom integration; those endpoints receive the user’s ID directly.