# RevCent MCP Operation: `CreateAIAssistant`

This document describes the `CreateAIAssistant` MCP operation and explains how to configure AI Assistant triggers and flows, with extra detail on Flow / Thread Builder design.

Sources used:
- RevCent MCP operation schema for `CreateAIAssistant`
- RevCent Knowledge Base: AI Assistants — `https://kb.revcent.com/tools/ai/assistants`
- RevCent AI Assistant Overview — `https://revcent.com/documentation/markdown/mcp/operation/OverviewAIAssistant.md`

---

---

# Read the AI Assistant Overview First

Before creating, editing, or deeply configuring AI Assistants, MCP/AI should read the AI Assistant overview:

```text
https://revcent.com/documentation/markdown/mcp/operation/OverviewAIAssistant.md
```

The overview explains AI Assistants as a whole, including:

```text
What AI Assistants are.
Why ecommerce businesses use AI Assistants.
How AI Threads work.
Trigger types.
Thread Builder concepts.
System tools.
Cost controls.
Event filters.
Flow design patterns.
Automation use cases.
Best practices and caveats.
```

This operation file is focused on the specific API/MCP operation. The overview provides the broader conceptual context MCP/AI should understand before making design decisions about an AI Assistant.

## Operation Summary

`CreateAIAssistant` creates a new RevCent AI Assistant and returns a unique 20-character `ai_assistant_id`.

A RevCent AI Assistant is an autonomous AI automation that runs in the background when triggered. Instead of a user chatting directly with the AI, RevCent starts an AI Thread and orchestrates the AI through a configured flow.

High-level lifecycle:

1. The AI Assistant is triggered.
2. RevCent creates a unique AI Thread.
3. The AI follows the configured Flow / Thread Builder.
4. RevCent orchestrates communication with the selected AI model.
5. The AI can analyze data, use tools, create notes, send emails, run functions, create AI memos, or trigger other configured workflows depending on the thread steps and available system tools.

---

## Required Fields

`CreateAIAssistant` requires:

| Field | Type | Required | Description |
|---|---:|---:|---|
| `name` | string | Yes | AI Assistant name. |
| `settings` | object | Yes | AI Assistant settings, including instructions, trigger settings, and flow. |
| `third_party_integration` | string | Yes | 20-character user third-party integration ID for an AI provider. |

Optional fields:

| Field | Type | Required | Description |
|---|---:|---:|---|
| `description` | string | No, but highly recommended | Human-readable explanation of what the assistant does. |
| `enabled` | boolean | No | Whether the assistant is enabled. |

---

# Why Create an AI Assistant?

Create an AI Assistant when you want AI to perform repeatable ecommerce automation.

Common use cases:

- Analyze declined sales.
- Create notes summarizing customer behavior.
- Trigger a follow-up email after a refund, chargeback, or failed renewal.
- Review customer notes and identify chargeback threats.
- Analyze failed gateway responses.
- Avoid futile `ProcessPendingSale` or `ProcessSalvageTransaction` attempts by filtering hard-decline reasons.
- Trigger Functions with inferred custom arguments.
- Create AI Memos for important account events.
- Run scheduled analytics and generate alerts.
- Triage customer or order activity.
- Trigger another assistant as part of a broader AI workflow.

AI Assistants are best suited for workflows that require reasoning, classification, summarization, decision-making, or tool orchestration.

---

# General Settings

## `name`

The name should be easy to read and unique.

Recommended format:

```text
<Trigger or Purpose> - <Action or Outcome>
```

Examples:

```text
Declined Sale - Recovery Analysis
Chargeback Created - Risk Memo
Daily Revenue - AI Summary
Customer Note - Chargeback Threat Detection
Subscription Renewal Failed - Customer Follow-Up
```

---

## `description`

The description should explain what the AI Assistant does as if another human or AI Assistant is reading it without context.

Descriptions are especially useful when one AI Assistant can trigger another AI Assistant as a system tool.

Good description:

```text
Analyzes declined sales, determines the most likely decline reason, creates a note, and sends a follow-up email if the sale is eligible for recovery.
```

Poor description:

```text
Decline bot
```

---

## `third_party_integration`

**Type:** `string`  
**Required:** Yes  
**Length:** 20 characters

The third-party AI integration that powers the assistant.

Supported AI third parties include:

- OpenAI
- Google Gemini
- xAI
- OpenRouter

Before creating an AI Assistant, the third-party integration should already exist in RevCent and should be a site integration of type `ai`.

---

## `enabled`

**Type:** `boolean`  
**Required:** No

Whether the AI Assistant is enabled.

Recommended approach:

- Use `enabled: false` while drafting, testing, or validating a new assistant.
- Enable only after the trigger and flow are safe and correct.

---

# `settings`

The `settings` object contains the assistant’s instructions, trigger settings, flow, and optional limits.

Schema-level required fields inside `settings`:

