# Connect a group

Share one connected account with every user in a group, such as the people at one of your customers.

## How groups work

A group is a set of represented users. A user can belong to several groups, and each session acts for one of them. Connect an integration once for the group, and each member’s calls in a session for the group use the group’s account unless the member has a connection of their own to that integration.

- The member stays the acting user. Executions, sessions, tool policies, approvals, hooks, and history are the user’s; the group’s connection only decides which provider account the calls use.

- A group’s connection doesn’t bypass anything: the integration still has to be on for the workspace and the World, and tool policies and [hooks](https://smallworld.sh/docs/guides/tool-call-hooks.md) still apply.

- Integrations without a connection, such as Web Access, custom integrations, and MCP servers without sign-in, work as before. There is nothing to connect for a group.

You need a server-side [API key](https://smallworld.sh/docs/authentication.md) and an enabled integration, as in [Connect a user’s account](https://smallworld.sh/docs/guides/connect-user.md). Your application manages group membership and decides who may manage a group’s connections and tool policies; Smallworld only checks that the group belongs to your workspace.

## 1. Create the group and add users

Use your own ID for the group, such as your customer organization’s ID. [Creating a group](https://smallworld.sh/docs/create-group.md) returns `201` the first time and `200` with the stored group after that, so you can call it whenever you need the group. The ID can’t change; the name is optional and can be changed with [PATCH](https://smallworld.sh/docs/update-group.md).

Group helpers · server-side TypeScript

```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>(method: string, path: string, body?: unknown): Promise<T> {
  const response = await fetch(baseUrl + path, {
    method,
    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 Group = { id: string; name: string | null; system: boolean; memberCount: number };
type User = { id: string; email: string | null; groupIds: string[] };
type GroupDetail = Group & { users: { items: User[]; nextCursor: string | null } };
const groupPath = (groupId: string) => `/groups/${encodeURIComponent(groupId)}`;

// Safe to repeat: an existing group is returned with its stored name.
async function ensureGroup(groupId: string, name: string | null) {
  return request<Group>("POST", "/groups", { groupId, name });
}

// Each group read includes a page of users; memberCount is the total across all pages.
async function getGroup(groupId: string, cursor?: string) {
  const query = new URLSearchParams({ limit: "50" });
  if (cursor) query.set("cursor", cursor);
  return request<GroupDetail>("GET", `${groupPath(groupId)}?${query}`);
}

// Adds the group and keeps the user's other groups. Creates the user if needed.
async function addMember(groupId: string, userId: string) {
  return request<User>("PUT", `/users/${encodeURIComponent(userId)}${groupPath(groupId)}`);
}

// A move: a user with no group joins, and a user in one other group leaves it for this one.
// Fails with user_in_multiple_groups for a user in several groups. Creates the user if needed.
async function moveMember(groupId: string, userId: string) {
  return request<User>("PUT", `${groupPath(groupId)}/users/${encodeURIComponent(userId)}`);
}

// Removes this one membership. Changes nothing when the user is not in the group.
async function removeMember(groupId: string, userId: string) {
  return request<User>("DELETE", `${groupPath(groupId)}/users/${encodeURIComponent(userId)}`);
}
```

[Get a group](https://smallworld.sh/docs/get-group.md) returns its details and a page of full user records in `users.items`. It returns up to `50` users by default; set `limit` from `1` to `100` to choose the page size. Pass `users.nextCursor` as `cursor` to the same endpoint for the next page, until it is `null`. The cursor is specific to this group and workspace, and `memberCount` always counts all members.

- [Adding a user](https://smallworld.sh/docs/add-user-group.md) keeps their other groups, and creates a user who doesn’t exist yet. Adding a user to a group they are already in changes nothing.

- [Moving a user](https://smallworld.sh/docs/add-group-user.md) is for users in at most one group: a user with no group joins, and a user in one other group leaves it for this one in one step. For a user in several groups it returns `user_in_multiple_groups`.

- You can also set memberships with [POST /users](https://smallworld.sh/docs/create-user.md), for new and existing users. `groupId` is a move, and `groupId: null` removes the user from every group. `groupIds` replaces the whole list at once. Leave both out to keep the user’s groups.

- [Removing a user](https://smallworld.sh/docs/remove-group-user.md) removes that one membership and only acts while they still belong to that group, so a delayed removal never undoes a newer move.

- Create groups from your backend with `POST /groups`. An unknown group returns `group_not_found`, and nothing is created, not even the user.

A session acts for at most one group, fixed when the session is created. For a user with no group or one group you don’t pass a group when you execute: a user with one group gets a session for that group, and a user with no group gets a groupless session, which uses personal and workspace-wide resources only and stays groupless when the user joins a group later. Add users to their group before you create their first session if it should use the group’s connections. For a user in several groups, see [Users in several groups](#several-groups).

## 2. Connect an account for the group

[Group connect sessions](https://smallworld.sh/docs/create-group-connect-session.md) work like a user’s: the same hosted page handles OAuth consent and API-key entry. The API-key form names the group, such as “Connect GitHub for Support team”, and says that everyone in the group can use the account. A group without a name is called “your team”.

Group connection helpers · server-side TypeScript

```typescript
// Reuse request<T> and groupPath from the example above.
type ConnectSession = {
  id: string;
  userId: string | null;
  groupId: string | null;
  status: "pending" | "awaiting_confirmation" | "completed" | "failed" | "expired" | "cancelled";
  connectUrl?: string;
  connection: { accountName: string | null } | null;
  error: { code: string; message: string } | null;
};

// Call only after your backend checked that the signed-in person may connect accounts for this group.
async function beginGroupConnection(groupId: string, integration: string, returnUrl: string) {
  const session = await request<ConnectSession>("POST", `${groupPath(groupId)}/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 beginGroupConnection's result.
// groupId is the group the returning person acts for; check their authority again first.
async function finishGroupConnection(groupId: string, savedSessionId: string) {
  const path = `/connect-sessions/${encodeURIComponent(savedSessionId)}`;
  let session = await request<ConnectSession>("GET", path);
  if (session.groupId !== groupId) throw new Error("This connection belongs to another group");
  if (session.status === "awaiting_confirmation") session = await request<ConnectSession>("POST", path + "/confirm", { groupId });
  return session;
}
```

With `requireConfirmation: true`, credentials stay inactive at `awaiting_confirmation` until your backend [confirms the session](https://smallworld.sh/docs/confirm-connect-session.md) with `{ groupId }`. Before confirming, check again that the person who returned may connect accounts for that group. A different group, or a `userId`, fails the attempt with `connect_session_group_mismatch` and discards the credentials.

Other session states work as for users. A new attempt for the group and integration supersedes the group’s earlier pending attempts; members’ own attempts are not affected.

## Collect an API key in your own application

For `api_key` integrations, your backend can also [save the group’s credentials](https://smallworld.sh/docs/save-group-connection.md) directly. Collect the catalog’s `credentialFields` as in [Connect a user’s account](https://smallworld.sh/docs/guides/connect-user.md). Smallworld checks them with the provider and stores them once for the whole group.

Save group credentials from your backend

```typescript
// Reuse request<T> and groupPath from the first example.
async function saveGroupApiKey(groupId: string, integration: string, credentials: Record<string, string>) {
  return request<{ status: string; accountName: string | null }>(
    "POST",
    `${groupPath(groupId)}/connections/${encodeURIComponent(integration)}`,
    { credentials },
  );
}
```

## 3. Check which account each user gets

[A user’s connections](https://smallworld.sh/docs/list-connections.md) list, for each integration, the account their calls use. `source` is `personal` for their own account or `group` for the group’s, with `groupId` naming the group. `overridesGroup` is `true` when the user’s own account hides the group’s. For a user in several groups, add `?groupId=` to read the connections for one of them. [A group’s connections](https://smallworld.sh/docs/list-group-connections.md) list only the group’s own accounts.

| User’s own connection | Group’s connection | Result |
| --- | --- | --- |
| Connected | Any | The user’s own account, `source: "personal"` |
| --- | --- | --- |
| Needs reauthorization | Any | No account until the user reconnects: `needs_reauth`, `source: "personal"` |
| --- | --- | --- |
| None, or disconnected | Connected | The group’s account, `source: "group"` |
| --- | --- | --- |
| None, or disconnected | Needs reauthorization | No account until the group reconnects: `needs_reauth`, `source: "group"` |
| --- | --- | --- |
| None, or disconnected | None | `not_connected` |
| --- | --- | --- |

- A personal connection replaces the group’s whole account. The user gets the tools, identity, and permissions of one account, never a mix of both.

- A personal connection that needs reauthorization still wins: the user doesn’t fall back to the group’s account. Ask them to reconnect, or [disconnect](https://smallworld.sh/docs/delete-connection.md) their account to use the group’s again.

- `POST` and `DELETE /users/:userId/connections/:integration` change only the user’s own account. Disconnecting a user who only uses the group’s account succeeds and changes nothing. Remove the group’s account with [DELETE /groups/:groupId/connections/:integration](https://smallworld.sh/docs/delete-group-connection.md).

Then reload [the user’s World tool catalog](https://smallworld.sh/docs/list-tools.md); it follows the account the user gets. Tool calls record `connectionSource` (`personal`, `group`, or `none`) and the session’s `group` when the call was made. Hooks receive `user.group` and `integration.connection`, and custom integrations receive `user.group`. `user.group` is the group the session acts for, or `null` in a groupless session.

## Set permissions for the group

A group decides what its sessions may do. [Set](https://smallworld.sh/docs/set-group-tool-policy.md) allow, ask, or deny per tool, [list](https://smallworld.sh/docs/list-group-tool-policies.md) the overrides, and [remove](https://smallworld.sh/docs/delete-group-tool-policy.md) one to inherit again. To make a whole integration unavailable, [turn it off for the group](https://smallworld.sh/docs/set-group-integration.md). Both can also be edited on the group’s page in the dashboard.

- Group permissions apply to every call in the group’s sessions: on the group’s connection, on a member’s own account, and for tools without a connection. Sessions of another group, and groupless sessions, don’t use them.

- Policies resolve as group, then user, then World, then workspace. A group’s override replaces the member’s own: its ask requires approval also after a remembered Allow, its allow runs the tool also for a member whose own override is ask or deny, and its deny hides the tool. The member’s own override stays stored and applies again where the group sets none.

- A group can only turn an integration off. Workspace and World availability stay prerequisites, and a tool the workspace or a World hides stays hidden whatever the group sets.

## Users in several groups

A user can belong to any number of groups, such as a consultant who works for two of your customers. Each session still acts for one group. When you create a session for a user in several groups, send `groupId` with [the execute request](https://smallworld.sh/docs/execute-command.md); without it the request returns `group_required`. Requests for users with no group or one group need no change.

Choose the group for a session · server-side TypeScript

```typescript
// Reuse request<T> from the first example.
type Execution = {
  user: { id: string; groupIds: string[] };
  session: {
    id: string;
    groupId: string | null;
    status: "idle" | "running" | "closed";
    closedReason: "group_membership_removed" | "group_deleted" | null;
  };
  execution: { id: string; status: string; errorCode: string | null };
};
const executePath = (worldId: string) => `/worlds/${encodeURIComponent(worldId)}/execute`;

// groupId chooses the group a new session acts for. It is required when the user belongs to several groups.
async function startGroupSession(worldId: string, userId: string, groupId: string, command: string) {
  return request<Execution>("POST", executePath(worldId), { userId, groupId, command });
}

// The session keeps its group, so later commands send only the sessionId.
async function continueSession(worldId: string, userId: string, sessionId: string, command: string) {
  return request<Execution>("POST", executePath(worldId), { userId, sessionId, command });
}
```

- In the session, the user’s own connection to an integration is used first, also when it needs reconnecting, then the connection of the session’s group. The group’s permissions apply to every call in the session, whichever connection serves it. The session’s mounts are the global ones, those of the session’s group, and the user’s own. Two groups can therefore have different accounts for the same integration and different mounts at the same path.

- The returned `session.groupId` is your ID for the session’s group, or `null` in a groupless session. With `sessionId` you don’t need `groupId`; if you send it, it must be the session’s group, or the request returns `session_group_mismatch`.

- A `groupId` for a group that doesn’t exist returns `group_not_found`, and one for a group the user isn’t in returns `user_not_in_group`. A user with groups can’t start a groupless session, so `groupId: null` is invalid.

- Reads outside a session take `?groupId=` with the same rules: [the World tool catalog](https://smallworld.sh/docs/list-tools.md), [a user’s connections](https://smallworld.sh/docs/list-connections.md), [a user’s mounts](https://smallworld.sh/docs/list-user-mounts.md), and [a user’s tool overrides](https://smallworld.sh/docs/list-user-tool-policies.md).

- User objects list the user’s current groups in `groupIds`, ordered by ID.

## When membership changes

Adding, moving, and removing users succeeds also while they have a running command or a pending approval. What happens to their sessions depends on the change.

- **Add.** The user’s open sessions keep the group they were created for, and a groupless session stays groupless.

- **Move.** The user’s open sessions that acted for the old group now act for the new one. A command running at that moment keeps running: a call prepared with the old group’s connection ends when it is dispatched, pending saves to the old group’s mounts are refused, and the next call uses the new group. A call that waits for approval on the old group’s connection ends `interrupted` with `errorCode: "integration_connection_stale"` and the error `The user's group changed while this tool call was waiting for approval, so the group's connection no longer applies.`

- **Leave.** When a user leaves a group other than by a move, their sessions that acted for that group are closed for good, with `status: "closed"` and `closedReason: "group_membership_removed"`. Their sessions for other groups are unaffected.

In a closed session, a running command is stopped at once and ends `interrupted` with `errorCode: "session_closed"`. A command waiting for approval ends the same way, and its pending tool call ends `interrupted` with `errorCode: "session_closed"` and the error `The session was closed while this tool call was waiting for approval, because the user left the session's group or the group was deleted.` Further execute requests for the session return `session_closed` (409). Its executions, tool calls, and outputs stay readable. Rejoining the group does not reopen it; start a new session.

## Delete a group

[Deleting a group](https://smallworld.sh/docs/delete-group.md) deletes its memberships, connections, pending connect sessions, tool overrides, and mounts. Its members stay, with their other groups, their own connections, and their history. Sessions that acted for the group are closed as when a user leaves, with `closedReason: "group_deleted"`, and `session.groupId` keeps the group’s ID. Tool calls made in the group’s sessions keep its ID and name.

## In the dashboard

The [Groups](https://app.smallworld.sh/app/users?tab=groups) tab in Users shows groups, members, metadata, connected accounts, and tool policies. Ordinary groups are read-only in the dashboard. Manage their creation, names, deletion, membership, connections, and tool overrides from your application’s backend through the API.

The Playground user belongs to the Playground Group, listed with `system: true`. Its name and membership are fixed and it can’t be deleted. Connect either one from the Playground’s Apps menu to try a group connection before writing code. The Playground Group’s tool policies remain editable for testing.
