# Agent Builder SDK Use Case Flows

> You're reading the Mindset v3 documentation. v3 is no longer sold; this is reference for existing customers. Mindset 4 docs are at /docs.

Comprehensive guide for integrating agent and context management into your platform

This document describes key workflows when using the Agent Builder SDK to enable tenant administrators to create and manage AI agents and knowledge contexts within your platform.

## Available Components Overview

The Agent Builder SDK provides four main components for agent and context management:

- **Agent Builder**: `<mindset-agents-manager>`

  Display all agents with create/edit/delete capabilities
- **Agent Configuration**: `<mindset-agent-configuration>`

  Standalone agent creation/editing interface
- **Context Builder**: `<mindset-contexts-manager>`

  Display all knowledge contexts with create/edit/delete capabilities
- **Context Configuration**: `<mindset-context-configuration>`

  Standalone context creation/editing interface

## Component Comparison Matrix

#### Builder Components

**Components:**

- `<mindset-agents-manager>`
- `<mindset-contexts-manager>`

**Features:**

- ✅ Complete CRUD interface
- ✅ List view included
- ✅ Built-in create/edit dialogs
- ✅ Delete functionality
- ✅ Search and filtering
- **Min Height:** 600px

**Best For:** Standard admin interfaces with full management capabilities

#### Configuration Components

**Components:**

- `<mindset-agent-configuration>`
- `<mindset-context-configuration>`

**Features:**

- ✅ Standalone create/edit interface
- ❌ No list view
- ❌ No delete functionality
- ❌ No search/filter
- **Min Height:** 400px

**Best For:** Managing one specific agent/context or building custom list views

## Use Case 1: Agent Management with Agent Builder

This flow shows how to embed a complete agent management interface where tenant administrators can view, create, edit, and delete agents in one unified interface.

### Prerequisites

- **externalTenantId**: The unique identifier for the tenant organization
- **externalId**: The unique identifier for the admin user within your system
- **appUid**: Your application's unique identifier provided by Mindset

### Step-by-Step Flow

### 1. Authenticate the Tenant Admin

Call the SDKUsers Auth API to create an auth token for the tenant admin user:

```bash
    POST https://{environment}.api.mindset.ai/api/v1/appuid/{appUid}/sdkusers/auth
    Content-Type: application/json
    x-api-key: {your-api-key}
    
    {
      "externalId": "admin-user-123",
      "externalTenantId": "tenant-abc-456"
    }
```

**Response:**

```json
    {
      "authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
    }
```

> **Info:** This call:
>
> - Creates or updates the user in Mindset's system
> - Registers them as an admin of the specified externalTenantId
> - Returns an auth token scoped to that tenant

### 2. Construct the Web Page with Agent Builder

Create an HTML page containing the Agent Builder component:

```html
    <!DOCTYPE html>
    <html>
    <head>
        <title>Agent Management</title>
        <style>
            mindset-agents-manager {
                display: block;
                width: 100%;
                min-height: 600px;
            }
        </style>
    </head>
    <body>
        <h1>Manage AI Agents</h1>
    
        <!-- Agent Builder component - complete CRUD interface -->
        <mindset-agents-manager></mindset-agents-manager>
    
        <!-- Load Agent Builder SDK JavaScript -->
        <script src="https://[AMS-SDK-URL]/mindset-sdk2.js"></script>
    
        <!-- Initialize SDK -->
        <script>
            (async () => {
                await window.mindset.init({
                    appUid: 'your-app-uid',
                    externalTenantId: 'tenant-abc-456',
                    fetchAuthentication: async () => {
                        // Call your backend to get auth token
                        const response = await fetch('/api/mindset/auth', {
                            credentials: 'include'
                        });
                        const data = await response.json();
                        return data.authToken;
                    }
                });
            })();
        </script>
    </body>
    </html>
```

> **Check:** **Key Benefits:**
>
> - Zero configuration - complete agent management in one component
> - Built-in list view with search and filtering
> - Automatic create/edit dialogs
> - Delete confirmation handling

### 3. Optional - Control Displayed Tabs

You can control which configuration tabs are shown in the agent dialogs:

```html
    <!-- Show only specific tabs in agent configuration -->
    <mindset-agents-manager displayTabs="Policy,LLM,Contexts"></mindset-agents-manager>
```

**Available tabs:** Policy, Options, LLM, Contexts, Bias, Preview

> **Note:** Settings and Personality tabs are always displayed.

## Use Case 2: Standalone Agent Creation/Editing

This flow shows how to embed a standalone agent creation or editing interface.

### Prerequisites

- **Authentication**: Same as Use Case 1
- **agentUid (optional)**: UID of existing agent to edit

### Step-by-Step Flow

### 1. Authenticate

Follow the authentication steps from Use Case 1.