| Field | Required | Purpose |
|---|---:|---|
| `assistant_instructions` | Yes | Base system instructions given to the AI for every thread. |
| `trigger_settings` | Yes | Determines when the assistant runs. |
| `flow` | Yes | Defines the Thread Builder nodes and connections. |

---

## `settings.assistant_instructions`

**Type:** `string`  
**Required:** Yes

These are the base instructions provided to the AI model with every AI Thread for this Assistant.

Use assistant instructions to describe the AI Assistant’s overall role and behavior.

Good examples:

```text
You are an AI Assistant that analyzes declined ecommerce sales and determines whether a recovery action is appropriate.
```

```text
You are an AI Assistant that reviews customer notes and identifies potential chargeback threats.
```

Important:

- Assistant instructions should describe the assistant’s broad purpose.
- Do not put step-by-step actions here.
- Specific tasks should be placed in Flow `action_step` nodes.
- The KB states that AI instructions are passed to the AI as the system role.

---

## `settings.assistant_limits`

**Type:** `object`  
**Required:** No

Limits token usage for the assistant and its threads.

Highly recommended to control costs.

### `thread_max_tokens`

**Type:** `integer`

Maximum tokens that one AI Thread can consume before being stopped.

- `0` means no limit.
- Recommended for preventing a single runaway thread from consuming too many tokens.

### `token_max_per_day`

**Type:** `integer`

Maximum tokens the AI Assistant can consume in a 24-hour period.

- `0` means no limit.
- Recommended for budget control.

---

# Trigger Settings

The trigger determines what activates the AI Assistant.

Schema-supported trigger values:

```text
account_event
on_demand
schedule
```

Trigger summary:

| Trigger | Description | Common Use |
|---|---|---|
| `account_event` | Runs when a specific RevCent account event occurs. | Sale declined, chargeback created, shipment shipped, subscription renewal failed. |
| `on_demand` | Runs via API, web app, or as a system tool from another AI Assistant. | Manual analysis, AI tool orchestration, support workflows. |
| `schedule` | Runs on a fixed schedule using a five-part cron expression. | Daily summaries, scheduled checks, recurring AI analysis. |

---

# Trigger: `account_event`

Use `account_event` when the AI Assistant should automatically run after a RevCent account event occurs.

Examples:

- Sale created successfully.
- Sale failed or declined.
- Customer created.
- Customer updated.
- Chargeback created.
- Fraud detection created.
- Shipping shipped.
- Subscription renewed.
- Subscription renewal failed.
- Trial expired.
- Invoice created.
- AI memo created.

---

## `trigger_settings.account_event.notation`

The event notation determines exactly which account event triggers the assistant.

Example:

```json
"trigger_settings": {
  "trigger": "account_event",
  "account_event": {
    "notation": "sale.created.failed.declined"
  }
}
```

Important:

- Use the most specific notation possible.
- For declined-sale recovery, prefer `sale.created.failed.declined` over broad `sale.created`.
- For paid successful sales, use `sale.created.success.paid`.
- For subscription renewal failures, use `subscription_renewal.updated.failed`.

---

## Account Event Data

Account event data is based on the item type from the first segment of the notation.

Examples:

| Event notation | Item type |
|---|---|
| `sale.created.failed.declined` | `sale` |
| `customer.created` | `customer` |
| `shipping.updated.shipped` | `shipping` |
| `subscription_renewal.updated.failed` | `subscription_renewal` |
| `trial.updated.expired.success` | `trial` |

The AI Assistant start thread node automatically gives the AI context about the item that triggered the event. For example, if the assistant is triggered by a new sale, the start node asks the AI to retrieve the sale details and keep those details in thread message history.

---

## Account Event Filters

Account event filters limit whether the assistant should run after the event occurs.

### `campaign_filter`

Only run for items associated with selected campaigns.

```json
"filters": {
  "campaign_filter": ["XXXXXXXXXXXXXXXXXXXX"]
}
```

### `status_filter`

Only run for matching statuses.

The available statuses depend on the item type. The item type is determined by the first word in the account event notation.

Example:

- `sale.created...` uses sale statuses.
- `shipping.updated...` uses shipping statuses.
- `subscription.updated...` uses subscription statuses.

### `metadata_filter`

Only run for items that have matching metadata name/value pairs.

```json
"metadata_filter": [
  {
    "name": "source",
    "value": "affiliate"
  }
]
```

Important:

- Metadata filters require matching all specified name/value pairs.
- Use metadata filters to keep assistants from running on irrelevant records.

---

## Filter Function

A filter function adds custom code-based filtering before the AI Assistant runs.

Field:

```json
"filter_function": "XXXXXXXXXXXXXXXXXXXX"
```

Requirements:

- The Function must have `event_source: "api_direct"`.
- The Function receives item data.
- The Function must return exactly one string:
  - `"pass"`
  - `"fail"`

Pass:

```javascript
callback(null, 'pass');
```

Fail:

