Here’s a guide to create agent sessions with programmatically provisioned Knowledge Contexts. And then embed a programmatic agent in your web application using those agent sessions.

Default agent system

With the default agents system, your Mindset App admin dashboard manages access permissions for knowledge contexts assigned on an agent basis.

Programmatic agent system

You may need to provision agents and knowledge contexts access based on the permission system set up in your platform.

We’ve introduced the concept of an agent session: Agent sessions are programmatically provisioned on-demand for specified agents and knowledge contexts.

Once an agent session is created, providing the agentSessionUid to the <mindset-agent> HTML tag will allow you to embed the agent with the specified access permissions.

Tutorial : Embed a programmatic agent

In this Tutorial you will learn how to embed your programmatic agent in a web application.

Required parameters

You will need to get few parameters before starting.

YOUR-APP-UID is provided by the Mindset support team. All others parameters can be found in the Mindset Management Portal.

ParameterDescription
YOUR-APP-UIDYour appUid is provided by mindset.
YOUR-MINDSET-API-KEYYour Mindset API key. It is used to authenticate your API calls.
AGENT-UIDThe agent Uid you want the user chat with. You can find that Agent Uid in the setting of the agent in the Agent Management Portal.
KNOWLEDGECONTEXT-1-UIDOne Knowledge context Uid you want to provision the agent with
KNOWLEDGECONTEXT-2-UIDAnother one Knowledge context Uid you want to provision the agent with
MINDSET-API-HOSTThe Mindset API host. Used to call the Mindset API.

Step 1: Create an agent session

To create an Agent Session (and hence create an agentSessionUid required by the SDK), you will need to call the Mindset agentSessions API. (See the Agent Sessions API documentation for more details).

We can imagine you would have to manage many agents, many knowledge contexts and many users in your platform.

According to your permissions and roles system, users would have specific rights to access specific agents and specific Knowledge contexts

For example:

  • A User1 has the permission to use the agent1 provisioned with the Knowledge Context 1 and knowledge context 2.
  • But a User2 has the permission to use the agent1 provisioned with the Knowledge Context 1

Based on your permissions rules you will then create agent sessions.

What we would like to achieve is :

  • to provision the agent (agentUid v8srU0hv88BeWBDcirSm)
  • with the 2 knowledge contexts (contextUids [qZJGsjytbM5fL15sfBui, 3am8rolEPXx3j0n132Bf])
  • and for a user with an externalUserId (user-x123456).

We would need to provide the following parameters in the request body:

const requestBody = {
  {
    agentUid: "v8srU0hv88BeWBDcirSm",
    externalUserId: "user-x123456",
    contextUids: ["qZJGsjytbM5fL15sfBui", "3am8rolEPXx3j0n132Bf"]
 }
};

Below an example of a HTTP POST request to create that agent session.

// Example Node.js code to make a server-side HTTP POST request for creating an agent session
// Adapt this example based on your server-side programming environment

const fetch = require('node-fetch');

const YOUR-MINDSET-API-KEY = 'YOUR-MINDSET-API-KEY' 
const MINDSET-API-HOST = 'MINDSET-API-HOST'
const YOUR-APP-UID = 'YOUR-APP-UID'

const requestBody = {
  {
    agentUid: "v8srU0hv88BeWBDcirSm",
    externalUserId: "user-x123456",
    contextUids: ["qZJGsjytbM5fL15sfBui", "3am8rolEPXx3j0n132Bf"]
 }
};

fetch('https://${MINDSET-API-HOST}/api/v1/appuid/${YOUR-APP-UID}/agentsessions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': YOUR-MINDSET-API-KEY
  },
  body: JSON.stringify(requestBody)
})
.then(response => response.json())

.catch((error) => {
  console.error('Error:', error);
});

The API response object will be:

{
  "uid": "uFKbuW0ipk2Za4QuQ6rx",
  "createdAt": "2025-06-10T16:26:21.635Z",
  "agentSessionUid": "v8srU0hv88BeWBDcirSm::uFKbuW0ipk2Za4QuQ6rx",
  "humanUid": "j8no2tZ26IcWQgJ9oNJbHjOf7hE3",
  "agentUid": "v8srU0hv88BeWBDcirSm",
  "externalUserId": "user-x123456",
  "lastUsedAt": "2025-06-10T16:26:21.634Z",
  "tags": [],
  "contextUids": [
    "qZJGsjytbM5fL15sfBui",
    "3am8rolEPXx3j0n132Bf"
  ],
  "userEmail": ""
}

The most important information that will be reused in the next step is the :

agentSessionUid (v8srU0hv88BeWBDcirSm::uFKbuW0ipk2Za4QuQ6rx).

Step 2: Embed the agent in your web application

You embed this agent using the same method you used to embed the default agent. You will use the <mindset-agent> HTML tag in your Front-end page:

 <mindset-agent 
    agentUid='AGENT-SESSION-UID'
    style='width: 100%; height: 600px; display: block; background-color: rgb(255, 255, 255);">
</mindset-agent>

But instead of providing the agentUid you will provide the agentSessionUid you just created in the previous step.

