Business API Design Specification - Create Chatmessage

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createChatMessage Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createChatMessage Business API is designed to handle a create operation on the ChatMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Send a message to the AI fitness coach. Enforces the full validation chain: subscription check → ban status check → quota check → content flagging → AI processing → tool call execution → quota increment. Returns both the user message and the AI response.

API Frontend Description By The Backend Architect

Chat Message Creation

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createChatMessage Business API includes a REST controller that can be triggered via the following route:

/v1/chatmessages

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createChatMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createChatMessage Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
chatMessageId ID No - body chatMessageId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
conversationId ID Yes `` body conversationId
Description: The conversation to send the message to
content Text Yes `` body content
Description: The message content

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createChatMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    conversationId: runMScript(() => (this.conversationId), {"path":"services[1].businessLogic[0].dataClause.customData[0].value"}),
    content: runMScript(() => (this.content), {"path":"services[1].businessLogic[0].dataClause.customData[1].value"}),
    role: runMScript(() => ('user'), {"path":"services[1].businessLogic[0].dataClause.customData[2].value"}),
    flagged: runMScript(() => (false), {"path":"services[1].businessLogic[0].dataClause.customData[3].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.chatMessageId,
  content: runMScript(() => (this.content), {"path":"services[1].businessLogic[0].dataClause.customData[1].value"}),
  conversationId: runMScript(() => (this.conversationId), {"path":"services[1].businessLogic[0].dataClause.customData[0].value"}),
  flagged: runMScript(() => (false), {"path":"services[1].businessLogic[0].dataClause.customData[3].value"}),
  role: runMScript(() => ('user'), {"path":"services[1].businessLogic[0].dataClause.customData[2].value"}),
  toolCallData: this.toolCallData,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Action : fetchConversationForMsg

Action Type: FetchObjectAction

Fetch the conversation to validate ownership

class Api {
  async fetchConversationForMsg() {
    // Fetch Object on childObject coachConversation

    const userQuery = {
      $and: [
        {
          id: runMScript(() => this.conversationId, {
            path: "services[1].businessLogic[0].actions.fetchObjectActions[0].matchValue",
          }),
        },
        { isActive: true },
      ],
    };
    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getCoachConversationByQuery(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:coachConversation");
    }

    return data
      ? {
          id: data["id"],
          userId: data["userId"],
          status: data["status"],
        }
      : null;
  }
}

[4] Action : checkSubForMsg

Action Type: InterserviceCallAction

Check if user has active subscription

class Api {
  async checkSubForMsg() {
    const { InterService } = require("serviceCommon");

    const bodyParams = {};

    bodyParams["userId"] = runMScript(() => this.session.userId, {
      path: "services[1].businessLogic[0].actions.interserviceCallActions[0].apiParameters[0].value",
    });

    const resp = await InterService.callSubscriptionCheckSubscriptionStatus({
      body: bodyParams,
    });

    return resp?.content ?? resp;
  }
}

[5] Action : checkBanForMsg

Action Type: FunctionCallAction

Check if user has active ban or suspension

class Api {
  async checkBanForMsg() {
    try {
      return await runMScript(
        () => (async () => await LIB.checkBanStatusFn(this.session.userId))(),
        {
          path: "services[1].businessLogic[0].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction checkBanForMsg:", err);
      throw err;
    }
  }
}

[6] Action : checkQuotaForMsg

Action Type: FunctionCallAction

Check if user has message quota remaining

class Api {
  async checkQuotaForMsg() {
    try {
      return await runMScript(
        () => (async () => await LIB.checkQuotaFn(this.session.userId))(),
        {
          path: "services[1].businessLogic[0].actions.functionCallActions[1].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction checkQuotaForMsg:", err);
      throw err;
    }
  }
}

[7] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[8] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[9] Action : validateConversationOwnership

Action Type: ValidationAction

Ensure user owns the conversation

class Api {
  async validateConversationOwnership() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () => this.fetchedConversation.userId === this.session.userId,
      {
        path: "services[1].businessLogic[0].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError("You do not have access to this conversation");
    }
    return isValid;
  }
}

[10] Action : validateConversationActive

Action Type: ValidationAction

Ensure the conversation is active

class Api {
  async validateConversationActive() {
    const isValid = runMScript(
      () => this.fetchedConversation.status === "active",
      {
        path: "services[1].businessLogic[0].actions.validationActions[1].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("This conversation is closed");
    }
    return isValid;
  }
}

[11] Action : validateSubForMsg

Action Type: ValidationAction

Active subscription required

class Api {
  async validateSubForMsg() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () =>
        this.activeSubscriptions?.subscriptions &&
        this.activeSubscriptions?.subscriptions.length > 0,
      {
        path: "services[1].businessLogic[0].actions.validationActions[2].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError(
        "Active subscription required to use the AI coach",
      );
    }
    return isValid;
  }
}

[12] Action : validateNotBannedForMsg

Action Type: ValidationAction

User must not be banned or suspended

class Api {
  async validateNotBannedForMsg() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () => this.banStatus && this.banStatus.isBanned === false,
      {
        path: "services[1].businessLogic[0].actions.validationActions[3].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError("Your account is currently suspended or banned");
    }
    return isValid;
  }
}

[13] Action : validateQuotaForMsg

Action Type: ValidationAction

Message quota must not be exceeded

class Api {
  async validateQuotaForMsg() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () => this.quotaCheck && this.quotaCheck.available === true,
      {
        path: "services[1].businessLogic[0].actions.validationActions[4].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError(
        "Message quota exceeded. Please wait for the next period or contact support.",
      );
    }
    return isValid;
  }
}

[14] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[15] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[16] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[17] Action : runMessagePipeline

Action Type: FunctionCallAction

Main AI processing pipeline: flag content, process with AI coach, execute tool calls, increment quota

class Api {
  async runMessagePipeline() {
    try {
      return await runMScript(
        () => (async () => await LIB.processMessagePipeline(this))(),
        {
          path: "services[1].businessLogic[0].actions.functionCallActions[2].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction runMessagePipeline:", err);
      throw err;
    }
  }
}

[18] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[19] Action : addAiResponseToOutput

Action Type: AddToResponseAction

Add AI response to the API response

class Api {
  async addAiResponseToOutput() {
    try {
      this.output["aiResponse"] = runMScript(() => this.aiResponse, {
        path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[0].contextValue",
      });

      this.output["remainingQuota"] = runMScript(
        () => this.quotaCheck.remaining,
        {
          path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[1].contextValue",
        },
      );

      this.output["existQuota"] = runMScript(() => this.quotaCheck.existQuota, {
        path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[2].contextValue",
      });

      this.output["additionalQuota"] = runMScript(
        () => this.quotaCheck?.additionalQuota,
        {
          path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[3].contextValue",
        },
      );

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[20] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[21] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createChatMessage api has got 2 regular client parameters

Parameter Type Required Population
conversationId ID true request.body?.[“conversationId”]
content Text true request.body?.[“content”]

REST Request

To access the api you can use the REST controller with the path POST /v1/chatmessages

  axios({
    method: 'POST',
    url: '/v1/chatmessages',
    data: {
            conversationId:"ID",  
            content:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the chatMessage object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chatMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chatMessage": {
		"id": "ID",
		"content": "Text",
		"conversationId": "ID",
		"flagged": "Boolean",
		"role": "Enum",
		"role_idx": "Integer",
		"toolCallData": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}