# Mica AI Workflows API

## Overview

Mica AI Assistant Workflows enable the creation of interactive, extensible workflows that function as interactive dialogues within the Monterosa Studio UI. This framework allows developers to build sophisticated user interfaces with minimal complexity whilst maintaining full control over the user experience.

### **Core Features**

The framework provides essential building blocks including:

* Various input types (text, numbers, images, colour pickers)
* Rich visual components (text blocks, images, progress loaders)
* Interactive button actions for user engagement

### **Architecture**

A Workflow is implemented as a backend web service that communicates with the Studio environment through HTTP POST requests. The service responds with JSON payloads that dynamically define the user interface and control the workflow's progression.

## Technical Architecture

### **Core Concepts**

* **Workflow Endpoint**: An HTTP endpoint containing the business logic that processes incoming data and generates the appropriate UI for each step
* **Stateless Communication**: Uses a `payload` field to maintain state across stateless requests
* **Request/Response Protocol**: Every request contains workflow context, user inputs, actions, and stateful payload data
* **Asynchronous Operations**: Supports long-running tasks through a polling mechanism for operations like image processing or data analysis

### **Workflow Registration**

After development, provide the workflow name and endpoint URL to the Monterosa team for platform configuration. This defines the workflow's availability across different scopes (Organisation, Space, Project, or Event).

## Authentication and Authorisation

**Critical Security Requirement**: Every request to a Workflow backend must be verified and authorised to prevent unauthorised access or data manipulation.

### **Security Strategy**

Workflow backends must verify that:

* Requests come from authenticated Studio users
* Users have appropriate access to requested resources (Organisation, Space, Project, etc.)
* Verification occurs before executing any actions or accessing resources

### **Authentication Header**

HTTP requests include an authorisation header:

```
Authorization: Bearer <TOKEN>
```

The token can be used to access Control API endpoints on behalf of the executing user.

### **Control API Endpoints**

#### **GET /api/v2/me**

Returns authenticated user information. A successful 200 status confirms user authentication.

**Response Format:**

```json
{
  "data": {
    "id": "4cafd83a-a401-4bed-895b-614906e051bc",
    "type": "users",
    "attributes": {
      "name": "John Johnson",
      "email": "email@example.me",
      "system_role": "creator"
    }
  }
}
```

#### **Role Verification Endpoints**

Check user roles within specific scopes:

* `GET /api/v2/organisations/{OrganisationID}/my_role`
* `GET /api/v2/spaces/{SpaceID}/my_role`
* `GET /api/v2/projects/{ProjectID}/my_role`

**Response Format:**

```json
{
  "data": {
    "type": "scope_roles",
    "attributes": {
      "role": "creator"
    }
  }
}
```

**Available Roles:** `none`, `viewer`, `creator`, `admin`

## Protocol Reference

### **Request Structure**

Workflow execution consists of HTTP POST requests with the following structure:

```typescript
type WorkflowRequest = {
  context: WorkflowContext;
  action?: string;
  taskId?: string;
  inputs?: WorkflowInputs;
  payload?: WorkflowPayload;
};
```

#### **Context Object**

Provides execution context and Studio URL:

```typescript
type WorkflowContext = {
  baseURL?: string;
  organisationId?: string;
  spaceId?: string;
  projectId?: string;
  eventId?: string;
};
```

Properties are hierarchically filled based on workflow execution scope.

### **Response Structure**

Successful responses follow this format:

```typescript
type WorkflowResponse = {
  blocks: Block[];
  actions?: Action[];
  autoAction?: AutoAction;
  payload?: WorkflowPayload;
  task?: Task;
};
```

## UI Components (Blocks)

Blocks are the fundamental UI building components, displayed in response order.

### **Text Block**

Display static text with optional formatting:

```typescript
type TextBlock = {
  type: "text";
  text: string;
  label?: string;
};
```

**Supported Formatting:**

* `<strong>...</strong>` - Bold text with emphasis
* `<em>...</em>` - Italicised text
* `<br>` - Line breaks

### **Image Block**

Display images with optional labels:

```typescript
type ImageBlock = {
  type: "image";
  url: string;
  label?: string;
  alt_text?: string;
};
```

### **Loader Block**

Show progress indicators:

```typescript
type LoaderBlock = {
  type: "loader";
  text?: string;
};
```

### **Colour Block**

Display colour values with preview:

```typescript
type ColourBlock = {
  type: "colour";
  value: string;
  label?: string;
};
```