### 2. Construct the Web Page with Agent Configuration

#### Creating a New Agent

```html
        <!DOCTYPE html>
        <html>
        <head>
            <title>Create New Agent</title>
            <style>
                mindset-agent-configuration {
                    display: block;
                    width: 100%;
                    min-height: 400px;
                }
            </style>
        </head>
        <body>
            <h1>Create New Agent</h1>
        
            <!-- Agent Configuration component - no agentUid = create mode -->
            <mindset-agent-configuration
                displayTabs="Policy"
                onClose="handleAgentSaved();">
            </mindset-agent-configuration>
        
            <script src="https://[AMS-SDK-URL]/mindset-sdk2.js"></script>
            <script>
                (async () => {
                    await window.mindset.init({
                        appUid: 'your-app-uid',
                        externalTenantId: 'tenant-abc-456',
                        fetchAuthentication: async () => {
                            const response = await fetch('/api/mindset/auth', {
                                credentials: 'include'
                            });
                            const data = await response.json();
                            return data.authToken;
                        }
                    });
                })();
        
                function handleAgentSaved() {
                    // User closed the dialog
                    window.location.href = '/admin/agents';
                }
            </script>
        </body>
        </html>
```

#### Editing an Existing Agent

```html
        <!-- Agent Configuration component - with agentUid = edit mode -->
        <mindset-agent-configuration
            agentUid="agent-abc-123"
            displayTabs="Policy"
            onClose="handleAgentSaved();">
        </mindset-agent-configuration>
```

> **Tip:** **Key Points:**
>
> - Omit `agentUid` attribute to create a new agent
> - Include `agentUid` attribute to edit an existing agent
> - The `onClose` callback fires when the user closes the config dialog
> - The SDK automatically saves the agent with the `externalTenantId` tag

### 3. Configuration Component Integration Pattern

For dynamic Configuration Component, create fresh elements each time:

```html
    <div id="agent-modal" style="display: none;">
        <div class="modal-content">
            <button onclick="closeModal()">Close</button>
            <div id="agent-config-container"></div>
        </div>
    </div>
    
    <script>
        function createAgent() {
            const container = document.getElementById('agent-config-container');
            container.innerHTML = '<mindset-agent-configuration displayTabs="Policy" onClose="closeModal();"></mindset-agent-configuration>';
            document.getElementById('agent-modal').style.display = 'block';
        }
    
        function editAgent(agentUid) {
            const container = document.getElementById('agent-config-container');
            container.innerHTML = `<mindset-agent-configuration agentUid="${agentUid}" displayTabs="Policy" onClose="closeModal();"></mindset-agent-configuration>`;
            document.getElementById('agent-modal').style.display = 'block';
        }
    
        function closeModal() {
            document.getElementById('agent-modal').style.display = 'none';
            document.getElementById('agent-config-container').innerHTML = '';
        }
    </script>
```

## Use Case 3: Knowledge Context Management with Context Builder

This flow shows how to embed a complete knowledge context management interface where tenant administrators can view, create, edit, and delete contexts.

> **Info:** **What are Knowledge Contexts?**
>
> Knowledge Contexts are bundles of files, links, and data that agents can reference—essentially a dynamic library for your agents.

### Prerequisites

Same as Use Case 1 (authentication and tenant setup)

### Step-by-Step Flow

### 1. Authenticate

Follow the authentication steps from Use Case 1.

### 2. Construct the Web Page with Context Builder

Create an HTML page containing the Context Builder component:

```html
    <!DOCTYPE html>
    <html>
    <head>
        <title>Knowledge Context Management</title>
        <style>
            mindset-contexts-manager {
                display: block;
                width: 100%;
                min-height: 600px;
            }
        </style>
    </head>
    <body>
        <h1>Manage Knowledge Contexts</h1>
    
        <!-- Context Builder component - complete CRUD interface -->
        <mindset-contexts-manager></mindset-contexts-manager>
    
        <!-- Load Agent Builder SDK JavaScript -->
        <script src="https://[AMS-SDK-URL]/mindset-sdk2.js"></script>
    
        <!-- Initialize SDK -->
        <script>
            (async () => {
                await window.mindset.init({
                    appUid: 'your-app-uid',
                    externalTenantId: 'tenant-abc-456',
                    fetchAuthentication: async () => {
                        const response = await fetch('/api/mindset/auth', {
                            credentials: 'include'
                        });
                        const data = await response.json();
                        return data.authToken;
                    }
                });
            })();
        </script>
    </body>
    </html>
```

> **Check:** **Key Benefits:**
>
> - Complete context management in one component
> - Built-in list view with search capabilities
> - Automatic create/edit dialogs
> - Delete confirmation handling

### 3. Optional - Control Displayed Tabs