```javascript
callback(null, 'fail');
```

Meaning:

- `pass`: the assistant runs.
- `fail`: the assistant does not run.
- Default behavior is effectively pass if no filter function is used.

Use cases:

- Only run the assistant for sales above a certain amount.
- Only run for customers with specific metadata.
- Skip customers who opted out.
- Run only when a product list matches custom logic.
- Prevent repeated or risky AI workflows.

---


---

## Filter Function vs. Step-Triggered Function

A `filter_function` is different from a Function that the AI Assistant triggers inside a flow `action_step`.

### Filter Function

A filter function is used before the AI Assistant thread starts. Its main purpose is to save tokens and reduce unnecessary AI runs by allowing only account events that pass specific criteria to continue into the assistant flow.

Use a filter function when you want to decide whether an account event is worthy of AI Assistant analysis before spending AI tokens.

Examples:

- Skip low-value declined sales.
- Skip customers who opted out.
- Only run for certain product, metadata, campaign, or customer conditions.
- Prevent the assistant from running on events that are not important enough for AI review.

A filter function must return exactly one string:

```text
pass
fail
```

If it returns `pass`, the AI Assistant runs. If it returns `fail`, the AI Assistant does not run.

### Function Triggered Within a Flow Step

A separate Function can also be triggered from within an `action_step`, but that Function is not used for account-event filtering. Instead, it is used after the assistant thread has already started and is meant to do anything else the user wants based on the assistant’s needs.

Use a step-triggered Function when the AI Assistant needs to perform custom logic, call an external system, transform data, look something up, or execute a business process as part of the flow.

Examples:

- Calculate custom recovery eligibility after the AI has reviewed the sale.
- Send data to an external CRM or webhook.
- Run custom account logic that is not available as a built-in system tool.
- Generate custom arguments or outputs needed by later steps.
- Perform any user-defined action that supports the assistant’s workflow.

In short:

| Function Type | When It Runs | Main Purpose | Token Impact | Typical Result |
|---|---|---|---|---|
| `filter_function` | Before the AI Assistant thread starts | Decide whether the account event deserves AI processing | Saves tokens by preventing unnecessary AI runs | `pass` or `fail` |
| Step-triggered Function | During an `action_step` after the thread starts | Perform custom work needed by the assistant flow | Uses tokens because the assistant is already running | Any function-specific output needed by the workflow |

## Delay

The delay determines how long after the account event occurs the AI Assistant thread starts.

Schema:

```json
"delay": {
  "time_value": 5,
  "time_unit": "minutes"
}
```

Allowed units:

```text
minutes
hours
days
```

Important KB details:

- Default minimum delay is 1 minute.
- Maximum delay is 30 days.
- Delays are useful when related events may occur shortly after the initial event.

Example:

A sale failure event may be followed by salvage transaction creation or related updates. A delay gives RevCent time to gather related activity before the AI starts analyzing.

---

## Account Event Limits

Limits prevent the same assistant from running too many times for the same item.

### `max_run_count`

Maximum number of times this specific AI Assistant can run for the same item.

Highly recommended:

```json
"max_run_count": 1
```

Why this matters:

If an assistant is triggered by declined sales and then attempts to reprocess a sale, a second decline can create another declined-sale event for the same sale. Without max-run protection, the assistant could trigger again.

### `min_time_value` and `min_time_unit`

Only applies if `max_run_count` is greater than 1.

Example:

```json
"limits": {
  "max_run_count": 2,
  "min_time_value": 1,
  "min_time_unit": "days"
}
```

This allows a second run for the same item only after at least 1 day.

---

# Trigger: `on_demand`

Use `on_demand` when the AI Assistant should run only when explicitly triggered.

On-demand assistants can be triggered by:

- API
- Web app
- Another AI Assistant as a System Tool

Example:

```json
"trigger_settings": {
  "trigger": "on_demand"
}
```

---

## On Demand via API

The AI Assistant can be triggered remotely through the `TriggerAIAssistant` operation.

Important:

- Only assistants with trigger setting `on_demand` can be triggered via API.
- Triggering creates an AI Thread.
- Use this for controlled, explicit automation.

Use cases:

- Analyze a specific customer.
- Summarize a sale.
- Run a manual customer support workflow.
- Ask AI to process an item selected by an external system.

---

## On Demand via Web App

If web access is configured in the web app, users can trigger an assistant from item detail pages.

Use cases:

- A support rep opens a customer and triggers an AI analysis.
- A finance user opens a chargeback and triggers an AI review.
- A manager opens a sale and triggers an AI recovery workflow.

---

## On Demand from Another Assistant

An AI Assistant can trigger another AI Assistant from within its thread.

This is useful for composing specialized assistants.

Example:

- Assistant A detects a chargeback threat.
- Assistant A triggers Assistant B, which specializes in chargeback mitigation.
- Assistant B creates a memo or sends a configured email.

