Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

6.6 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
  Property,
  StaticPropsValue,
  AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
import {
  DedupeStrategy,
  HttpMethod,
  Polling,
  pollingHelper,
} from '@activepieces/pieces-common';
import { frontAuth } from '../common/auth';
import { makeRequest } from '../common/client';

const props = {
  inbox_id: Property.ShortText({
    displayName: 'Inbox ID',
    description: 'The ID of the inbox to monitor for new inbound messages.',
    required: false,
  }),
};

const polling: Polling<AppConnectionValueForAuthProperty<typeof frontAuth>, StaticPropsValue<typeof props>> = {
  strategy: DedupeStrategy.TIMEBASED,
  items: async ({ auth, propsValue, lastFetchEpochMS }) => {
    let query = `q[types]=inbound`;
    if (propsValue.inbox_id) {
      query += `&q[inboxes]=${propsValue.inbox_id}`;
    }
    const limit = 15;
    const response = await makeRequest(
      auth,
      HttpMethod.GET,
      `/events?${query}&limit=${limit}`
    );
    const events = response._results || [];
    const inboundMessages: any[] = [];

    for (const event of events) {
      // Only include new events since last fetch
      const emittedAtMs = Math.floor(Number(event.emitted_at) * 1000);
      if (!lastFetchEpochMS || emittedAtMs > lastFetchEpochMS) {
        inboundMessages.push({
          epochMilliSeconds: emittedAtMs,
          data: event,
        });
      }
    }
    return inboundMessages;
  },
};

export const newInboundMessage = createTrigger({
  auth: frontAuth,
  name: 'newInboundMessage',
  displayName: 'New Inbound Message',
  description: 'Fires when a new message is received in a shared inbox.',
  aiMetadata: {
    description:
      'Fires when a new inbound message is received in Front, such as an incoming email or chat from a contact, optionally scoped to a specific inbox. Represents a message arriving from an external sender and emits the inbound event with its message body, sender, and parent conversation, letting an agent act on newly received customer communications.',
  },
  props,
  sampleData: {
    _links: {
      self: 'https://api.example.com/events/evt_dummy1234',
    },
    id: 'evt_dummy1234',
    type: 'inbound',
    emitted_at: 1700000000,
    conversation: {
      _links: {
        self: 'https://api.example.com/conversations/cnv_dummy5678',
        related: {
          events: 'https://api.example.com/conversations/cnv_dummy5678/events',
          followers:
            'https://api.example.com/conversations/cnv_dummy5678/followers',
          messages:
            'https://api.example.com/conversations/cnv_dummy5678/messages',
          comments:
            'https://api.example.com/conversations/cnv_dummy5678/comments',
          inboxes:
            'https://api.example.com/conversations/cnv_dummy5678/inboxes',
          last_message:
            'https://api.example.com/messages/msg_dummy9012?referer=conversation',
        },
      },
      id: 'cnv_dummy5678',
      subject: 'dummy subject',
      status: 'open',
      status_id: 'sts_dummy0001',
      status_category: 'unresolved',
      ticket_ids: ['tkt_dummy1111'],
      assignee: 'John Doe',
      recipient: {
        _links: {
          related: {
            contact: 'https://api.example.com/contacts/crd_dummy2222',
          },
        },
        name: 'Jane Doe',
        handle: '[email protected]',
        role: 'to',
      },
      tags: ['urgent', 'test'],
      links: ['https://example.com'],
      custom_fields: {
        priority: 'high',
      },
      created_at: 1700001000,
      waiting_since: 1700000500,
      is_private: false,
      scheduled_reminders: [1700002000],
      metadata: {
        source: 'API',
      },
    },
    source: {
      _meta: {
        type: 'inboxes',
      },
      data: [
        {
          _links: {
            self: 'https://api.example.com/inboxes/inb_dummy3333',
            related: {
              channels:
                'https://api.example.com/inboxes/inb_dummy3333/channels',
              conversations:
                'https://api.example.com/inboxes/inb_dummy3333/conversations',
              teammates:
                'https://api.example.com/inboxes/inb_dummy3333/teammates',
              owner: 'https://api.example.com/teams/tim_dummy4444',
            },
          },
          id: 'inb_dummy3333',
          name: 'Dummy Inbox',
          is_private: true,
          is_public: false,
          custom_fields: {},
          address: '[email protected]',
          send_as: '[email protected]',
          type: 'gmail',
        },
      ],
    },
    target: {
      _meta: {
        type: 'message',
      },
      data: {
        _links: {
          self: 'https://api.example.com/messages/msg_dummy9012',
          related: {
            conversation: 'https://api.example.com/conversations/cnv_dummy5678',
            message_seen: 'https://api.example.com/messages/msg_dummy9012/seen',
          },
        },
        id: 'msg_dummy9012',
        message_uid: 'dummyuid1234567890',
        type: 'email',
        is_inbound: true,
        created_at: 1700000100,
        blurb: 'This is a dummy message generated for testing.',
        body: 'This is a dummy message body.<br>',
        text: 'This is a dummy message text.\n',
        error_type: null,
        version: '1.0',
        subject: 'dummy message subject',
        draft_mode: false,
        metadata: {
          importance: 'low',
        },
        author: {
          name: 'Dummy Sender',
          email: '[email protected]',
        },
        recipients: [
          {
            _links: {
              related: {
                contact: 'https://api.example.com/contacts/crd_dummy5555',
              },
            },
            name: 'Recipient One',
            handle: '[email protected]',
            role: 'from',
          },
          {
            _links: {
              related: {
                contact: 'https://api.example.com/contacts/crd_dummy6666',
              },
            },
            name: 'Recipient Two',
            handle: '[email protected]',
            role: 'to',
          },
        ],
        attachments: ['file1.pdf', 'image1.png'],
        signature: 'Best regards, Dummy Sender',
        is_draft: false,
      },
    },
  },
  type: TriggerStrategy.POLLING,
  async test(context) {
    return await pollingHelper.test(polling, context);
  },
  async onEnable(context) {
    await pollingHelper.onEnable(polling, context);
  },
  async onDisable(context) {
    await pollingHelper.onDisable(polling, context);
  },
  async run(context) {
    return await pollingHelper.poll(polling, context);
  },
});