You can control which configuration tabs are shown in the context dialogs:

```html
    <!-- Show only specific tabs in context configuration -->
    <mindset-contexts-manager displayTabs="Prompts"></mindset-contexts-manager>
```

**Available tabs:** Prompts, Bias

> **Note:** General tab is always displayed.

## Use Case 4: Standalone Context Creation/Editing

This flow shows how to embed a standalone context creation or editing interface.

### Prerequisites

- **Authentication**: Same as Use Case 1
- **contextUid (optional)**: UID of existing context to edit

### Step-by-Step Flow

### 1. Authenticate

Follow the authentication steps from Use Case 1.

### 2. Construct the Web Page with Context Configuration

#### Creating a New Context

```html
        <!DOCTYPE html>
        <html>
        <head>
            <title>Create New Knowledge Context</title>
            <style>
                mindset-context-configuration {
                    display: block;
                    width: 100%;
                    min-height: 400px;
                }
            </style>
        </head>
        <body>
            <h1>Create New Knowledge Context</h1>
        
            <!-- Context Configuration component - no contextUid = create mode -->
            <mindset-context-configuration
                displayTabs="Prompts,Bias"
                onClose="handleContextSaved();">
            </mindset-context-configuration>
        
            <script src="https://[AMS-SDK-URL]/mindset-sdk2.js"></script>
            <script>
                (async () => {
                    await window.mindset.init({
                        appUid: 'your-app-uid',
                        externalTenantId: 'tenant-abc-456',
                        fetchAuthentication: async () => {
                            const response = await fetch('/api/mindset/auth', {
                                credentials: 'include'
                            });
                            const data = await response.json();
                            return data.authToken;
                        }
                    });
                })();
        
                function handleContextSaved() {
                    // User closed the dialog
                    window.location.href = '/admin/contexts';
                }
            </script>
        </body>
        </html>
```

#### Editing an Existing Context

```html
        <!-- Context Configuration component - with contextUid = edit mode -->
        <mindset-context-configuration
            contextUid="context-xyz-789"
            displayTabs="Prompts,Bias"
            onClose="handleContextSaved();">
        </mindset-context-configuration>
```

> **Tip:** **Key Points:**
>
> - Omit `contextUid` attribute to create a new context
> - Include `contextUid` attribute to edit an existing context
> - The `onClose` callback fires when the user closes the configuration component
> - The SDK automatically saves the context with the `externalTenantId` tag

### 3. Configuration Component Integration Pattern

For dynamic configuration component, create fresh elements each time:

```html
    <div id="context-modal" style="display: none;">
        <div class="modal-content">
            <button onclick="closeContextModal()">Close</button>
            <div id="context-config-container"></div>
        </div>
    </div>
    
    <script>
        function createContext() {
            const container = document.getElementById('context-config-container');
            container.innerHTML = '<mindset-context-configuration displayTabs="Prompts,Bias" onClose="closeContextModal();"></mindset-context-configuration>';
            document.getElementById('context-modal').style.display = 'block';
        }
    
        function editContext(contextUid) {
            const container = document.getElementById('context-config-container');
            container.innerHTML = `<mindset-context-configuration contextUid="${contextUid}" displayTabs="Prompts,Bias" onClose="closeContextModal();"></mindset-context-configuration>`;
            document.getElementById('context-modal').style.display = 'block';
        }
    
        function closeContextModal() {
            document.getElementById('context-modal').style.display = 'none';
            document.getElementById('context-config-container').innerHTML = '';
        }
    </script>
```

## Understanding fetchAuthentication

The `fetchAuthentication` parameter is a function that returns a Promise resolving to an auth token. This enables a deferred authentication pattern:

### 1. Page Loads

Your page loads and displays the Agent Builder SDK UI immediately

### 2. SDK Requests Auth

The SDK calls `fetchAuthentication()` only when it actually needs authentication

### 3. Client Calls Backend

Your client-side code makes a request to your backend API

### 4. Backend Generates Token

Your backend calls the Mindset SDKUsers Auth API to generate the token

### 5. Token Returned

Your backend returns the token to your frontend

### 6. SDK Authenticated

The SDK uses the token for authenticated operations

### Example Implementation

#### Client-side Code

```javascript
    await window.mindset.init({
        appUid: 'your-app-uid',
        externalTenantId: 'tenant-abc-456',
        fetchAuthentication: async () => {
            // Call YOUR backend API
            const response = await fetch('/api/mindset/auth', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include' // Send session cookies
            });
            const data = await response.json();
            return data.authToken;
        }
    });
```

#### Backend API (Node.js/Express)

