> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/en/work/maigpt-system-integration-guide.md).

# Add MaiGPT to Your System

An end-to-end guide to adding MaiGPT to your own system for organization members, covering member provisioning, token issuance, frontend embedding, sign-out, and acceptance testing—all on one page

This page walks engineers through adding MaiGPT to their system from start to finish. Whether you run your company's portal, an internal workspace, or a SaaS platform managed for customers, the process is the same as long as users are **members of a MaiAgent organization** (employees or staff responsible for handling work). Each step explains what to do here; follow the links when you need more detail.

{% hint style="info" %}
If your users are **your customers, registered users, or anonymous visitors** rather than organization members, they cannot use the MaiGPT product itself. Instead, use [a custom AI Agent with MaiGPT window mode](/tech/en/work/maigpt-system-integration-guide/maigpt-integration.md#build-agent). For contact identity integration, see the [Software Vendor Integration Guide](/tech/en/serve/vendor-integration-guide.md).
{% endhint %}

## Overview <a href="#overview" id="overview"></a>

```mermaid
flowchart LR
    A["1 Provision members<br/>SCIM／Invitation／SSO"] --> B["2 Issue member tokens on the backend<br/>Organization API Key"]
    B --> C["3 Embed on the frontend<br/>auth.getToken"]
    C --> D["4 Sign-out and offboarding<br/>signOut／Deactivation"]
    D --> E["5 Acceptance testing"]
```

Once complete, employees log in to your system and see MaiGPT directly on the page. They can generate images, use Deep Research, and access connectors. Permissions, quotas, and conversation history follow their MaiAgent member identity. They do not need to log in to MaiAgent separately or even know that MaiAgent exists.

## Prerequisites <a href="#prerequisites" id="prerequisites"></a>

| Item                                                                                                                         | Where to get it                                                                                                                                                                                                                                                                                                                                                 |
| ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A MaiAgent organization with a plan that includes MaiGPT and identity synchronization                                        | Contact sales if you are unsure                                                                                                                                                                                                                                                                                                                                 |
| An organization API Key whose holder is the organization owner or has administrative permissions for “Organization Overview” | See [Quickstart](/tech/en/api-integration/quickstart.md) for instructions                                                                                                                                                                                                                                                                                       |
| The MaiGPT Web Chat ID                                                                                                       | The entry in the `GET /api/v1/web-chats/` response with the name `MaiGPT` and `accessType` set to `web`                                                                                                                                                                                                                                                         |
| Roles created and permissions configured in advance                                                                          | In the admin console, go to “Organization Settings → Organization Overview → Edit Role Permissions,” create a role such as “Employee,” and enable MaiGPT access ([configuration instructions](https://docs.maiagent.ai/org/roles/maigpt-role-permissions)). **All member capabilities come from roles**. Without this step, the rest of the setup will not work |
| Decide where members come from                                                                                               | Choose one of the three options in the next section                                                                                                                                                                                                                                                                                                             |

## Step 1: Provision Members <a href="#step-1" id="step-1"></a>

Your users must first be members of the MaiAgent organization. Choose whichever of these three methods is easiest:

{% hint style="info" %}
Does anyone in your organization already use MaiAgent? Connecting SCIM will neither invalidate their existing accounts nor create duplicates. Existing members taken over by SCIM will subsequently stay synchronized with your system. See [What Happens to Existing Accounts and Members](/tech/en/identity-and-access/member-provisioning.md#scim-existing-accounts) for details.
{% endhint %}

{% tabs %}
{% tab title="Your system has user management (recommended)" %}
Call MaiAgent's SCIM endpoints from your system's user creation, update, and deactivation events to keep members synchronized in real time.

1. In the admin console, select SCIM under “Organization Settings → Identity Synchronization,” then copy the Endpoint URL and Token from the “Connection Information” tab (the Token is displayed only once; store it in server environment variables)
2. Add the `MaiAgentMembers` client from the [Real-Time Synchronization page](/tech/en/identity-and-access/member-provisioning/member-event-sync.md) to your project and call it from your events:

```python
members = MaiAgentMembers()   # Read environment variables MAIAGENT_SCIM_URL / MAIAGENT_SCIM_TOKEN

# Create a user
user.maiagent_member_id = members.on_user_created(
    external_id=user.id, email=user.email, name=user.display_name, groups=["Employee"],
)
# Change name or department
members.on_user_updated(user.maiagent_member_id, user.id, user.email, user.display_name, ["Employee"])
# Suspend access or offboard
members.on_user_deactivated(user.maiagent_member_id)
```

3. On initial launch, run `on_user_created` once for all existing users (idempotent; see [Backfill](/tech/en/identity-and-access/member-provisioning/member-event-sync.md#backfill)), then maintain synchronization through events.
   {% endtab %}

{% tab title="You only have a roster (HR export, Excel, database)" %}
Use the [Roster Synchronization Tool](/tech/en/identity-and-access/member-provisioning/member-roster-sync.md): prepare a CSV or JSON file with four fields (personnel ID, Email, name, role), configure the SCIM connection environment variables, and review the plan with `--dry-run` before running it for real. Then schedule it to run daily. Users on the roster are created or updated; users removed from it are deactivated.
{% endtab %}

{% tab title="You have Okta／Entra ID／JumpCloud" %}
Enter the SCIM Endpoint URL and Token in your IdP's provisioning settings. The IdP will automatically push users and groups. See [Push from an IdP](/tech/en/identity-and-access/member-provisioning.md#scim-idp) for details.
{% endtab %}
{% endtabs %}

Remember these three points—the most common stumbling blocks in real integrations:

* **Match role names to the roles created in the admin console**: the names in `groups` when SCIM creates a member must match roles with permissions already configured in the admin console. An unmatched name automatically creates a new role with **no permissions**.
* **Email is the account key**: `userName` is the Email used later to issue tokens. After creation, Email cannot be changed through SCIM.
* **Accounts created through SCIM have no password**: employees using this approach do not log in to MaiAgent, which is exactly the intended behavior. To also allow access to the MaiGPT web interface or App, configure [SSO](/tech/en/identity-and-access/member-provisioning.md#sso) separately.

## Step 2: Issue Member Tokens on the Backend <a href="#step-2" id="step-2"></a>

Create a backend endpoint that only **logged-in users** can call (for example, `GET /maigpt-token`). Internally, use the organization API Key to request a short-lived token for that member from MaiAgent:

```bash
curl -X POST https://api.maiagent.ai/api/v1/members/embed-tokens/ \
  -H "Authorization: Api-Key <Your organization API Key>" \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@acme.com"}'
```

A successful request returns `201`:

```json
{
  "accessToken": "<Short-lived member JWT>",
  "organizationId": "8d2f...-...",
  "expiresAt": 1789906401000,
  "member": { "id": "c1a4...", "userId": "5e77...", "email": "alice@acme.com", "name": "Alice" }
}
```

Return the entire response to the frontend unchanged. Rules and status codes:

| Fact                                                    | Explanation                                                                                                                                                   |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Valid for 15 minutes; no refresh token is issued        | The frontend SDK handles renewal automatically (Step 3). Your backend only needs to issue a token whenever called—**always issue a new one; do not cache it** |
| The token works only with MaiGPT conversation endpoints | Calling any API under `/api/v1/` with it returns `401`, so a leaked token cannot access organization data                                                     |
| `401`／`403`                                             | Api-Key was not used, or the Key holder is neither the owner nor an organization administrator                                                                |
| `404`                                                   | This Email does not belong to an active member of this organization—Step 1 was not completed, or the member has been deactivated                              |
| Every token issuance creates an audit record            | Available in the organization's API request logs; the token in the response is not recorded                                                                   |

For parameters and more details, see [Member Token Issuance](/tech/en/work/maigpt-system-integration-guide/maigpt-integration.md#member-embed-issue).

## Step 3: Embed on the Frontend <a href="#step-3" id="step-3"></a>

Add the embed code to the page where you want MaiGPT and point `auth.getToken` to the endpoint from Step 2. The SDK handles everything else (fetching a token at initialization, automatically fetching another before expiration, and continuing the same conversation):

```html
<div id="maigpt-container" style="height: 720px;"></div>
<script>
  window.maiagentChatbotConfig = {
    webChatId: '<MaiGPT Web Chat ID>',
    baseUrl: 'https://chat.maiagent.ai/web-chats',
    enabledWindowModes: ['maigpt'],
    targetElement: '#maigpt-container',
    maigptTitle: 'Acme GPT',            // Optional: brand name in the upper-left corner
    locale: 'zh-TW',                    // Optional: interface language
    auth: {
      getToken: async () => {
        const res = await fetch('/maigpt-token', { credentials: 'include' })
        const { accessToken, organizationId, member } = await res.json()
        return { accessToken, organizationId, sourceId: member.userId }
      },
    },
  }
</script>
<script src="https://chat.maiagent.ai/js/embed.min.js" defer></script>
```

{% hint style="danger" %}
Set `sourceId` to `member.userId` from the response, not `member.id` or the user ID in your system. MaiGPT uses it to associate conversations with the member. An incorrect value results in anonymous conversations and prevents access to that member's history.
{% endhint %}

Set the container height yourself. For an SPA, load the SDK after the container mounts. The `baseUrl` and SDK URL are SaaS addresses; replace them with your domain for a private deployment. For layout and other parameters, see [Embedding MaiGPT Mode](/tech/en/serve/web-chat-sdk/web-chat-maigpt-mode.md).

## Step 4: Sign-Out and Offboarding <a href="#step-4" id="step-4"></a>

| Event                                                  | What you need to do                                                                         | Result                                                                                                                  |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| A user logs out of your system                         | Call `MaiAgent.auth.signOut()` on the frontend                                              | The iframe clears the identity and stops renewal; issued tokens remain valid for up to 15 more minutes                  |
| A user leaves the organization or has access suspended | Deactivate them through Step 1 (`on_user_deactivated`, roster removal, or IdP deactivation) | Subsequent token requests return `404`, and the embedded page loses access; conversation and quota records are retained |
| A user returns to work                                 | Reactivate them through Step 1                                                              | Roles and history are restored                                                                                          |

## Step 5: Acceptance Testing <a href="#step-5" id="step-5"></a>

Check these items in order. Each has a clear pass criterion:

1. **The member exists and has a role**: the person appears under “Member Management” in the admin console, assigned to the role whose permissions you configured.
2. **Token issuance succeeds**: the curl request in Step 2 returns `201`; using a nonexistent Email returns `404`.
3. **Conversations work**: open MaiGPT on the embedded page, send a message, and receive a reply. The conversation is visible when you log in to the MaiGPT web interface as that member (if SSO is available), or in the admin console's conversation records.
4. **Capabilities are correct**: ask it to generate an image. If the role enables connectors and Deep Research, their entry points appear.
5. **Renewal is seamless**: leave the page open for more than 15 minutes, then send a message. The same conversation continues without refreshing the page.
6. **Sign-out takes effect**: messages are rejected after `signOut()`; after deactivating the member, Step 2 returns `404`.

## After Launch <a href="#after-launch" id="after-launch"></a>

* **SCIM Token and API Key rotation**: the admin console reminds you when a SCIM Token is more than 180 days old. Regenerating it immediately invalidates the old token; remember to update the server environment variables.
* **Plan capacity**: member count affects built-in Agent seats and each member's Credits quota. See [Member Credits Quota Management](https://docs.maiagent.ai/others/credits/member-credit-quota).
* **Auditing**: every token issuance appears in the organization's API request logs. Each SCIM synchronization appears under “Identity Synchronization → Synchronization Logs” in the admin console.

## Troubleshooting <a href="#troubleshooting" id="troubleshooting"></a>

| Symptom                                                                                               | Cause                                                                                            | Resolution                                                                                                                |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| Token issuance returns `404`                                                                          | Email does not belong to an active member of this organization                                   | Return to Step 1 and confirm that the member exists, is not deactivated, and has the same Email (case-insensitive)        |
| Token issuance returns `403`                                                                          | The API Key holder is neither the owner nor someone with organization administrative permissions | Use a Key issued by an administrator                                                                                      |
| The chat window shows “Failed to create conversation (400): You do not have permission to use MaiGPT” | The member's role lacks MaiGPT access, or `auth` was not passed                                  | Enable MaiGPT in the admin console's role permissions; confirm that `getToken` returns `accessToken` and `organizationId` |
| Conversations are anonymous and history is unavailable                                                | Incorrect `sourceId`                                                                             | Use `member.userId`                                                                                                       |
| Sending messages fails after 15 minutes                                                               | `getToken` is not called or fails (check the browser console for `[MaiAgent]` errors)            | Confirm that the endpoint is available to logged-in users and returns the correct response format                         |
| The member is created but cannot use anything                                                         | No role is assigned, or the role has no permissions                                              | Configure role permissions in the admin console; assign the same role name through SCIM                                   |
| Changing Email has no effect                                                                          | SCIM does not allow Email changes                                                                | Change it in the admin console, or deactivate the old account and create one with the new Email                           |

For more SCIM error codes, see the [Roster Synchronization Tool Error Reference](/tech/en/identity-and-access/member-provisioning/member-roster-sync.md#errors).

## Further Reading <a href="#further-reading" id="further-reading"></a>

* [Member Provisioning: SCIM／Invitation／SSO](/tech/en/identity-and-access/member-provisioning.md) — Complete SCIM API reference and comparison of the three approaches
* [Real-Time Synchronization: Call from User Events](/tech/en/identity-and-access/member-provisioning/member-event-sync.md)／[Roster Synchronization Tool](/tech/en/identity-and-access/member-provisioning/member-roster-sync.md)
* [Integrating MaiGPT: Choose the Right Agent and Enable Its Capabilities](/tech/en/work/maigpt-system-integration-guide/maigpt-integration.md) — MaiGPT product vs. custom Agent, and complete parameters for embedding with member identity
* [Web Chat Embedding and SDK](/tech/en/serve/web-chat-sdk.md)／[Embedding MaiGPT Mode](/tech/en/serve/web-chat-sdk/web-chat-maigpt-mode.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/en/work/maigpt-system-integration-guide.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