Descriptions matter here because another assistant may need to identify which assistant to trigger.

---

# Trigger: `schedule`

Use `schedule` when the assistant should run repeatedly on a fixed cron schedule.

Example:

```json
"trigger_settings": {
  "trigger": "schedule",
  "schedule": {
    "cron_expression": "0 9 * * *",
    "cron_timezone": "America/New_York"
  }
}
```

---

## `cron_expression`

Must be a standard five-part cron expression:

```text
minute hour day-of-month month day-of-week
```

Example:

```text
0 9 * * *
```

Meaning: run every day at 9:00 AM in the configured timezone.

Important KB notes:

- Intervals cannot be less than 1 hour apart.
- Scheduled assistants are checked every 10 minutes, so exact execution may vary by up to 10 minutes.
- Only standard five-part cron expressions are supported.
- `@daily`, `@hourly`, and similar shortcut syntax is not supported.

---

## `cron_timezone`

Must be a valid IANA timezone string.

Examples:

```text
UTC
America/New_York
America/Los_Angeles
Europe/London
```

If omitted, UTC is used.

---

# Flow / Thread Builder

The `flow` array defines how the AI Assistant thread runs after the assistant is triggered.

In the KB, this is called the Thread Builder. In the API schema, it is the `settings.flow` array.

Each flow is an array of connected nodes.

Each node has:

| Field | Purpose |
|---|---|
| `id` | Unique node ID within the flow. |
| `type` | Node type. |
| `inputs` | Connections from previous nodes. |
| `outputs` | Connections to next nodes. |
| `position` | Optional UI positioning. |
| `node_settings` | Settings based on node type. |

---

## Flow Node Types

Schema-supported node types:

```text
start_thread
action_step
action_branch
action_time_delay
action_end_thread
```

| Node Type | Purpose |
|---|---|
| `start_thread` | Starting point of the AI Thread. |
| `action_step` | Sends a task/message to the AI. |
| `action_branch` | Lets AI choose a path based on conditional messages. |
| `action_time_delay` | Pauses the thread before continuing. |
| `action_end_thread` | Ends the thread. |

---

## Flow Connection Rules

Important schema rules:

- Each node must have a unique `id`.
- Nodes connect using `inputs` and `outputs`.
- `start_thread` has no inputs.
- `action_end_thread` has no outputs.
- A node input can connect from only one other node output.
- A node output can connect to only one other node input.
- Multiple nodes cannot connect into the same input.
- Multiple nodes cannot connect from the same output.
- `action_branch` can have up to four outputs:
  - `output_1`
  - `output_2`
  - `output_3`
  - `output_4`

---

## `position`

`position` controls how the node appears in the RevCent UI.

It does not affect execution.

Schema:

```json
"position": {
  "x_axis": 0,
  "y_axis": 0
}
```

Recommended:

- Provide positions when possible.
- The UI node is approximately 300px wide and 400px high.
- Use spacing to keep the flow readable.

Example layout:

| Node | x_axis | y_axis |
|---|---:|---:|
| Start | 0 | 0 |
| Step 1 | 400 | 0 |
| Branch | 800 | 0 |
| Output 1 Step | 1200 | -300 |
| Output 2 Step | 1200 | 100 |
| End | 1600 | 0 |

---

# Flow Node: `start_thread`

The `start_thread` node is the starting point.

Important:

- It occurs once when the thread starts.
- It does not have inputs.
- It typically connects to the first `action_step`, `action_branch`, `action_time_delay`, or `action_end_thread`.
- The start message is predetermined based on the trigger and item type.

For account-event triggers, if a sale triggers the assistant, the start thread tells the AI to retrieve the sale details. The sale details remain in thread history so later steps can reference them without retrieving them again.

Minimal start node:

```json
{
  "id": "start",
  "type": "start_thread",
  "outputs": {
    "output_1": {
      "connections": [
        {
          "node": "step_review_sale",
          "output": "input_1"
        }
      ]
    }
  },
  "position": {
    "x_axis": 0,
    "y_axis": 0
  }
}
```

---

# Flow Node: `action_step`

An `action_step` sends a message to the AI.

Schema setting:

```json
"node_settings": {
  "step_message": "Review the sale and create a note summarizing what happened."
}
```

Use `action_step` for specific instructions.

Examples:

```text
Review the sale and determine whether the decline appears recoverable.
```

```text
Read the customer notes. If the notes indicate the customer threatened a chargeback, create an AI Memo explaining the risk.
```

```text
Find the Instant Full Refund email template and send an SMTP message using that template with a customized apology.
```

Important:

- Write step messages as if giving instructions to a human.
- Be clear and precise.
- Put action-specific instructions in steps, not in `assistant_instructions`.
- The AI may use available system tools depending on what the step asks and what tools are available.

### AI Flow Step System Tools

The AI Assistant has RevCent operations are available for AI use in a flow `action_step`.

Important:

