Skip to content

The open alternative to Salesforce, designed for AI.

Add campaign preview, test send, send and suppression tools for AI and MCP (#29072)

neo7734ff64d7758eb
diff --git a/packages/twenty-server/src/modules/emailing/constants/send-campaign-test-tool-name.constant.ts b/packages/twenty-server/src/modules/emailing/constants/send-campaign-test-tool-name.constant.ts
new file mode 100644
index 00000000000..6923c380505
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/constants/send-campaign-test-tool-name.constant.ts
@@ -0,0 +1 @@
+export const SEND_CAMPAIGN_TEST_TOOL_NAME = 'send_campaign_test';
diff --git a/packages/twenty-server/src/modules/emailing/constants/send-campaign-tool-name.constant.ts b/packages/twenty-server/src/modules/emailing/constants/send-campaign-tool-name.constant.ts
new file mode 100644
index 00000000000..f3e74464de4
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/constants/send-campaign-tool-name.constant.ts
@@ -0,0 +1 @@
+export const SEND_CAMPAIGN_TOOL_NAME = 'send_campaign';
diff --git a/packages/twenty-server/src/modules/emailing/emailing.module.ts b/packages/twenty-server/src/modules/emailing/emailing.module.ts
index bc024cfa449..c868f05017a 100644
--- a/packages/twenty-server/src/modules/emailing/emailing.module.ts
+++ b/packages/twenty-server/src/modules/emailing/emailing.module.ts
@@ -63,7 +63,11 @@ import { MessageListDuplicationService } from 'src/modules/emailing/services/mes
import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
import { UnsubscribeTopicService } from 'src/modules/emailing/services/unsubscribe-topic.service';
import { UnsubscribePreferencesService } from 'src/modules/emailing/services/unsubscribe-preferences.service';
+import { FindCampaignSuppressionsTool } from 'src/modules/emailing/tools/find-campaign-suppressions.tool';
+import { PreviewCampaignSendTool } from 'src/modules/emailing/tools/preview-campaign-send.tool';
import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool';
+import { SendCampaignTestTool } from 'src/modules/emailing/tools/send-campaign-test.tool';
+import { SendCampaignTool } from 'src/modules/emailing/tools/send-campaign.tool';
@Module({
imports: [
@@ -114,6 +118,10 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
UnsubscribeTopicService,
EmailingDomainSenderService,
SaveCampaignTool,
+ PreviewCampaignSendTool,
+ SendCampaignTestTool,
+ SendCampaignTool,
+ FindCampaignSuppressionsTool,
EmailingSendResolver,
MessageListDuplicationService,
AddPeopleToMessageListService,
diff --git a/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts b/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts
index 22216ac5575..15b55e0b84b 100644
--- a/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts
+++ b/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts
@@ -1,12 +1,10 @@
-import { Logger, UseFilters, UseGuards, UsePipes } from '@nestjs/common';
+import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';
import { Args, Context, Mutation, Query } from '@nestjs/graphql';
import { PermissionFlagType } from 'twenty-shared/constants';
import { FeatureFlagKey } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
-import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { CampaignAudiencePreviewDTO } from 'src/engine/core-modules/emailing-domain/dtos/campaign-audience-preview.dto';
import { CancelMessageCampaignInput } from 'src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign.input';
import { CancelMessageCampaignOutputDTO } from 'src/engine/core-modules/emailing-domain/dtos/cancel-message-campaign-output.dto';
@@ -19,15 +17,10 @@ import { SendEmailViaDomainOutputDTO } from 'src/engine/core-modules/emailing-do
import { SendMessageCampaignInput } from 'src/engine/core-modules/emailing-domain/dtos/send-message-campaign.input';
import { SendMessageCampaignTestInput } from 'src/engine/core-modules/emailing-domain/dtos/send-message-campaign-test.input';
import { SendMessageCampaignOutputDTO } from 'src/engine/core-modules/emailing-domain/dtos/send-message-campaign-output.dto';
-import {
- EmailingDomainException,
- EmailingDomainExceptionCode,
-} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
import { type I18nContext } from 'src/engine/core-modules/i18n/types/i18n-context.type';
import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
-import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
@@ -35,13 +28,10 @@ import { FeatureFlagGuard } from 'src/engine/guards/feature-flag.guard';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
import { ThrottlerGraphqlApiExceptionFilter } from 'src/engine/core-modules/throttler/filters/throttler-graphql-api-exception.filter';
-import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
import { MessageCampaignAudienceService } from 'src/modules/emailing/services/message-campaign-audience.service';
import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
import { MessageCampaignScheduleService } from 'src/modules/emailing/services/message-campaign-schedule.service';
import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
-import { countDeliveredRecipients } from 'src/engine/core-modules/emailing-domain/utils/count-delivered-recipients.util';
-import { type EmailingDomainSendEmailResult } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-send-email-result.type';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
@UseGuards(
@@ -68,16 +58,12 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt
@UsePipes(ResolverValidationPipe)
@MetadataResolver()
export class EmailingSendResolver {
- private readonly logger = new Logger(EmailingSendResolver.name);
-
constructor(
private readonly messageCampaignService: MessageCampaignService,
private readonly messageCampaignScheduleService: MessageCampaignScheduleService,
private readonly messageCampaignAudienceService: MessageCampaignAudienceService,
private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
private readonly emailGroupAccessService: EmailGroupAccessService,
- private readonly emailBillingService: EmailBillingService,
- private readonly billingService: BillingService,
) {}
@Mutation(() => SendMessageCampaignOutputDTO)
@@ -89,35 +75,11 @@ export class EmailingSendResolver {
): Promise<SendMessageCampaignOutputDTO> {
this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
- const isPayingCustomer = await this.billingService.isPayingCustomer(
- currentWorkspace.id,
- );
-
- if (!isPayingCustomer) {
- throw new EmailingDomainException(
- `Campaign ${input.campaignId} cannot be sent: workspace ${currentWorkspace.id} is not on a paid plan`,
- EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_REQUIRES_PAID_PLAN,
- );
- }
-
- await this.emailBillingService.validateEmailSendOrThrow({
- workspaceId: currentWorkspace.id,
- spenders: { userWorkspaceId },
- });
-
- if (isDefined(input.scheduledAt)) {
- return this.messageCampaignScheduleService.schedule({
- workspaceId: currentWorkspace.id,
- userWorkspaceId,
- campaignId: input.campaignId,
- scheduledAt: input.scheduledAt,
- });
- }
-
- return this.messageCampaignService.send({
+ return this.messageCampaignScheduleService.sendNowOrScheduleOrThrow({
workspaceId: currentWorkspace.id,
userWorkspaceId,
campaignId: input.campaignId,
+ scheduledAt: input.scheduledAt,
});
}
@@ -146,13 +108,10 @@ export class EmailingSendResolver {
userWorkspaceId: string | undefined,
): Promise<SendEmailViaDomainOutputDTO> {
this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
- await this.emailBillingService.validateEmailSendOrThrow({
- workspaceId: currentWorkspace.id,
- spenders: { userWorkspaceId },
- });
const result = await this.messageCampaignService.sendTest({
workspaceId: currentWorkspace.id,
+ spenders: { userWorkspaceId },
toAddress: input.toAddress,
unsubscribeTopicId: input.unsubscribeTopicId,
subject: input.subject,
@@ -160,12 +119,6 @@ export class EmailingSendResolver {
fromAddress: input.fromAddress,
});
- await this.billAcceptedSend({
- workspaceId: currentWorkspace.id,
- spenders: { userWorkspaceId },
- result,
- });
-
return { messageId: result.messageId };
}
@@ -217,30 +170,4 @@ export class EmailingSendResolver {
locale: context.req.locale,
});
}
-
- // The provider has already accepted the mail, so surfacing a billing failure
- // would invite a retry that sends it a second time.
- private async billAcceptedSend({
- workspaceId,
- spenders,
- result,
- }: {
- workspaceId: string;
- spenders: UsageSpenders;
- result: EmailingDomainSendEmailResult;
- }): Promise<void> {
- await this.emailBillingService
- .billSentEmails({
- workspaceId,
- spenders,
- sentEmailCount: countDeliveredRecipients(result.deliveredRecipients),
- })
- .catch((error) => {
- this.logger.error(
- `Workspace ${workspaceId} sent email ${result.messageId} but failed to bill it, so this send is unbilled: ${
- error instanceof Error ? error.message : String(error)
- }`,
- );
- });
- }
}
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-schedule.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-schedule.service.ts
index c3c08407509..eb5d0700fa7 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-schedule.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-schedule.service.ts
@@ -4,6 +4,7 @@ import { MessageCampaignStatus } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { withWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
+import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { CAMPAIGN_SEND_RETRY_BACKOFF } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-backoff.constant';
import { CAMPAIGN_SEND_RETRY_LIMIT } from 'src/engine/core-modules/emailing-domain/constants/campaign-send-retry-limit.constant';
import {
@@ -16,6 +17,7 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { SEND_SCHEDULED_CAMPAIGN_JOB } from 'src/modules/emailing/constants/send-scheduled-campaign-job.constant';
+import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';
import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';
import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
import { type SendCampaignResult } from 'src/modules/emailing/types/send-campaign-result.type';
@@ -29,18 +31,68 @@ export class MessageCampaignScheduleService {
private readonly campaignMessageQueueService: MessageQueueService,
private readonly messageCampaignLifecycleService: MessageCampaignLifecycleService,
private readonly messageCampaignService: MessageCampaignService,
+ private readonly billingService: BillingService,
+ private readonly emailBillingService: EmailBillingService,
) {}
+ async sendNowOrScheduleOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ scheduledAt,
+ expectedRecipientCount,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ campaignId: string;
+ scheduledAt?: Date;
+ expectedRecipientCount?: number;
+ }): Promise<SendCampaignResult> {
+ const isPayingCustomer =
+ await this.billingService.isPayingCustomer(workspaceId);
+
+ if (!isPayingCustomer) {
+ throw new EmailingDomainException(
+ `Campaign ${campaignId} cannot be sent: workspace ${workspaceId} is not on a paid plan`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_REQUIRES_PAID_PLAN,
+ );
+ }
+
+ await this.emailBillingService.validateEmailSendOrThrow({
+ workspaceId,
+ spenders: { userWorkspaceId },
+ });
+
+ if (isDefined(scheduledAt)) {
+ return this.schedule({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ scheduledAt,
+ expectedRecipientCount,
+ });
+ }
+
+ return this.messageCampaignService.send({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ expectedRecipientCount,
+ });
+ }
+
async schedule({
workspaceId,
userWorkspaceId,
campaignId,
scheduledAt,
+ expectedRecipientCount,
}: {
workspaceId: string;
userWorkspaceId: string;
campaignId: string;
scheduledAt: Date;
+ expectedRecipientCount?: number;
}): Promise<SendCampaignResult> {
const {
roleId,
@@ -53,6 +105,7 @@ export class MessageCampaignScheduleService {
userWorkspaceId,
campaignId,
requestedScheduledAt: scheduledAt,
+ expectedRecipientCount,
});
const scheduled =
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
index aeb1469de1e..2cbc3bdd3c8 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
import { isNonEmptyString } from '@sniptt/guards';
@@ -20,11 +20,13 @@ import {
EmailingDomainExceptionCode,
} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';
import { type MaterializeCampaignJobData } from 'src/engine/core-modules/emailing-domain/types/materialize-campaign-job-data.type';
+import { countDeliveredRecipients } from 'src/engine/core-modules/emailing-domain/utils/count-delivered-recipients.util';
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { MessageChannelMetadataService } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.service';
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
@@ -52,6 +54,8 @@ const TEST_SEND_THROTTLE = { maxRequests: 3, windowMs: 24 * 60 * 60 * 1000 };
@Injectable()
export class MessageCampaignService {
+ private readonly logger = new Logger(MessageCampaignService.name);
+
constructor(
@InjectWorkspaceScopedRepository(EmailingDomainEntity)
private readonly emailingDomainRepository: WorkspaceScopedRepository<EmailingDomainEntity>,
@@ -73,15 +77,18 @@ export class MessageCampaignService {
workspaceId,
userWorkspaceId,
campaignId,
+ expectedRecipientCount,
}: {
workspaceId: string;
userWorkspaceId: string;
campaignId: string;
+ expectedRecipientCount?: number;
}): Promise<SendCampaignResult> {
const prepared = await this.prepareCampaignSendOrThrow({
workspaceId,
userWorkspaceId,
campaignId,
+ expectedRecipientCount,
});
return this.claimAndMaterializeOrThrow({
@@ -167,11 +174,13 @@ export class MessageCampaignService {
userWorkspaceId,
campaignId,
requestedScheduledAt,
+ expectedRecipientCount,
}: {
workspaceId: string;
userWorkspaceId: string;
campaignId: string;
requestedScheduledAt?: Date;
+ expectedRecipientCount?: number;
}): Promise<PreparedCampaignSend> {
const roleId = await this.userRoleService.getRoleIdForUserWorkspace({
workspaceId,
@@ -193,6 +202,16 @@ export class MessageCampaignService {
requestedScheduledAt,
});
+ if (
+ isDefined(expectedRecipientCount) &&
+ sendableRecipients.length !== expectedRecipientCount
+ ) {
+ throw new EmailingDomainException(
+ `Campaign ${campaignId} would now reach ${sendableRecipients.length} recipient(s), not the ${expectedRecipientCount} that were approved`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE,
+ );
+ }
+
const messageChannel =
await this.messageChannelMetadataService.getOrCreateEmailGroupChannel({
fromAddress,
@@ -361,8 +380,64 @@ export class MessageCampaignService {
};
}
+ async sendCampaignTest({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ toAddress,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ campaignId: string;
+ toAddress: string;
+ }): Promise<EmailingDomainSendEmailResult> {
+ const roleId = await this.userRoleService.getRoleIdForUserWorkspace({
+ workspaceId,
+ userWorkspaceId,
+ });
+
+ const campaign = await this.workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ this.workspaceOrmManager
+ .getRepository(
+ MessageCampaignWorkspaceEntity,
+ buildEmailingRolePermissionConfig(roleId),
+ )
+ .findOne({ where: { id: campaignId } }),
+ );
+
+ if (!isDefined(campaign)) {
+ throw new EmailingDomainException(
+ `Campaign ${campaignId} not found`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_FOUND,
+ );
+ }
+
+ if (
+ !isNonEmptyString(campaign.fromAddress?.primaryEmail) ||
+ !isNonEmptyString(campaign.subject) ||
+ !isNonEmptyString(campaign.bodyTemplate)
+ ) {
+ throw new EmailingDomainException(
+ `Campaign ${campaignId} needs a from address, a subject and a body before a test send`,
+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE,
+ );
+ }
+
+ return this.sendTest({
+ workspaceId,
+ spenders: { userWorkspaceId },
+ toAddress,
+ subject: campaign.subject,
+ html: campaign.bodyTemplate,
+ fromAddress: campaign.fromAddress.primaryEmail,
+ unsubscribeTopicId: campaign.unsubscribeTopicId ?? undefined,
+ });
+ }
+
async sendTest({
workspaceId,
+ spenders,
toAddress,
subject,
html,
@@ -370,12 +445,18 @@ export class MessageCampaignService {
unsubscribeTopicId,
}: {
workspaceId: string;
+ spenders: UsageSpenders;
toAddress: string;
subject: string;
html: string;
fromAddress: string;
unsubscribeTopicId?: string;
}): Promise<EmailingDomainSendEmailResult> {
+ await this.emailBillingService.validateEmailSendOrThrow({
+ workspaceId,
+ spenders,
+ });
+
const emailingDomain = await this.findSendReadyEmailingDomainOrThrow({
workspaceId,
fromAddress,
@@ -407,7 +488,7 @@ export class MessageCampaignService {
TEST_SEND_THROTTLE.windowMs,
);
- return this.emailingDomainSenderService.sendEmail(
+ const result = await this.emailingDomainSenderService.sendEmail(
workspaceId,
emailingDomain.id,
{
@@ -420,6 +501,38 @@ export class MessageCampaignService {
unsubscribeTopicId,
},
);
+
+ await this.billAcceptedSend({ workspaceId, spenders, result });
+
+ return result;
+ }
+
+ // The provider already accepted the mail, so a billing failure must not invite a resend
+ private async billAcceptedSend({
+ workspaceId,
+ spenders,
+ result,
+ }: {
+ workspaceId: string;
+ spenders: UsageSpenders;
+ result: Pick<
+ EmailingDomainSendEmailResult,
+ 'messageId' | 'deliveredRecipients'
+ >;
+ }): Promise<void> {
+ await this.emailBillingService
+ .billSentEmails({
+ workspaceId,
+ spenders,
+ sentEmailCount: countDeliveredRecipients(result.deliveredRecipients),
+ })
+ .catch((error) => {
+ this.logger.error(
+ `Workspace ${workspaceId} sent email ${result.messageId} but failed to bill it, so this send is unbilled: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
}
private async findSendReadyEmailingDomainOrThrow({
diff --git a/packages/twenty-server/src/modules/emailing/tools/find-campaign-suppressions.tool.ts b/packages/twenty-server/src/modules/emailing/tools/find-campaign-suppressions.tool.ts
new file mode 100644
index 00000000000..bd27fef9133
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/tools/find-campaign-suppressions.tool.ts
@@ -0,0 +1,85 @@
+import { ToolCategory } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { z } from 'zod';
+
+import { MessageSuppressionReason } from 'src/engine/core-modules/emailing-domain/types/message-suppression-reason.type';
+import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';
+import { DefineTool } from 'src/engine/core-modules/tool-provider/decorators/define-tool.decorator';
+import { BaseTool } from 'src/engine/core-modules/tool-provider/interfaces/base-tool.interface';
+import { type ToolExecuteArgs } from 'src/engine/core-modules/tool-provider/types/tool-execute-args.type';
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';
+
+const findCampaignSuppressionsInputSchema = z.object({
+ searchTerm: z
+ .string()
+ .optional()
+ .describe('Part of an email address to look for.'),
+ reason: z
+ .enum(MessageSuppressionReason)
+ .optional()
+ .describe(
+ 'BOUNCE and COMPLAINT block every campaign, UNSUBSCRIBE blocks all campaigns or one topic, TRACKING only turns off open and click tracking.',
+ ),
+ unsubscribeTopicId: z
+ .uuid()
+ .optional()
+ .describe('Only return unsubscribes from this topic.'),
+ limit: z.number().int().min(1).max(100).default(30),
+ offset: z.number().int().min(0).default(0),
+});
+
+@DefineTool({
+ name: 'find_campaign_suppressions',
+ category: ToolCategory.ACTION,
+ requiredPermissionFlags: [PermissionFlagType.WORKSPACE],
+ requiredFeatureFlags: [FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED],
+ description:
+ 'List the email addresses that campaigns skip: bounces, spam complaints, unsubscribes (global or per topic) and tracking opt-outs, newest first. ' +
+ 'Use it to explain why someone is not receiving campaigns. Read only: suppressions can only be removed from the settings page.',
+})
+export class FindCampaignSuppressionsTool extends BaseTool<
+ typeof findCampaignSuppressionsInputSchema
+> {
+ readonly inputSchema = findCampaignSuppressionsInputSchema;
+
+ constructor(
+ private readonly messageSuppressionService: MessageSuppressionService,
+ private readonly emailGroupAccessService: EmailGroupAccessService,
+ ) {
+ super();
+ }
+
+ async execute({
+ input,
+ context: { workspaceId },
+ }: ToolExecuteArgs<
+ typeof findCampaignSuppressionsInputSchema
+ >): Promise<ToolOutput> {
+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
+
+ const { records, totalCount } =
+ await this.messageSuppressionService.findSuppressions({
+ workspaceId,
+ ...input,
+ });
+
+ return {
+ success: true,
+ message: `Found ${totalCount} suppression(s)`,
+ result: {
+ totalCount,
+ suppressions: records.map(
+ ({ id, emailAddress, reason, unsubscribeTopicId, createdAt }) => ({
+ id,
+ emailAddress,
+ reason,
+ unsubscribeTopicId,
+ createdAt,
+ }),
+ ),
+ },
+ };
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/tools/preview-campaign-send.tool.ts b/packages/twenty-server/src/modules/emailing/tools/preview-campaign-send.tool.ts
new file mode 100644
index 00000000000..7f726a258e8
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/tools/preview-campaign-send.tool.ts
@@ -0,0 +1,81 @@
+import { ToolCategory } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';
+import { DefineTool } from 'src/engine/core-modules/tool-provider/decorators/define-tool.decorator';
+import { BaseTool } from 'src/engine/core-modules/tool-provider/interfaces/base-tool.interface';
+import { type ToolExecuteArgs } from 'src/engine/core-modules/tool-provider/types/tool-execute-args.type';
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
+
+const previewCampaignSendInputSchema = z.object({
+ campaignId: z.uuid().describe('The UUID of the messageCampaign record.'),
+ scheduledAt: z
+ .string()
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'ISO 8601 date-time to check a scheduled send for. Omit to check an immediate send.',
+ ),
+});
+
+@DefineTool({
+ name: 'preview_campaign_send',
+ category: ToolCategory.ACTION,
+ requiredPermissionFlags: [PermissionFlagType.WORKSPACE],
+ requiredFeatureFlags: [FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED],
+ description:
+ 'Check whether an email campaign can be sent, without sending anything. ' +
+ 'Returns the audience: list members, how many are sendable, and how many are skipped and why (no email, duplicate email, suppressed, globally or topic unsubscribed, tracking refused). ' +
+ 'Also returns blockers that would stop the send, such as an unverified sending domain, a missing subject or no sendable recipient. ' +
+ 'Call this before send_campaign and show the person the sendable count.',
+})
+export class PreviewCampaignSendTool extends BaseTool<
+ typeof previewCampaignSendInputSchema
+> {
+ readonly inputSchema = previewCampaignSendInputSchema;
+
+ constructor(
+ private readonly messageCampaignService: MessageCampaignService,
+ private readonly emailGroupAccessService: EmailGroupAccessService,
+ ) {
+ super();
+ }
+
+ async execute({
+ input: { campaignId, scheduledAt },
+ context: { workspaceId, userWorkspaceId, locale },
+ }: ToolExecuteArgs<
+ typeof previewCampaignSendInputSchema
+ >): Promise<ToolOutput> {
+ if (!isDefined(userWorkspaceId)) {
+ return {
+ success: false,
+ message: 'Failed to preview campaign send',
+ error: 'This tool can only run on behalf of a workspace member',
+ };
+ }
+
+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
+
+ const preview = await this.messageCampaignService.previewSend({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ scheduledAt: isDefined(scheduledAt) ? new Date(scheduledAt) : undefined,
+ locale,
+ });
+
+ return {
+ success: true,
+ message:
+ preview.blockers.length > 0
+ ? `Campaign cannot be sent: ${preview.blockers.map(({ message }) => message).join(' ')}`
+ : `Campaign can be sent to ${preview.audience?.sendable ?? 0} recipient(s)`,
+ result: preview,
+ };
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/tools/send-campaign-test.tool.ts b/packages/twenty-server/src/modules/emailing/tools/send-campaign-test.tool.ts
new file mode 100644
index 00000000000..7698fa2189c
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/tools/send-campaign-test.tool.ts
@@ -0,0 +1,71 @@
+import { ToolCategory } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';
+import { DefineTool } from 'src/engine/core-modules/tool-provider/decorators/define-tool.decorator';
+import { BaseTool } from 'src/engine/core-modules/tool-provider/interfaces/base-tool.interface';
+import { type ToolExecuteArgs } from 'src/engine/core-modules/tool-provider/types/tool-execute-args.type';
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { SEND_CAMPAIGN_TEST_TOOL_NAME } from 'src/modules/emailing/constants/send-campaign-test-tool-name.constant';
+import { MessageCampaignService } from 'src/modules/emailing/services/message-campaign.service';
+
+const sendCampaignTestInputSchema = z.object({
+ campaignId: z.uuid().describe('The UUID of the messageCampaign record.'),
+ toAddress: z
+ .email()
+ .describe('The single address that receives the test email.'),
+});
+
+@DefineTool({
+ name: SEND_CAMPAIGN_TEST_TOOL_NAME,
+ category: ToolCategory.ACTION,
+ requiredPermissionFlags: [PermissionFlagType.WORKSPACE],
+ requiredFeatureFlags: [FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED],
+ description:
+ 'Send one test email of a saved campaign to a single address, from the campaign sender. ' +
+ 'Variables render with empty values or their fallbacks, since the test is not tied to a person. ' +
+ 'The campaign status and statistics are not changed. Limited to a few test sends per workspace per day.',
+})
+export class SendCampaignTestTool extends BaseTool<
+ typeof sendCampaignTestInputSchema
+> {
+ readonly inputSchema = sendCampaignTestInputSchema;
+
+ constructor(
+ private readonly messageCampaignService: MessageCampaignService,
+ private readonly emailGroupAccessService: EmailGroupAccessService,
+ ) {
+ super();
+ }
+
+ async execute({
+ input: { campaignId, toAddress },
+ context: { workspaceId, userWorkspaceId },
+ }: ToolExecuteArgs<typeof sendCampaignTestInputSchema>): Promise<ToolOutput> {
+ if (!isDefined(userWorkspaceId)) {
+ return {
+ success: false,
+ message: 'Failed to send campaign test',
+ error: 'This tool can only run on behalf of a workspace member',
+ };
+ }
+
+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
+
+ const { messageId } = await this.messageCampaignService.sendCampaignTest({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ toAddress,
+ });
+
+ return {
+ success: true,
+ message: `Test email sent to ${toAddress}`,
+ result: { messageId },
+ };
+ }
+}
diff --git a/packages/twenty-server/src/modules/emailing/tools/send-campaign.tool.ts b/packages/twenty-server/src/modules/emailing/tools/send-campaign.tool.ts
new file mode 100644
index 00000000000..1871fde9dd7
--- /dev/null
+++ b/packages/twenty-server/src/modules/emailing/tools/send-campaign.tool.ts
@@ -0,0 +1,95 @@
+import { ToolCategory } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { FeatureFlagKey, MessageCampaignStatus } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';
+import { DefineTool } from 'src/engine/core-modules/tool-provider/decorators/define-tool.decorator';
+import { BaseTool } from 'src/engine/core-modules/tool-provider/interfaces/base-tool.interface';
+import { type ToolExecuteArgs } from 'src/engine/core-modules/tool-provider/types/tool-execute-args.type';
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { SEND_CAMPAIGN_TOOL_NAME } from 'src/modules/emailing/constants/send-campaign-tool-name.constant';
+import { MessageCampaignScheduleService } from 'src/modules/emailing/services/message-campaign-schedule.service';
+
+const sendCampaignInputSchema = z.object({
+ campaignId: z.uuid().describe('The UUID of the messageCampaign record.'),
+ scheduledAt: z
+ .string()
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'ISO 8601 date-time in the future to schedule the send for. Omit to send now.',
+ ),
+ expectedRecipientCount: z
+ .number()
+ .int()
+ .min(1)
+ .describe(
+ 'The sendable count from preview_campaign_send that the person approved. The send is refused if the audience no longer matches it.',
+ ),
+});
+
+@DefineTool({
+ name: SEND_CAMPAIGN_TOOL_NAME,
+ category: ToolCategory.ACTION,
+ requiredPermissionFlags: [PermissionFlagType.WORKSPACE],
+ requiredFeatureFlags: [FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED],
+ description:
+ 'Send an email campaign to its list now, or schedule it. This emails real people and cannot be undone once sending starts. ' +
+ 'Only call it after the person explicitly asked to send this campaign and approved the recipient count from preview_campaign_send. ' +
+ 'Unsubscribed and suppressed recipients are always skipped. A scheduled send goes to the list as it is at send time. ' +
+ 'Returns the campaign ID and its status; read the messageCampaign record to follow progress and statistics.',
+})
+export class SendCampaignTool extends BaseTool<typeof sendCampaignInputSchema> {
+ readonly inputSchema = sendCampaignInputSchema;
+
+ constructor(
+ private readonly messageCampaignScheduleService: MessageCampaignScheduleService,
+ private readonly emailGroupAccessService: EmailGroupAccessService,
+ ) {
+ super();
+ }
+
+ async execute({
+ input: { campaignId, scheduledAt, expectedRecipientCount },
+ context: { workspaceId, userWorkspaceId },
+ }: ToolExecuteArgs<typeof sendCampaignInputSchema>): Promise<ToolOutput> {
+ if (!isDefined(userWorkspaceId)) {
+ return {
+ success: false,
+ message: 'Failed to send campaign',
+ error: 'This tool can only run on behalf of a workspace member',
+ };
+ }
+
+ this.emailGroupAccessService.validateEmailGroupAccessOrThrow();
+
+ const scheduledAtDate = isDefined(scheduledAt)
+ ? new Date(scheduledAt)
+ : undefined;
+
+ const { queuedCount } =
+ await this.messageCampaignScheduleService.sendNowOrScheduleOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ campaignId,
+ scheduledAt: scheduledAtDate,
+ expectedRecipientCount,
+ });
+
+ return {
+ success: true,
+ message: isDefined(scheduledAtDate)
+ ? `Campaign scheduled for ${scheduledAtDate.toISOString()} to ${queuedCount} recipient(s)`
+ : `Campaign is sending to ${queuedCount} recipient(s)`,
+ result: {
+ campaignId,
+ status: isDefined(scheduledAtDate)
+ ? MessageCampaignStatus.SCHEDULED
+ : MessageCampaignStatus.SENDING,
+ queuedCount,
+ },
+ };
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant.ts
index 1c5766d1efb..d980d70cbf4 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/application-bound-agent-excluded-tool-names.constant.ts
@@ -1,10 +1,18 @@
import { type ActionToolId } from 'src/engine/core-modules/tool-provider/constants/action-tool-label.constant';
+import { SEND_CAMPAIGN_TEST_TOOL_NAME } from 'src/modules/emailing/constants/send-campaign-test-tool-name.constant';
+import { SEND_CAMPAIGN_TOOL_NAME } from 'src/modules/emailing/constants/send-campaign-tool-name.constant';
export const APPLICATION_BOUND_AGENT_EXCLUDED_TOOL_NAMES = [
'code_interpreter',
'save_campaign',
+ SEND_CAMPAIGN_TOOL_NAME,
+ SEND_CAMPAIGN_TEST_TOOL_NAME,
'send_email',
'draft_email',
'find_connected_accounts',
'create_calendar_event',
-] as const satisfies readonly ActionToolId[];
+] as const satisfies readonly (
+ | ActionToolId
+ | typeof SEND_CAMPAIGN_TOOL_NAME
+ | typeof SEND_CAMPAIGN_TEST_TOOL_NAME
+)[];
diff --git a/packages/twenty-server/test/integration/emailing/campaign-mcp-tools.integration-spec.ts b/packages/twenty-server/test/integration/emailing/campaign-mcp-tools.integration-spec.ts
new file mode 100644
index 00000000000..046a7499c73
--- /dev/null
+++ b/packages/twenty-server/test/integration/emailing/campaign-mcp-tools.integration-spec.ts
@@ -0,0 +1,206 @@
+import gql from 'graphql-tag';
+import { executeToolThroughMcp } from 'test/integration/ai/utils/execute-tool-through-mcp.util';
+import { createOneOperation } from 'test/integration/graphql/utils/create-one-operation.util';
+import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';
+import { findOneOperation } from 'test/integration/graphql/utils/find-one-operation.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { EMAIL_DOCUMENT_SCHEMA_VERSION } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+
+import { type FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const SENDABLE_BODY_TEMPLATE = JSON.stringify({
+ type: 'doc',
+ attrs: { schemaVersion: EMAIL_DOCUMENT_SCHEMA_VERSION },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Hello' }] }],
+});
+
+const CREATE_MESSAGE_SUPPRESSION = gql`
+ mutation CreateMessageSuppression($input: CreateMessageSuppressionInput!) {
+ createMessageSuppression(input: $input) {
+ id
+ }
+ }
+`;
+
+const DELETE_MESSAGE_SUPPRESSION = gql`
+ mutation DeleteMessageSuppression($id: UUID!) {
+ deleteMessageSuppression(id: $id)
+ }
+`;
+
+const createRecord = async (
+ objectMetadataSingularName: string,
+ input: Record<string, unknown>,
+) => {
+ const { errors } = await createOneOperation({
+ objectMetadataSingularName,
+ input,
+ });
+
+ expect(errors).toBeUndefined();
+};
+
+const destroyRecord = (objectMetadataSingularName: string, recordId: string) =>
+ makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName,
+ gqlFields: 'id',
+ recordId,
+ }),
+ );
+
+describe('Campaign lifecycle tools through MCP (integration)', () => {
+ const domain = `${v4()}.example.com`;
+ const listId = v4();
+ const personId = v4();
+ const memberId = v4();
+ const campaignId = v4();
+ const suppressedEmailAddress = `mcp-suppressed-${v4()}@example.com`;
+ let suppressionId: string;
+ let wasMessageCampaignEnabled: boolean;
+
+ const readCampaignStatus = async (): Promise<string> => {
+ const { data } = await findOneOperation({
+ objectMetadataSingularName: 'messageCampaign',
+ gqlFields: 'status',
+ filter: { id: { eq: campaignId } },
+ });
+
+ return data.findResponse.status;
+ };
+
+ beforeAll(async () => {
+ wasMessageCampaignEnabled =
+ await getAppProviderByClassName<FeatureFlagService>(
+ 'FeatureFlagService',
+ ).isFeatureEnabled(
+ FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED,
+ SEED_APPLE_WORKSPACE_ID,
+ );
+
+ await updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED,
+ value: true,
+ expectToFail: false,
+ });
+
+ await testDataSource.query(
+ `INSERT INTO "core"."emailingDomain"
+ ("workspaceId", "domain", "status", "verifiedAt", "unsubscribeHostname", "unsubscribeHostnameStatus")
+ VALUES ($1, $2, 'VERIFIED', now(), $3, 'ACTIVE')`,
+ [SEED_APPLE_WORKSPACE_ID, domain, `unsubscribe.${domain}`],
+ );
+
+ await createRecord('messageList', { id: listId, name: 'MCP tools list' });
+ await createRecord('person', {
+ id: personId,
+ emails: { primaryEmail: `mcp-tools-${personId}@example.com` },
+ });
+ await createRecord('messageListMember', { id: memberId, listId, personId });
+ await createRecord('messageCampaign', {
+ id: campaignId,
+ name: 'MCP tools campaign',
+ subject: 'Monthly newsletter',
+ bodyTemplate: SENDABLE_BODY_TEMPLATE,
+ fromAddress: { primaryEmail: `campaigns@${domain}` },
+ listId,
+ });
+
+ const suppressionResponse = await makeMetadataApiRequest({
+ query: CREATE_MESSAGE_SUPPRESSION,
+ variables: { input: { emailAddress: suppressedEmailAddress } },
+ });
+
+ expect(suppressionResponse.body.errors).toBeUndefined();
+ suppressionId = suppressionResponse.body.data.createMessageSuppression.id;
+ });
+
+ afterAll(async () => {
+ await makeMetadataApiRequest({
+ query: DELETE_MESSAGE_SUPPRESSION,
+ variables: { id: suppressionId },
+ });
+ await destroyRecord('messageCampaign', campaignId);
+ await destroyRecord('messageListMember', memberId);
+ await destroyRecord('person', personId);
+ await destroyRecord('messageList', listId);
+ await testDataSource.query(
+ `DELETE FROM "core"."emailingDomain" WHERE "domain" = $1`,
+ [domain],
+ );
+
+ await updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED,
+ value: wasMessageCampaignEnabled,
+ expectToFail: false,
+ });
+ });
+
+ it('should preview the audience of a ready campaign', async () => {
+ const output = await executeToolThroughMcp<{
+ audience: { totalMembers: number; sendable: number };
+ blockers: unknown[];
+ }>({
+ toolName: 'preview_campaign_send',
+ toolArguments: { campaignId },
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ expect(output.success).toBe(true);
+ expect(output.result).toMatchObject({
+ audience: { totalMembers: 1, sendable: 1 },
+ blockers: [],
+ });
+ });
+
+ it('should refuse to send when the approved recipient count no longer matches', async () => {
+ const output = await executeToolThroughMcp({
+ toolName: 'send_campaign',
+ toolArguments: { campaignId, expectedRecipientCount: 2 },
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ expect(output.success).toBe(false);
+ expect(output.error).toContain('would now reach 1 recipient(s)');
+ expect(await readCampaignStatus()).toBe('DRAFT');
+ });
+
+ it('should find a suppressed address', async () => {
+ const output = await executeToolThroughMcp<{
+ totalCount: number;
+ suppressions: { emailAddress: string; reason: string }[];
+ }>({
+ toolName: 'find_campaign_suppressions',
+ toolArguments: { searchTerm: suppressedEmailAddress },
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ expect(output.success).toBe(true);
+ expect(output.result?.suppressions).toEqual([
+ expect.objectContaining({
+ emailAddress: suppressedEmailAddress,
+ reason: 'UNSUBSCRIBE',
+ }),
+ ]);
+ });
+
+ it('should not let a member without the workspace settings permission send', async () => {
+ const output = await executeToolThroughMcp({
+ toolName: 'send_campaign',
+ toolArguments: { campaignId, expectedRecipientCount: 2 },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(output).toMatchObject({
+ success: false,
+ message: 'Tool "send_campaign" not found',
+ });
+ expect(await readCampaignStatus()).toBe('DRAFT');
+ });
+});