```javascript
    app.post('/api/mindset/auth', async (req, res) => {
        // Get current user from your session
        const user = req.session.user;
    
        // Call Mindset SDKUsers Auth API
        const response = await fetch(
            `https://b.api.mindset.ai/api/v1/appuid/${MINDSET_APP_UID}/sdkusers/auth`,
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': MINDSET_API_KEY
                },
                body: JSON.stringify({
                    externalId: user.id,
                    externalTenantId: user.tenantId
                })
            }
        );
    
        const data = await response.json();
        res.json({ authToken: data.authToken });
    });
```

> **Check:** **Benefits of this approach:**
>
> - **API key security:** Your Mindset API key never leaves your backend
> - **Faster UI rendering:** The page displays immediately without waiting for authentication
> - **Session validation:** Your backend can verify the user's session before generating tokens
> - **Token refresh:** The SDK will call `fetchAuthentication()` again if tokens expire

## Component Attributes Reference

### Agent Builder

| Attribute   | Type              | Description                                                                                       |
| ----------- | ----------------- | ------------------------------------------------------------------------------------------------- |
| displayTabs | string (optional) | Comma-separated list of tabs to display. Available: Policy, Options, LLM, Contexts, Bias, Preview |

### Agent Configuration

| Attribute   | Type              | Description                                                                                       |
| ----------- | ----------------- | ------------------------------------------------------------------------------------------------- |
| agentUid    | string (optional) | UID of agent to edit. Omit for create mode.                                                       |
| onClose     | string (optional) | JavaScript code to execute when configuration component is closed                                 |
| displayTabs | string (optional) | Comma-separated list of tabs to display. Available: Policy, Options, LLM, Contexts, Bias, Preview |

### Context Builder

| Attribute   | Type              | Description                                                       |
| ----------- | ----------------- | ----------------------------------------------------------------- |
| displayTabs | string (optional) | Comma-separated list of tabs to display. Available: Prompts, Bias |

### Context Configuration

| Attribute   | Type              | Description                                                       |
| ----------- | ----------------- | ----------------------------------------------------------------- |
| contextUid  | string (optional) | UID of context to edit. Omit for create mode.                     |
| onClose     | string (optional) | JavaScript code to execute when configuration component is closed |
| displayTabs | string (optional) | Comma-separated list of tabs to display. Available: Prompts, Bias |

## Security Best Practices

#### Tenant Admin Authentication

- The `externalTenantId` in the auth call registers the user as an admin for that tenant
- Backend validates that the user is authorized before allowing any create/edit operations
- Tenant admins can only see and manage resources tagged with their `externalTenantId`

#### Auth Token Security

- Auth tokens should be generated server-side, not exposed in client code
- Implement the `fetchAuthentication` callback to request tokens from your backend
- Tokens have expiration times and will be refreshed automatically by the SDK
- Never hardcode API keys in client-side code

#### Dynamic Element Creation

**Important:** When using configuration components in modals or overlays, always create a fresh element each time:

✅ **CORRECT:**

```javascript
    const container = document.getElementById('config-container');
    container.innerHTML = `<mindset-agent-configuration agentUid="${uid}"></mindset-agent-configuration>`;
```

❌ **INCORRECT:**

```javascript
    const element = document.getElementById('agent-config');
    element.setAttribute('agentUid', uid); // May not trigger re-initialization
```

## Receiving Notifications (Optional)

When users save agents or contexts, you have two options to get the resource details:

#### Option A: Webhook Notification

If you've registered a webhook for events, you'll receive a notification within 5 seconds:

```json
    {
      "event": "agent.created",
      "timestamp": "2025-10-06T14:30:00Z",
      "data": {
        "uid": "agent-new-123",
        "name": "Customer Support Agent",
        "externalTenantId": "tenant-abc-456",
        "createdBy": "admin-user-123"
      }
    }
```

#### Option B: Query the API

**For Agents:**

```bash
    GET https://{environment}.api.mindset.ai/api/v1/appuid/{appUid}/agents?externalTenantId=tenant-abc-456
    x-api-key: {your-api-key}
```

**For Contexts:**

```bash
    GET https://{environment}.api.mindset.ai/api/v1/appuid/{appUid}/contexts?externalTenantId=tenant-abc-456
    x-api-key: {your-api-key}
```

## Next Steps

- [Complete Integration Guide](https://docs4.mindset.ai/v3/deploy/ams-sdk/ams-sdk-integration-guide): See the full Agent Builder SDK documentation for detailed customization options
- [Webhook Setup](https://docs4.mindset.ai/v3/deploy/webhooks/webhooks): Configure webhooks to receive real-time notifications for agent and context events
- [API Reference](https://docs4.mindset.ai/v3/deploy/api/introduction): Explore the complete API documentation for Agents, Contexts, and SDKUsers APIs
- [Theme Customization](https://docs4.mindset.ai/v3/deploy/sdk2/agent-color-theme): Learn how to customize the SDK appearance to match your platform's branding