- You do not manually attach operation IDs to an individual `action_step`.
- Write the `step_message` in natural language and name the outcome you want.
- The AI can select from the allowed system tools when the step requires data retrieval, note creation, email sending, refunds, function execution, or another supported action.
- Tool availability can still depend on account permissions, object status, trigger context, and operation-specific requirements.
- Be explicit before customer-facing or financial actions such as sending email, canceling a subscription, refunding, or deleting data.

Operations in the AI Assistant schema that are available to the AI in a flow step include:

| Area | Operations | Typical flow-step use |
|---|---|---|
| AI Assistants | `GetAIAssistants`, `GetAIAssistant`, `TriggerAIAssistant` | Find and trigger another on-demand assistant. |
| AI Memos | `GetAIMemos`, `GetAIMemo`, `CreateAIMemo`, `DeleteAIMemo` | Create or review AI-generated memos. |
| AI Prompts | `GetAIPrompts`, `GetAIPrompt`, `CreateAIPrompt`, `EditAIPrompt`, `DeleteAIPrompt` | Reuse or manage stored AI prompt text. |
| AI Threads | `GetAIThreads`, `GetAIThread`, `CancelAIThread` | Review or stop AI thread activity. |
| API Calls | `GetAPICall` | Inspect a previous API call response or failure. |
| Chargebacks | `GetChargebacks`, `GetChargeback`, `CreateChargeback` | Retrieve or create chargeback records. |
| Customers and Cards | `SearchCustomers`, `GetCustomer`, `CreateCustomer`, `EditCustomer`, `DisableCustomer`, `EnableCustomer`, `SetDefaultCustomerCard`, `DeleteCustomerCard` | Find, review, update, enable/disable customers, and manage stored cards. |
| Email Templates and SMTP | `GetEmailTemplates`, `GetEmailTemplate`, `SendSMTPMessage` | Find an API-direct email template and send a templated message. |
| Functions | `GetFunctions`, `GetFunction`, `TriggerFunction` | Find a function, inspect its custom arguments, and run it. |
| Gateway Groups | `GetGatewayGroups`, `GetGatewayGroup`, `AddUserGatewayToGatewayGroup`, `RemoveUserGatewayFromGatewayGroup` | Review or update gateway group membership. |
| Invoices | `GetInvoices`, `GetInvoice` | Retrieve invoice details. |
| Key Values | `GetKeyValues`, `CreateKeyValue`, `GetKeyValue`, `EditKeyValue` | Store or retrieve account-level key/value data. |
| Metadata and Notes | `InsertMetadata`, `CreateNote` | Add structured metadata or create item notes. |
| Payments and Transactions | `SearchTransactions`, `GetTransactions`, `GetTransaction`, `RefundTransaction`, `SearchPayPalTransactions`, `GetPayPalTransaction`, `GetOfflinePayment`, `GetCheckDirect` | Retrieve payment activity and issue supported transaction refunds. |
| Products and Product Sales | `SearchProducts`, `GetProduct`, `DisableProduct`, `EnableProduct`, `GetProductSales`, `GetProductSale`, `RefundProductSale` | Search/review products, change product availability, or refund product sales. |
| Sales | `SearchSales`, `GetSales`, `GetSale`, `AddFraudAlert`, `RemoveFraudAlert` | Retrieve sales and manage fraud alerts. |
| Shipping | `SearchShipping`, `GetShipments`, `GetShipment`, `RefundShipment` | Retrieve shipment details or refund shipment charges. |
| Subscriptions | `SearchSubscriptions`, `GetSubscriptions`, `GetSubscription`, `CancelSubscription`, `SuspendSubscription`, `ReactivateSubscription`, `RenewSubscription` | Review or manage subscriptions. |
| Subscription Renewals | `GetSubscriptionRenewals`, `GetSubscriptionRenewal`, `RefundSubscriptionRenewal` | Retrieve or refund subscription renewals. |
| Tax | `GetTaxes`, `GetTax`, `RefundTax` | Retrieve or refund tax records. |
| Trials | `SearchTrials`, `GetTrials`, `GetTrial`, `ExtendTrial`, `ShortenTrial`, `CancelTrial` | Review or modify trial records. |
| Related-item retrieval | `GetDiscount`, `GetLicenseKey`, `GetPendingRefund`, `GetFraudDetection`, `GetSalvageTransaction` | Retrieve related records referenced by another item. |

Example flow-step instructions:

```text
Review the triggered sale, retrieve related transactions and customer details, then create a note summarizing whether recovery is appropriate.
```

```text
Find the correct API-direct email template, confirm the required custom arguments, then send a customer apology email only if the sale was fully refunded.
```

```text
Retrieve the subscription and customer details. If the customer requested cancellation, cancel the subscription and create an AI Memo summarizing the action taken.
```

Example node:

```json
{
  "id": "step_review_sale",
  "type": "action_step",
  "inputs": {
    "input_1": {
      "connections": [
        {
          "node": "start",
          "input": "output_1"
        }
      ]
    }
  },
  "outputs": {
    "output_1": {
      "connections": [
        {
          "node": "branch_recoverable",
          "output": "input_1"
        }
      ]
    }
  },
  "node_settings": {
    "step_message": "Review the sale details and determine the likely payment failure reason."
  },
  "position": {
    "x_axis": 400,
    "y_axis": 0
  }
}
```

---

# Flow Node: `action_branch`

An `action_branch` lets the AI choose the next path.

It behaves like:

```text
if condition 1
else if condition 2
else if condition 3
else
```

Branch outputs:

| Output | Meaning |
|---|---|
| `output_1` | Used if `output_1_message` is true. |
| `output_2` | Used if `output_2_message` is true. |
| `output_3` | Used if `output_3_message` is true. |
| `output_4` | Else / catch-all path if no condition matches. |

Required setting:

```json
"output_1_message"
```

Optional settings:

```json
"output_2_message"
"output_3_message"
```

Important:

- You must provide at least output 1 condition.
- Output 4 is the fallback else branch.
- The AI evaluates the branch condition messages.
- The AI chooses only one output.
- Branches are useful for dynamic logic where simple filters are not enough.

---

## Branch Example

Goal:

- If customer purchased a USB, follow one path.
- If customer purchased a laptop, follow another path.
- Otherwise, follow default path.

Branch settings:

```json
"node_settings": {
  "output_1_message": "The customer purchased a USB.",
  "output_2_message": "The customer purchased a laptop.",
  "output_3_message": "The customer did not purchase a laptop or a USB."
}
```

The AI evaluates the current thread context and chooses the matching output.

---

## Branch Node Example

```json
{
  "id": "branch_product_type",
  "type": "action_branch",
  "inputs": {
    "input_1": {
      "connections": [
        {
          "node": "step_review_sale",
          "input": "output_1"
        }
      ]
    }
  },
  "outputs": {
    "output_1": {
      "connections": [
        {
          "node": "step_usb_followup",
          "output": "input_1"
        }
      ]
    },
    "output_2": {
      "connections": [
        {
          "node": "step_laptop_followup",
          "output": "input_1"
        }
      ]
    },
    "output_4": {
      "connections": [
        {
          "node": "end",
          "output": "input_1"
        }
      ]
    }
  },
  "node_settings": {
    "output_1_message": "The customer purchased a USB.",
    "output_2_message": "The customer purchased a laptop."
  },
  "position": {
    "x_axis": 800,
    "y_axis": 0
  }
}
```

---

# Flow Node: `action_time_delay`

An `action_time_delay` pauses the thread before continuing.

Schema settings:

```json
"node_settings": {
  "time_unit": "hours",
  "time_value": "2"
}
```

Allowed units:

```text
minutes
hours
days
```

Important KB details:

- Minimum delay is 1 minute.
- Maximum delay is 3 days.
- Threads are stored for a maximum of 7 days since created, regardless of delays.
- Use time delays when you need to wait for related updates.

Use cases:

- Wait after a failed payment before checking if a salvage attempt occurred.
- Wait before checking whether shipping status changed.
- Wait before sending a follow-up or creating an AI Memo.
- Delay escalation to see if customer support resolves an issue first.

---

# Flow Node: `action_end_thread`

An `action_end_thread` ends the AI Thread.

Important:

- It has no outputs.
- If a node has no next connection, the thread self-ends.
- Explicit end nodes make flows clearer.

Example:

```json
{
  "id": "end",
  "type": "action_end_thread",
  "inputs": {
    "input_1": {
      "connections": [
        {
          "node": "step_create_note",
          "input": "output_1"
        }
      ]
    }
  },
  "position": {
    "x_axis": 1200,
    "y_axis": 0
  }
}
```

---

# Full Minimal Flow Example

This flow:

1. Starts the thread.
2. Reviews the triggered item.
3. Ends the thread.

```json
[
  {
    "id": "start",
    "type": "start_thread",
    "outputs": {
      "output_1": {
        "connections": [
          {
            "node": "step_review",
            "output": "input_1"
          }
        ]
      }
    },
    "position": {
      "x_axis": 0,
      "y_axis": 0
    }
  },
  {
    "id": "step_review",
    "type": "action_step",
    "inputs": {
      "input_1": {
        "connections": [
          {
            "node": "start",
            "input": "output_1"
          }
        ]
      }
    },
    "outputs": {
      "output_1": {
        "connections": [
          {
            "node": "end",
            "output": "input_1"
          }
        ]
      }
    },
    "node_settings": {
      "step_message": "Review the triggered item and create a concise note summarizing the most important details."
    },
    "position": {
      "x_axis": 400,
      "y_axis": 0
    }
  },
  {
    "id": "end",
    "type": "action_end_thread",
    "inputs": {
      "input_1": {
        "connections": [
          {
            "node": "step_review",
            "input": "output_1"
          }
        ]
      }
    },
    "position": {
      "x_axis": 800,
      "y_axis": 0
    }
  }
]
```