### **Alert Block**

Show contextual messages:

```typescript
type AlertBlock = {
  type: "alert";
  text: string;
  title?: string;
  severity?: "success" | "info" | "warning" | "error";
};
```

### **Input Block**

Create interactive input components:

```typescript
type InputBlock = {
  type: "input";
  input_type: "text" | "file" | "image" | "colour";
  label: string;
  name: string;
};
```

Input values are included in subsequent requests using the `name` as the key. File and image inputs are serialised as Base64 strings.

## State Management

### **Payload**

Use the `payload` field as key-value storage for workflow duration:

```typescript
type WorkflowPayload = Record<string, unknown>;
```

Data returned in the payload is automatically included in the next request.

## User Interactions

### **Actions**

Create interactive buttons:

```typescript
type Action = {
  type: "button";
  label: string;
  action_id: string;
};
```

When triggered, the `action_id` is sent in the next request.

### **Auto Actions**

Trigger automatic actions without user interaction:

```typescript
type AutoAction = {
  action_id: string;
};
```

Useful for implementing automatic workflows or initial processing steps.

## Asynchronous Operations

### **Task Management**

For long-running operations, use the task system:

```typescript
type Task = {
  id: string;
  state: "running" | "completed" | "failed";
  progress?: number; // 0-100
  pollIntervalMs?: number;
  error?: string;
};
```

### **Task Lifecycle**

1. **Initiate Task**: Return a task object with "running" state
2. **Polling**: Frontend polls using task ID
3. **Progress Updates**: Return updated progress and state
4. **Completion**: Remove task from response or mark as "completed"/"failed"

**Example Running Task Response:**

```json
{
  "blocks": [
    {
      "type": "loader",
      "text": "Processing images...",
      "progress": 45
    }
  ],
  "task": {
    "id": "task_123",
    "state": "running",
    "progress": 45,
    "pollIntervalMs": 2000
  }
}
```

## Quality Assurance

### **Review Requirements**

All workflows require Studio team review before production deployment.

#### **Security Checklist**

* ✅ **Authentication Implementation**: Properly implemented and cannot be bypassed
* ✅ **Access Verification**: User access and role verification in place
* ✅ **Data Protection**: No exposure of data from different organisations

## Implementation Examples

### **"Spot the Ball" Workflow**

This example demonstrates a complete workflow for creating interactive image-based experiences:

#### **Initial Request**

```json
{
  "context": {
    "baseURL": "https://studio.monterosa.cloud",
    "organisationId": "9b39fa10-c34a-4f26-9579-ba6117adb504",
    "projectId": "13a48d49-a5f8-4047-b9f7-ece48153d661",
    "eventId": "3f9f39c4-b2dd-497c-8ea6-58d41c9e2a2d"
  }
}
```

#### **Input Collection Response**

```json
{
  "blocks": [
    {
      "type": "input",
      "input_type": "image",
      "label": "Upload image",
      "name": "upload_image"
    },
    {
      "type": "input",
      "input_type": "text",
      "label": "Number of answer options",
      "name": "options_count"
    },
    {
      "type": "input",
      "input_type": "colour",
      "label": "Label colour",
      "name": "label_colour"
    }
  ],
  "actions": [
    {
      "type": "button",
      "label": "Generate",
      "action_id": "generate_images"
    }
  ]
}
```

#### **Results Display**

After processing, the workflow displays generated content for user verification before final creation.

### **"Summarise Event" Workflow**

Demonstrates auto-action implementation:

#### **Auto-Action Response**

```json
{
  "blocks": [],
  "actions": [],
  "autoAction": {
    "action_id": "summarise_event"
  }
}
```

This immediately triggers the summarisation process without user interaction.

## Best Practices

### **Security**

* Always implement proper authentication and authorisation
* Verify user permissions before data access
* Validate all input data
* Use secure endpoints for sensitive operations

### **User Experience**

* Provide clear loading states for long operations
* Use appropriate input types for different data
* Implement error handling with helpful messages
* Maintain consistent visual styling

### **Performance**

* Use tasks for operations taking longer than a few seconds
* Implement appropriate polling intervals
* Minimise payload size for better performance
* Cache frequently accessed data where possible

### **Development**

* Test thoroughly across different user roles
* Implement comprehensive error handling
* Document your workflow's expected behaviour
* Follow established naming conventions

***

**Need Help?** Contact the support team for workflow registration, technical support, or security review requirements.