The final HTML tag will look like this:

 <mindset-agent 
    agentUid='v8srU0hv88BeWBDcirSm::uFKbuW0ipk2Za4QuQ6rx'
    style='width: 100%; height: 600px; display: block; background-color: rgb(255, 255, 255);">
</mindset-agent>

Lifetime of Agent Session Access

Agent Sessions are intended to be generated on demand each time you create a web page that contains an embedded agent.

They become inactive after 31 days of non-use. They can also be deactivated immediately using the API.

We expect that you will create multiple agent sessions for the same user with identical agent and context details.

Please refer to the Agent Sessions API documentation for more details on how to manage agent sessions.

Reporting

Here’s how to set up reporting for agents.

When creating an agent session through the API, you can provide tags to the parmaters:

{
    agentUid: "v8srU0hv88BeWBDcirSm",
    externalUserId: "user-x123456",
    contextUids: ["qZJGsjytbM5fL15sfBui", "3am8rolEPXx3j0n132Bf"],
    tags: ["tag1", "tag2"],
 }

When initiating an agent session, the tags you specify are essential for understanding the interaction between agents, contexts, and users.

Adding tags enables you to view reports based on groups or filter activity according to the tags you’ve applied.

Please refer to the Agent Sessions API documentation for more information on adding tags.

Back-end and Front-end scripts full example

Back-end script

Sample back-end script (using express). It shows 2 end-points you can implement:

  1. /api/getusertoken which authenticate the user with Mindset system and returns an authToken
  2. /api/getagentsessionuid which create an agent session and returns the agentSessionUid
import express from "express";
import axios from "axios";


const YOUR-MINDSET-API-KEY = 'YOUR-MINDSET-API-KEY' ;
const MINDSET-API-HOST = 'MINDSET-API-HOST';
const YOUR-APP-UID = 'YOUR-APP-UID';

const EXTERNAL-USER-ID = 'userx123456';
const AGENT-UID = 'AGENT-UID';
const KNOWLEDGE-CONTEXT-UID = 'ONE-KNOWLEDGE-CONTEXT-UID'



const app = express();

app.get("/api/getusertoken", async (req, res) => {
  try {
    const embedUserToken: any = await axios.post(
      `https://${MINDSET-API-HOST}/api/v1/appuid/${YOUR_APP_UID}/sdkusers/auth`,
      {
        externalId: EXTERNAL-USER-ID,
      },
      {
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': YOUR-MINDSET-API-KEY
        },
      }
    )
    res.send(embedUserToken.data);
  
  } catch (error: any) {
    console.error(error);
    console.error("Error", error, error.response.status, error.response, error);
    res.status(500).send("Error getting token");
  };
});



app.get("/api/getagentsessionuid", async (req, res) => {
  
  try {
    const agentSessionCreationResponse: any = await axios.post(
      `https://${MINDSET-API-HOST}/api/v1/appuid/${YOUR-APP-UID}/agentsessions`,
      {
        agentUid: AGENT-UID,
        externalUserId: EXTERNAL-USER-ID,
        contextUids: [KNOWLEDGE-CONTEXT-UID]
      },
      {
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': YOUR-MINDSET-API-KEY
        },
      }
    )
    
    res.send(agentSessionCreationResponse.data);
  } catch (error: any) {
    console.error(error);
    console.error("Error", error, error.response.status, error.response, error);
    res.status(500).send("Error getting token");
  };
});


export default app;

Front-end script

A sample front-end script which:

  1. Provide a getAuthToken() method using your /api/getusertoken end-point.
  2. Provide a getAgentSessionUid() method using your /api/getagentsessionuid end-point.
  3. Build the <mindset-agent> html tag by passing the agentSessionUid returned.
  4. call mindset.init()
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="MINDSET-SERVER-URL/mindset-sdk2.js"></script>
  
  <body>

    <script>
        const userAgentSessionServerUrl = `https://YOUR-BACK-END-HOST/api/getagentsessionuid/`

        async function createAgentSession() {
            try {
                const response = await fetch(userAgentSessionServerUrl);
                const textData = await response.json();
                return textData.agentSessionUid;
            } catch (error) {
                console.log('Error fetching auth token:', error);
                throw error;
            }
        }

        const userAuthokenServerUrl = `https://YOUR-BACK-END-HOST/api/getusertoken/`

        async function getAuthToken() {
            try {
                const response = await fetch(userAuthokenServerUrl);
                const textData = await response.json();
                return textData.authToken;
            } catch (error) {
                console.log('Error fetching auth token:', error);
                throw error;
            }
        }


        (async function addMindsetAgent(){
            const agentSessionUid = await createAgentSession()
     
            const embededAgentPlaceholder = document.getElementById("embeded-agent-placeholder");

            const agenttag = '<mindset-agent id="agent" agentUid="' + agentSessionUid + '" style="width: 100%; height: 600px; display: block;"></mindset-agent>'
            embededAgentPlaceholder.innerHTML = agenttag;

            mindset.init({
                fetchAuthentication: getAuthToken, 
                appUid: "YOUR-APP-UID"
                
            });

        })();
    </script>

    <div id="embeded-agent-placeholder" style="width: 800px; height: 800px;"></div>

  </body>
</html>