---

# CreateAIAssistant Request Example: Account Event

Example declined-sale assistant:

```json
{
  "name": "Declined Sale - Recovery Analysis",
  "description": "Analyzes declined sales and creates a note summarizing whether the sale appears recoverable.",
  "enabled": false,
  "third_party_integration": "XXXXXXXXXXXXXXXXXXXX",
  "settings": {
    "assistant_instructions": "You are an AI Assistant that analyzes declined ecommerce sales and determines whether a recovery action is appropriate.",
    "assistant_limits": {
      "thread_max_tokens": 100000,
      "token_max_per_day": 500000
    },
    "trigger_settings": {
      "trigger": "account_event",
      "account_event": {
        "notation": "sale.created.failed.declined",
        "delay": {
          "time_value": 5,
          "time_unit": "minutes"
        },
        "limits": {
          "max_run_count": 1
        }
      }
    },
    "flow": [
      {
        "id": "start",
        "type": "start_thread",
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "step_review_sale",
                "input": "input_1"
              }
            ]
          }
        },
        "position": {
          "x_axis": 0,
          "y_axis": 0
        }
      },
      {
        "id": "step_review_sale",
        "type": "action_step",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "start",
                "input": "output_1"
              }
            ]
          }
        },
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "end",
                "input": "input_1"
              }
            ]
          }
        },
        "node_settings": {
          "step_message": "Review the declined sale, determine the likely decline reason, and create a note summarizing whether the sale appears recoverable."
        },
        "position": {
          "x_axis": 400,
          "y_axis": 0
        }
      },
      {
        "id": "end",
        "type": "action_end_thread",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "step_review_sale",
                "input": "output_1"
              }
            ]
          }
        },
        "position": {
          "x_axis": 800,
          "y_axis": 0
        }
      }
    ]
  }
}
```

---

# CreateAIAssistant Request Example: On Demand

```json
{
  "name": "On Demand - Customer Summary",
  "description": "Triggered manually or via API to summarize a customer and their recent activity.",
  "enabled": false,
  "third_party_integration": "XXXXXXXXXXXXXXXXXXXX",
  "settings": {
    "assistant_instructions": "You are an AI Assistant that summarizes customer activity clearly and concisely for support users.",
    "assistant_limits": {
      "thread_max_tokens": 100000,
      "token_max_per_day": 500000
    },
    "trigger_settings": {
      "trigger": "on_demand"
    },
    "flow": [
      {
        "id": "start",
        "type": "start_thread",
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "step_summary",
                "input": "input_1"
              }
            ]
          }
        }
      },
      {
        "id": "step_summary",
        "type": "action_step",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "start",
                "input": "output_1"
              }
            ]
          }
        },
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "end",
                "input": "input_1"
              }
            ]
          }
        },
        "node_settings": {
          "step_message": "Review the item details and create a concise summary of the most important customer activity."
        }
      },
      {
        "id": "end",
        "type": "action_end_thread",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "step_summary",
                "input": "output_1"
              }
            ]
          }
        }
      }
    ]
  }
}
```

---

# CreateAIAssistant Request Example: Schedule

```json
{
  "name": "Schedule - Daily Revenue AI Memo",
  "description": "Runs daily and creates an AI Memo if revenue or decline rates appear unusual.",
  "enabled": false,
  "third_party_integration": "XXXXXXXXXXXXXXXXXXXX",
  "settings": {
    "assistant_instructions": "You are an AI Assistant that analyzes ecommerce metrics and identifies unusual revenue or payment patterns.",
    "assistant_limits": {
      "thread_max_tokens": 100000,
      "token_max_per_day": 500000
    },
    "trigger_settings": {
      "trigger": "schedule",
      "schedule": {
        "cron_expression": "0 9 * * *",
        "cron_timezone": "America/New_York"
      }
    },
    "flow": [
      {
        "id": "start",
        "type": "start_thread",
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "step_analyze_metrics",
                "input": "input_1"
              }
            ]
          }
        }
      },
      {
        "id": "step_analyze_metrics",
        "type": "action_step",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "start",
                "input": "output_1"
              }
            ]
          }
        },
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "end",
                "input": "input_1"
              }
            ]
          }
        },
        "node_settings": {
          "step_message": "Run a BigQuery analysis of yesterday's sales and transaction decline rate. If there is an unusual change, create an AI Memo summarizing the issue."
        }
      },
      {
        "id": "end",
        "type": "action_end_thread",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "step_analyze_metrics",
                "input": "output_1"
              }
            ]
          }
        }
      }
    ]
  }
}
```

---

# Output Schema

A successful `CreateAIAssistant` response returns:

```json
{
  "api_call_id": "XXXXXXXXXXXXXXXXXXXX",
  "api_call_unix": 1740000000,
  "code": 1,
  "ai_assistant_id": "XXXXXXXXXXXXXXXXXXXX",
  "result": "..."
}
```

Fields:

| Field | Description |
|---|---|
| `api_call_id` | 20-character API call ID. |
| `api_call_unix` | Unix timestamp when the API call was initiated. |
| `code` | Response code. `1` indicates success. |
| `ai_assistant_id` | 20-character ID of the created AI Assistant. |
| `result` | Human-readable result message. |

---

# Implementation Checklist

## AI Integration Verification Before Creating an Assistant

Before proceeding with `CreateAIAssistant`, the system should first verify that the user already has at least one AI third-party integration configured in RevCent.

Recommended process:

1. List all third-party integrations where the integration type is `ai`.
2. If the user has exactly one AI integration:
   - Use that integration automatically for `third_party_integration`.
3. If the user has more than one AI integration:
   - Present the available AI integrations to the user.
   - Have the user choose which integration should power the AI Assistant.
4. If the user has no AI integrations:
   - An AI integration must be created before continuing.
   - The assistant creation process should stop until a valid AI integration exists.

Why this matters:

- `CreateAIAssistant` requires a valid 20-character AI `third_party_integration` ID.
- The integration determines which AI provider powers the assistant.
- Different integrations may use different providers, models, billing configurations, or API credentials.

Supported AI integrations can include:

- OpenAI
- Google Gemini
- xAI
- OpenRouter

Important:

- Only integrations configured as type `ai` should be considered valid.
- Do not assume a usable AI integration exists.
- Always verify available AI integrations before attempting assistant creation.


Before calling `CreateAIAssistant`:

0. Confirm the AI Assistant overview has been reviewed when making broader design decisions.
1. Confirm the AI third-party integration exists and is type `ai`.
2. Use the 20-character third-party integration ID.
3. Choose a clear assistant name.
4. Add a useful description.
5. Write broad assistant instructions, not step-specific tasks.
6. Choose the correct trigger: `account_event`, `on_demand`, or `schedule`.
7. For account-event triggers, use the most specific event notation.
8. For account-event triggers, use filters where appropriate.
9. Use a `filter_function` only to decide whether an account event should start the assistant; use step-triggered Functions inside `action_step` nodes for custom workflow actions after the assistant has started.
11. For account-event triggers, set `max_run_count` to `1` unless repeated runs are intentional.
11. For account-event triggers, add delay if related events need time to occur.
12. For schedule triggers, use a valid five-part cron expression.
13. Set token limits to control cost.
14. Build a flow with one `start_thread` node.
15. Use `action_step` nodes for specific instructions.
16. Use `action_branch` nodes for AI-driven conditional paths.
17. Use `action_time_delay` nodes only when waiting is necessary.
18. Add explicit `action_end_thread` nodes where helpful.
19. Ensure every node ID is unique.
20. Ensure every input/output connection points to an existing node.
21. Ensure each input and output has at most one connection.
22. Provide node positions when possible for a readable UI flow.
23. Create the assistant disabled first if the workflow is not fully tested.
24. Test with realistic events or on-demand triggers before enabling production automation.

---

# Quick Reference

Minimal conceptual request:

```json
{
  "name": "Declined Sale - Recovery Analysis",
  "description": "Analyzes declined sales and creates a note with recovery guidance.",
  "enabled": false,
  "third_party_integration": "XXXXXXXXXXXXXXXXXXXX",
  "settings": {
    "assistant_instructions": "You are an AI Assistant that analyzes declined ecommerce sales.",
    "trigger_settings": {
      "trigger": "account_event",
      "account_event": {
        "notation": "sale.created.failed.declined",
        "limits": {
          "max_run_count": 1
        }
      }
    },
    "flow": [
      {
        "id": "start",
        "type": "start_thread",
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "step_1",
                "input": "input_1"
              }
            ]
          }
        }
      },
      {
        "id": "step_1",
        "type": "action_step",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "start",
                "input": "output_1"
              }
            ]
          }
        },
        "outputs": {
          "output_1": {
            "connections": [
              {
                "node": "end",
                "input": "input_1"
              }
            ]
          }
        },
        "node_settings": {
          "step_message": "Review the declined sale and create a note summarizing the likely reason."
        }
      },
      {
        "id": "end",
        "type": "action_end_thread",
        "inputs": {
          "input_1": {
            "connections": [
              {
                "node": "step_1",
                "input": "output_1"
              }
            ]
          }
        }
      }
    ]
  }
}
```


---

# Overview Reference

MCP/AI should read the AI Assistant overview for broad conceptual understanding:

```text
https://revcent.com/documentation/markdown/mcp/operation/OverviewAIAssistant.md
```


---
Document Parent Directory
* [Operations](https://revcent.com/documentation/markdown/mcp/operation/index.md) - AI/MCP details and overviews for operations available within the RevCent MCP.