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

feat(rabbitmq): publish, inspect and discover queues and exchanges from flows and AI agents (#16927)

Odai Ahmadf072e2ccf2bb
diff --git a/bun.lock b/bun.lock
index 4545f085a0f..cee12041f68 100644
--- a/bun.lock
+++ b/bun.lock
@@ -7724,18 +7724,19 @@
},
"packages/pieces/community/rabbitmq": {
"name": "@activepieces/piece-rabbitmq",
- "version": "0.1.8",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"amqplib": "0.10.7",
- "dayjs": "1.11.9",
+ "undici": "7.29.1",
},
"devDependencies": {
"@types/amqplib": "0.10.7",
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/raia-ai": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 27221fa8dcf..04ce81f7687 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,24 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### RabbitMQ 0.2.0: the Send Message actions are no longer AI agent tools, and their output changes
+
+**Send Message to Queue** and **Send Message to Exchange** (shown before as `sendMessageToQueue` and `sendMessageToExchange`) are now shown only in the flow builder. AI agents and MCP clients get **Publish to Queue** and **Publish to Exchange** instead.
+
+After you upgrade a Send Message step:
+
+- The step returns an object (`success`, `queue`, `exchange`, `routingKey`, `sizeBytes`, `persistent`, `contentType`) instead of `true`.
+- Messages are persistent by default and carry a content type (`application/json`, or `text/plain` for text).
+- The username, password and virtual host in the connection are now URL-encoded for you. If you encoded them by hand to work around the old behavior, enter them as plain text.
+
+#### What you need to do
+
+- Agents that used the Send Message actions as tools: switch to Publish to Queue or Publish to Exchange.
+- If a later step checked the old `true` output, map `success` instead.
+- If your connection holds a hand-encoded password or virtual host (for example `%2F`), edit it to the plain value.
+
+Steps keep running on the version they were built with until you upgrade them.
+
#### Workable 0.3.0: Move Candidate is no longer an agent tool, and some step outputs change
**Move Candidate** is now shown only in the flow builder. AI agents and MCP clients get **Move Candidate (by IDs)** instead, which takes the candidate ID and the target stage as text.
diff --git a/packages/pieces/community/rabbitmq/package.json b/packages/pieces/community/rabbitmq/package.json
index faf88e395ef..e4b9d7fdf04 100644
--- a/packages/pieces/community/rabbitmq/package.json
+++ b/packages/pieces/community/rabbitmq/package.json
@@ -1,23 +1,25 @@
{
"name": "@activepieces/piece-rabbitmq",
- "version": "0.1.8",
+ "version": "0.2.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"amqplib": "0.10.7",
- "dayjs": "1.11.9",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
"@types/amqplib": "0.10.7",
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/rabbitmq/src/index.ts b/packages/pieces/community/rabbitmq/src/index.ts
index 79cfc3820a8..0f0c555d22d 100644
--- a/packages/pieces/community/rabbitmq/src/index.ts
+++ b/packages/pieces/community/rabbitmq/src/index.ts
@@ -1,22 +1,30 @@
-import { createPiece, PieceAuth, Property } from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { messageReceived } from './lib/triggers/message-received';
import { sendMessageToExchange } from './lib/actions/send-message-to-exchange';
import { sendMessageToQueue } from './lib/actions/send-message-to-queue';
+import { publishToQueue } from './lib/actions/ai/publish-to-queue';
+import { publishToExchange } from './lib/actions/ai/publish-to-exchange';
+import { getQueueInfo } from './lib/actions/ai/get-queue-info';
+import { listQueues } from './lib/actions/ai/list-queues';
+import { listExchanges } from './lib/actions/ai/list-exchanges';
+import { listBindings } from './lib/actions/ai/list-bindings';
import { rabbitmqAuth } from './lib/auth';
export const rabbitmq = createPiece({
- displayName: "RabbitMQ",
+ displayName: 'RabbitMQ',
auth: rabbitmqAuth,
- minimumSupportedRelease: '0.30.0',
- logoUrl: "https://cdn.activepieces.com/pieces/rabbitmq.png",
- authors: [
- "alinperghel"
- ],
+ minimumSupportedRelease: '0.86.4',
+ logoUrl: 'https://cdn.activepieces.com/pieces/rabbitmq.png',
+ authors: ['alinperghel', 'OdaiAhmed99'],
actions: [
sendMessageToExchange,
sendMessageToQueue,
+ publishToQueue,
+ publishToExchange,
+ getQueueInfo,
+ listQueues,
+ listExchanges,
+ listBindings,
],
- triggers: [
- messageReceived,
- ],
+ triggers: [messageReceived],
});
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/ai/get-queue-info.ts b/packages/pieces/community/rabbitmq/src/lib/actions/ai/get-queue-info.ts
new file mode 100644
index 00000000000..4bfd68c619d
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/ai/get-queue-info.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { rabbitmqAuth } from '../../auth';
+import { rabbitmqCommon } from '../../common';
+
+export const getQueueInfo = createAction({
+ auth: rabbitmqAuth,
+ name: 'rabbitmq_get_queue_info',
+ displayName: 'Get Queue Info',
+ description: 'Gets the message and consumer count of a queue.',
+ audience: 'ai',
+ classification: 'READ',
+ outputSchema: {
+ fields: [
+ { key: 'queue', label: 'Queue' },
+ { key: 'messageCount', label: 'Ready Messages', format: 'number' },
+ { key: 'consumerCount', label: 'Consumers', format: 'number' },
+ ],
+ },
+ aiMetadata: {
+ description:
+ 'Checks that a RabbitMQ queue exists and returns how many messages are ready and how many consumers are attached. Works without the Management API. Fails if the queue does not exist. Does not read or remove messages.',
+ idempotent: true,
+ },
+ props: {
+ queue: Property.ShortText({
+ displayName: 'Queue',
+ description: 'Exact name of the queue.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { queue } = context.propsValue;
+ return rabbitmqCommon.withChannel({
+ auth: context.auth.props,
+ fn: async (channel) => {
+ const info = await channel.checkQueue(queue);
+ return {
+ queue: info.queue,
+ messageCount: info.messageCount,
+ consumerCount: info.consumerCount,
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-bindings.ts b/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-bindings.ts
new file mode 100644
index 00000000000..494d44d5f69
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-bindings.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { rabbitmqAuth } from '../../auth';
+import { rabbitmqCommon } from '../../common';
+
+export const listBindings = createAction({
+ auth: rabbitmqAuth,
+ name: 'rabbitmq_list_bindings',
+ displayName: 'List Bindings',
+ description: 'Lists the bindings in the connected virtual host.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ outputSchema: {
+ fields: [
+ {
+ key: 'bindings',
+ label: 'Bindings',
+ listItems: [
+ { key: 'source', label: 'Source Exchange' },
+ { key: 'destination', label: 'Destination' },
+ { key: 'destinationType', label: 'Destination Type' },
+ { key: 'routingKey', label: 'Routing Key' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ },
+ aiMetadata: {
+ description:
+ 'Lists the bindings that route messages from exchanges to queues or other exchanges in the connection\'s virtual host. Filter by exchange to see which routing keys reach which queues before calling Publish to Exchange. Default-exchange bindings are left out. Requires the Management API URL in the connection; without it the call fails with a message saying so.',
+ idempotent: true,
+ },
+ props: {
+ exchange: Property.ShortText({
+ displayName: 'Exchange',
+ description: 'Optional. Only return bindings whose source is this exchange.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const auth = context.auth.props;
+ const { exchange } = context.propsValue;
+ const vhost = rabbitmqCommon.encodedVhost(auth);
+ const path = exchange
+ ? `/exchanges/${vhost}/${encodeURIComponent(exchange)}/bindings/source`
+ : `/bindings/${vhost}`;
+ const bindings = await rabbitmqCommon.managementRequest<ManagementBinding[]>({ auth, path });
+ const mapped = bindings
+ .filter((b) => b.source !== '')
+ .map((b) => ({
+ source: b.source,
+ destination: b.destination,
+ destinationType: b.destination_type,
+ routingKey: b.routing_key,
+ }));
+ return { bindings: mapped, count: mapped.length };
+ },
+});
+
+type ManagementBinding = {
+ source: string;
+ destination: string;
+ destination_type: string;
+ routing_key: string;
+};
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-exchanges.ts b/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-exchanges.ts
new file mode 100644
index 00000000000..173c5197170
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-exchanges.ts
@@ -0,0 +1,60 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { rabbitmqAuth } from '../../auth';
+import { rabbitmqCommon } from '../../common';
+
+export const listExchanges = createAction({
+ auth: rabbitmqAuth,
+ name: 'rabbitmq_list_exchanges',
+ displayName: 'List Exchanges',
+ description: 'Lists the exchanges in the connected virtual host.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ outputSchema: {
+ fields: [
+ {
+ key: 'exchanges',
+ label: 'Exchanges',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Type' },
+ { key: 'durable', label: 'Durable', format: 'boolean' },
+ { key: 'autoDelete', label: 'Auto Delete', format: 'boolean' },
+ { key: 'internal', label: 'Internal', format: 'boolean' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ },
+ aiMetadata: {
+ description:
+ 'Lists the exchanges in the connection\'s virtual host with their type (direct, topic, fanout, headers). The unnamed default exchange is left out. Use it to find an exchange name for Publish to Exchange. Requires the Management API URL in the connection; without it the call fails with a message saying so.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const auth = context.auth.props;
+ const exchanges = await rabbitmqCommon.managementRequest<ManagementExchange[]>({
+ auth,
+ path: `/exchanges/${rabbitmqCommon.encodedVhost(auth)}`,
+ });
+ const mapped = exchanges
+ .filter((e) => e.name !== '')
+ .map((e) => ({
+ name: e.name,
+ type: e.type,
+ durable: e.durable,
+ autoDelete: e.auto_delete,
+ internal: e.internal,
+ }));
+ return { exchanges: mapped, count: mapped.length };
+ },
+});
+
+type ManagementExchange = {
+ name: string;
+ type: string;
+ durable: boolean;
+ auto_delete: boolean;
+ internal: boolean;
+};
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-queues.ts b/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-queues.ts
new file mode 100644
index 00000000000..d0a4db7f73d
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/ai/list-queues.ts
@@ -0,0 +1,64 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { rabbitmqAuth } from '../../auth';
+import { rabbitmqCommon } from '../../common';
+
+export const listQueues = createAction({
+ auth: rabbitmqAuth,
+ name: 'rabbitmq_list_queues',
+ displayName: 'List Queues',
+ description: 'Lists the queues in the connected virtual host.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ outputSchema: {
+ fields: [
+ {
+ key: 'queues',
+ label: 'Queues',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'vhost', label: 'Virtual Host' },
+ { key: 'type', label: 'Type' },
+ { key: 'durable', label: 'Durable', format: 'boolean' },
+ { key: 'messages', label: 'Messages', format: 'number' },
+ { key: 'consumers', label: 'Consumers', format: 'number' },
+ { key: 'state', label: 'State' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ },
+ aiMetadata: {
+ description:
+ 'Lists every queue in the connection\'s virtual host with its message and consumer counts. Use it to find the exact queue name before publishing or reading. Requires the Management API URL in the connection; without it the call fails with a message saying so.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const auth = context.auth.props;
+ const queues = await rabbitmqCommon.managementRequest<ManagementQueue[]>({
+ auth,
+ path: `/queues/${rabbitmqCommon.encodedVhost(auth)}?columns=name,vhost,type,durable,messages,consumers,state`,
+ });
+ const mapped = queues.map((q) => ({
+ name: q.name,
+ vhost: q.vhost,
+ type: q.type ?? null,
+ durable: q.durable,
+ messages: q.messages ?? 0,
+ consumers: q.consumers ?? 0,
+ state: q.state ?? null,
+ }));
+ return { queues: mapped, count: mapped.length };
+ },
+});
+
+type ManagementQueue = {
+ name: string;
+ vhost: string;
+ type?: string;
+ durable: boolean;
+ messages?: number;
+ consumers?: number;
+ state?: string;
+};
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/ai/publish-to-exchange.ts b/packages/pieces/community/rabbitmq/src/lib/actions/ai/publish-to-exchange.ts
new file mode 100644
index 00000000000..47a632574e7
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/ai/publish-to-exchange.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { rabbitmqAuth } from '../../auth';
+import { publishOutputSchema, rabbitmqCommon } from '../../common';
+
+export const publishToExchange = createAction({
+ auth: rabbitmqAuth,
+ name: 'rabbitmq_publish_to_exchange',
+ displayName: 'Publish to Exchange',
+ description: 'Publishes a message to an exchange with a routing key.',
+ audience: 'ai',
+ classification: 'WRITE',
+ outputSchema: publishOutputSchema,
+ aiMetadata: {
+ description:
+ 'Publishes one message to an existing RabbitMQ exchange with a routing key, and waits for the broker to confirm it. The exchange routes it to every bound queue whose binding matches; a message that matches no binding is dropped silently. Use List Exchanges and List Bindings to find the exchange and a matching routing key. Use Publish to Queue to target one queue directly. Not idempotent: every call publishes a new message.',
+ idempotent: false,
+ },
+ props: {
+ exchange: Property.ShortText({
+ displayName: 'Exchange',
+ description: 'Exact name of an existing exchange.',
+ required: true,
+ }),
+ routingKey: Property.ShortText({
+ displayName: 'Routing Key',
+ description: 'Routing key, for example orders.created. Leave empty for fanout exchanges.',
+ required: false,
+ }),
+ message: Property.LongText({
+ displayName: 'Message',
+ description: 'Message body. A valid JSON string is sent as application/json, anything else as text/plain.',
+ required: true,
+ }),
+ ...rabbitmqCommon.publishOptionProps,
+ },
+ async run(context) {
+ const { exchange, routingKey, message, persistent, contentType, headers } = context.propsValue;
+ return rabbitmqCommon.publish({
+ auth: context.auth.props,
+ target: { type: 'exchange', exchange, routingKey: routingKey ?? '' },
+ data: message,
+ options: { persistent, contentType: contentType || rabbitmqCommon.detectContentType(message), headers },
+ });
+ },
+});
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/ai/publish-to-queue.ts b/packages/pieces/community/rabbitmq/src/lib/actions/ai/publish-to-queue.ts
new file mode 100644
index 00000000000..b51657e880c
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/ai/publish-to-queue.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { rabbitmqAuth } from '../../auth';
+import { publishOutputSchema, rabbitmqCommon } from '../../common';
+
+export const publishToQueue = createAction({
+ auth: rabbitmqAuth,
+ name: 'rabbitmq_publish_to_queue',
+ displayName: 'Publish to Queue',
+ description: 'Publishes a message directly to a queue.',
+ audience: 'ai',
+ classification: 'WRITE',
+ outputSchema: publishOutputSchema,
+ aiMetadata: {
+ description:
+ 'Publishes one message straight onto an existing RabbitMQ queue through the default exchange, and waits for the broker to confirm it. Use Publish to Exchange instead when the message should be routed by an exchange and routing key. Use Get Queue Info or List Queues first if the queue name is unknown; the call fails if the queue does not exist. Not idempotent: every call adds a new message.',
+ idempotent: false,
+ },
+ props: {
+ queue: Property.ShortText({
+ displayName: 'Queue',
+ description: 'Exact name of an existing queue.',
+ required: true,
+ }),
+ message: Property.LongText({
+ displayName: 'Message',
+ description: 'Message body. A valid JSON string is sent as application/json, anything else as text/plain.',
+ required: true,
+ }),
+ ...rabbitmqCommon.publishOptionProps,
+ },
+ async run(context) {
+ const { queue, message, persistent, contentType, headers } = context.propsValue;
+ return rabbitmqCommon.publish({
+ auth: context.auth.props,
+ target: { type: 'queue', queue },
+ data: message,
+ options: { persistent, contentType: contentType || rabbitmqCommon.detectContentType(message), headers },
+ });
+ },
+});
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-exchange.ts b/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-exchange.ts
index 4eebc2b7bc0..316e8412ea1 100644
--- a/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-exchange.ts
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-exchange.ts
@@ -1,15 +1,15 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { rabbitmqAuth } from '../auth';
-import { rabbitmqConnect } from '../common';
+import { publishOutputSchema, rabbitmqCommon } from '../common';
export const sendMessageToExchange = createAction({
auth: rabbitmqAuth,
name: 'sendMessageToExchange',
classification: 'WRITE',
- displayName: 'sendMessageToExchange',
+ displayName: 'Send Message to Exchange',
description: 'Send a message on a RabbitMQ exchange',
- audience: 'both',
- aiMetadata: { description: 'Publishes a JSON message to a named RabbitMQ exchange, optionally with a routing key that the exchange uses to route the message to bound queues. Choose this to emit an event into a pub/sub or topic-style topology where one exchange fans out to multiple consumers; use the send-to-queue action instead to push directly onto a specific queue. The target exchange must already exist (the call verifies it first). Not idempotent: each call publishes a new message.', idempotent: false },
+ audience: 'human',
+ outputSchema: publishOutputSchema,
props: {
exchange: Property.ShortText({
displayName: 'Exchange',
@@ -27,39 +27,20 @@ export const sendMessageToExchange = createAction({
description: 'The data to send',
required: true,
defaultValue: {
- "key": "value",
- "nested": { "key": "value" },
- "array": ["value1", "value2"]
+ key: 'value',
+ nested: { key: 'value' },
+ array: ['value1', 'value2'],
},
}),
+ ...rabbitmqCommon.publishOptionProps,
},
async run(context) {
- let connection;
- let channel;
- try {
- const exchange = context.propsValue.exchange;
- const routingKey = context.propsValue.routingKey || '';
-
- connection = await rabbitmqConnect(context.auth.props);
- channel = await connection.createChannel();
-
- await channel.checkExchange(exchange);
-
- const result = channel.publish(
- exchange,
- routingKey,
- Buffer.from(JSON.stringify(context.propsValue.data))
- );
-
- if (!result) {
- throw new Error('Failed to send message to exchange');
- }
- return result;
- } finally {
- if (channel)
- await channel.close();
- if (connection)
- await connection.close();
- }
- }
+ const { exchange, routingKey, data, persistent, contentType, headers } = context.propsValue;
+ return rabbitmqCommon.publish({
+ auth: context.auth.props,
+ target: { type: 'exchange', exchange, routingKey: routingKey || '' },
+ data,
+ options: { persistent, contentType, headers },
+ });
+ },
});
diff --git a/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-queue.ts b/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-queue.ts
index 79d6244513e..b8e53d046e7 100644
--- a/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-queue.ts
+++ b/packages/pieces/community/rabbitmq/src/lib/actions/send-message-to-queue.ts
@@ -1,19 +1,19 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { rabbitmqAuth } from '../auth';
-import { rabbitmqConnect } from '../common';
+import { publishOutputSchema, rabbitmqCommon } from '../common';
export const sendMessageToQueue = createAction({
auth: rabbitmqAuth,
name: 'sendMessageToQueue',
classification: 'WRITE',
- displayName: 'sendMessageToQueue',
+ displayName: 'Send Message to Queue',
description: 'Send a message on a RabbitMQ queue',
- audience: 'both',
- aiMetadata: { description: 'Publishes a JSON message directly to a named RabbitMQ queue (default exchange), bypassing exchange-based routing. Choose this to enqueue work onto one specific queue for its consumers; use the send-to-exchange action when you need routing-key-based fan-out across multiple queues. The target queue must already exist (the call verifies it first). Not idempotent: each call enqueues a new message.', idempotent: false },
+ audience: 'human',
+ outputSchema: publishOutputSchema,
props: {
queue: Property.ShortText({
displayName: 'Queue',
- description: 'The name of the exchange to send the message to',
+ description: 'The name of the queue to send the message to. It must already exist.',
required: true,
}),
data: Property.Json({
@@ -21,38 +21,20 @@ export const sendMessageToQueue = createAction({
description: 'The data to send',
required: true,
defaultValue: {
- "key": "value",
- "nested": { "key": "value" },
- "array": ["value1", "value2"]
+ key: 'value',
+ nested: { key: 'value' },
+ array: ['value1', 'value2'],
},
}),
+ ...rabbitmqCommon.publishOptionProps,
},
async run(context) {
- const queue = context.propsValue.queue;
- let connection;
- let channel;
- try {
- connection = await rabbitmqConnect(context.auth.props);
- channel = await connection.createChannel();
-
- await channel.checkQueue(queue);
-
- const result = channel.sendToQueue(
- queue,
- Buffer.from(JSON.stringify(context.propsValue.data))
- );
-
- if (!result) {
- throw new Error('Failed to send message to exchange');
- }
- return result;
- } finally {
- if (channel) {
- await channel.close();
- }
- if (connection) {
- await connection.close();
- }
- }
- }
+ const { queue, data, persistent, contentType, headers } = context.propsValue;
+ return rabbitmqCommon.publish({
+ auth: context.auth.props,
+ target: { type: 'queue', queue },
+ data,
+ options: { persistent, contentType, headers },
+ });
+ },
});
diff --git a/packages/pieces/community/rabbitmq/src/lib/auth.ts b/packages/pieces/community/rabbitmq/src/lib/auth.ts
index 5316244ce8c..c8d83004bc0 100644
--- a/packages/pieces/community/rabbitmq/src/lib/auth.ts
+++ b/packages/pieces/community/rabbitmq/src/lib/auth.ts
@@ -1,33 +1,69 @@
import { PieceAuth, Property } from '@activepieces/pieces-framework';
+import { rabbitmqCommon } from './common';
export const rabbitmqAuth = PieceAuth.CustomAuth({
- description: "Rabbitmq Auth",
+ description: 'Connect to your RabbitMQ broker over AMQP. Add the Management API URL to let AI agents list queues, exchanges and bindings.',
required: true,
props: {
host: Property.ShortText({
- displayName: "Host",
- description: "Host",
+ displayName: 'Host',
+ description: 'Broker host name or IP, without scheme or port (for example rabbitmq.example.com).',
required: true,
}),
username: Property.ShortText({
- displayName: "Username",
- description: "Username",
+ displayName: 'Username',
+ description: 'Username',
required: true,
}),
password: PieceAuth.SecretText({
- displayName: "Password",
- description: "Password",
+ displayName: 'Password',
+ description: 'Password',
required: true,
}),
port: Property.Number({
- displayName: "Port",
- description: "Port",
+ displayName: 'Port',
+ description: 'AMQP port. Usually 5672, or 5671 with TLS.',
required: true,
+ defaultValue: 5672,
}),
vhost: Property.ShortText({
- displayName: "Virtual Host",
- description: "Virtual Host",
+ displayName: 'Virtual Host',
+ description: 'Virtual host name. Leave empty for the default "/".',
required: false,
}),
+ useTls: Property.Checkbox({
+ displayName: 'Use TLS (amqps)',
+ description: 'Connect with TLS. Most hosted brokers require this.',
+ required: false,
+ defaultValue: false,
+ }),
+ managementUrl: Property.ShortText({
+ displayName: 'Management API URL',
+ description: 'Optional. Base URL of the RabbitMQ Management plugin (for example http://localhost:15672). Uses the same username and password.',
+ required: false,
+ }),
+ },
+ validate: async ({ auth }) => {
+ try {
+ const connection = await rabbitmqCommon.connect(auth);
+ connection.on('error', () => undefined);
+ await connection.close().catch(() => undefined);
+ } catch (e) {
+ return {
+ valid: false,
+ error: `Could not connect to the broker: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+ if (auth.managementUrl) {
+ try {
+ await rabbitmqCommon.managementRequest({ auth, path: '/overview' });
+ } catch {
+ return {
+ valid: false,
+ error: 'Connected over AMQP, but the Management API URL did not accept these credentials. Check the URL and that the user has the "management" tag.',
+ };
+ }
+ }
+ return { valid: true };
},
});
diff --git a/packages/pieces/community/rabbitmq/src/lib/common/index.ts b/packages/pieces/community/rabbitmq/src/lib/common/index.ts
index ce2d013af4d..99d171f6708 100644
--- a/packages/pieces/community/rabbitmq/src/lib/common/index.ts
+++ b/packages/pieces/community/rabbitmq/src/lib/common/index.ts
@@ -1,24 +1,370 @@
-import { PiecePropValueSchema } from '@activepieces/pieces-framework';
-import { rabbitmqAuth } from '../auth';
-import amqp, { ChannelModel, Connection } from 'amqplib';
-
-export async function rabbitmqConnect(
- auth: PiecePropValueSchema<typeof rabbitmqAuth>,
-): Promise<ChannelModel> {
- return amqp.connect(createAmqpURI(auth), (err: Error, conn: Connection) => {
- if (err) {
- throw err;
+import { OutputSchema, PiecePropValueSchema, Property } from '@activepieces/pieces-framework';
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import amqp, { Channel, ChannelModel, ConfirmChannel, GetMessage } from 'amqplib';
+import type { rabbitmqAuth } from '../auth';
+
+function createAmqpURI(auth: RabbitmqAuthProps): string {
+ const scheme = auth.useTls ? 'amqps' : 'amqp';
+ const port = auth.port ?? (auth.useTls ? 5671 : 5672);
+ const credentials = `${encodeURIComponent(auth.username)}:${encodeURIComponent(auth.password)}`;
+ const uri = `${scheme}://${credentials}@${auth.host}:${port}`;
+ if (!auth.vhost) {
+ return uri;
+ }
+ return `${uri}/${encodeURIComponent(auth.vhost)}`;
+}
+
+async function connect(auth: RabbitmqAuthProps): Promise<ChannelModel> {
+ return amqp.connect(createAmqpURI(auth));
+}
+
+function toPieceError(error: unknown): Error {
+ const message = error instanceof Error ? error.message : String(error);
+ const notFound = /no (queue|exchange) '([^']*)' in vhost '([^']*)'/.exec(message);
+ if (notFound) {
+ const kind = notFound[1] === 'queue' ? 'Queue' : 'Exchange';
+ return new Error(`${kind} "${notFound[2]}" does not exist in vhost "${notFound[3]}".`);
+ }
+ if (/ACCESS_REFUSED|403/.test(message)) {
+ return new Error(`RabbitMQ refused access: ${message}`);
+ }
+ return error instanceof Error ? error : new Error(message);
+}
+
+async function runWithChannel<C extends Channel, T>({
+ auth,
+ open,
+ fn,
+}: {
+ auth: RabbitmqAuthProps;
+ open: (connection: ChannelModel) => Promise<C>;
+ fn: (channel: C) => Promise<T>;
+}): Promise<T> {
+ const connection = await connect(auth);
+ let brokerError: unknown;
+ let channelClosed = false;
+ const captureError = (error: unknown): void => {
+ brokerError ??= error;
+ };
+ connection.on('error', captureError);
+ let channel: C | undefined;
+ try {
+ channel = await open(connection);
+ channel.on('error', captureError);
+ channel.on('close', () => {
+ channelClosed = true;
+ });
+ return await fn(channel);
+ } catch (error) {
+ throw toPieceError(brokerError ?? error);
+ } finally {
+ if (channel && !channelClosed) {
+ await channel.close().catch(() => undefined);
}
+ await connection.close().catch(() => undefined);
+ }
+}
- return conn;
+async function withChannel<T>({
+ auth,
+ fn,
+}: {
+ auth: RabbitmqAuthProps;
+ fn: (channel: Channel) => Promise<T>;
+}): Promise<T> {
+ return runWithChannel({ auth, open: (connection) => connection.createChannel(), fn });
+}
+
+async function withConfirmChannel<T>({
+ auth,
+ fn,
+}: {
+ auth: RabbitmqAuthProps;
+ fn: (channel: ConfirmChannel) => Promise<T>;
+}): Promise<T> {
+ return runWithChannel({ auth, open: (connection) => connection.createConfirmChannel(), fn });
+}
+
+function toBuffer(data: unknown): Buffer {
+ if (typeof data === 'string') {
+ return Buffer.from(data);
+ }
+ return Buffer.from(JSON.stringify(data ?? null));
+}
+
+function parseHeaders(headers: unknown): Record<string, unknown> | undefined {
+ if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
+ return undefined;
+ }
+ const result: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(headers)) {
+ result[key] = value;
+ }
+ return Object.keys(result).length > 0 ? result : undefined;
+}
+
+async function publish({
+ auth,
+ target,
+ data,
+ options,
+}: {
+ auth: RabbitmqAuthProps;
+ target: PublishTarget;
+ data: unknown;
+ options: PublishOptions;
+}): Promise<PublishResult> {
+ const content = toBuffer(data);
+ const publishOptions = {
+ persistent: options.persistent ?? true,
+ contentType: options.contentType || (typeof data === 'string' ? 'text/plain' : 'application/json'),
+ headers: parseHeaders(options.headers),
+ };
+ return withConfirmChannel({
+ auth,
+ fn: async (channel) => {
+ if (target.type === 'queue') {
+ await channel.checkQueue(target.queue);
+ channel.sendToQueue(target.queue, content, publishOptions);
+ } else {
+ await channel.checkExchange(target.exchange);
+ channel.publish(target.exchange, target.routingKey, content, publishOptions);
+ }
+ await channel.waitForConfirms();
+ return {
+ success: true,
+ queue: target.type === 'queue' ? target.queue : null,
+ exchange: target.type === 'exchange' ? target.exchange : null,
+ routingKey: target.type === 'queue' ? target.queue : target.routingKey,
+ sizeBytes: content.length,
+ persistent: publishOptions.persistent,
+ contentType: publishOptions.contentType,
+ };
+ },
});
}
-function createAmqpURI(auth: PiecePropValueSchema<typeof rabbitmqAuth>): string {
- const uri = `amqp://${auth.username}:${auth.password}@${auth.host}:${auth.port}`;
+function detectContentType(message: string): string {
+ try {
+ JSON.parse(message);
+ return 'application/json';
+ } catch {
+ return 'text/plain';
+ }
+}
- if (!auth.vhost) {
- return uri;
+function parseContent(message: GetMessage): ParsedMessage {
+ const rawContent = message.content.toString('utf8');
+ let content: unknown = rawContent;
+ try {
+ content = JSON.parse(rawContent);
+ } catch {
+ content = rawContent;
+ }
+ const { properties, fields } = message;
+ return {
+ content,
+ rawContent,
+ properties: {
+ contentType: properties.contentType ?? null,
+ contentEncoding: properties.contentEncoding ?? null,
+ headers: properties.headers ?? {},
+ deliveryMode: properties.deliveryMode ?? null,
+ priority: properties.priority ?? null,
+ correlationId: properties.correlationId ?? null,
+ replyTo: properties.replyTo ?? null,
+ expiration: properties.expiration ?? null,
+ messageId: properties.messageId ?? null,
+ timestamp: properties.timestamp ?? null,
+ type: properties.type ?? null,
+ userId: properties.userId ?? null,
+ appId: properties.appId ?? null,
+ },
+ fields: {
+ deliveryTag: fields.deliveryTag,
+ redelivered: fields.redelivered,
+ exchange: fields.exchange,
+ routingKey: fields.routingKey,
+ messageCount: 'messageCount' in fields ? fields.messageCount : null,
+ },
+ };
+}
+
+function encodedVhost(auth: RabbitmqAuthProps): string {
+ return encodeURIComponent(auth.vhost || '/');
+}
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+async function managementRequest<T>({
+ auth,
+ path,
+}: {
+ auth: RabbitmqAuthProps;
+ path: string;
+}): Promise<T> {
+ if (!auth.managementUrl) {
+ throw new Error(
+ 'This action needs the RabbitMQ Management API. Set "Management API URL" in the connection (for example http://localhost:15672).',
+ );
+ }
+ const base = auth.managementUrl.replace(/\/+$/, '');
+ const token = Buffer.from(`${auth.username}:${auth.password}`).toString('base64');
+ try {
+ const response = await httpClient.sendRequest<T>(
+ {
+ method: HttpMethod.GET,
+ url: `${base}/api${path}`,
+ headers: { Accept: 'application/json', Authorization: `Basic ${token}` },
+ timeout: 30000,
+ },
+ { dispatcher: await verifiedTls() },
+ );
+ return response.body;
+ } catch (error) {
+ const failure = readHttpFailure(error);
+ if (failure === undefined) {
+ throw error;
+ }
+ throw new RabbitmqManagementError({
+ message: `RabbitMQ Management API request to ${path.split('?')[0]} failed (HTTP ${failure.status}).`,
+ status: failure.status,
+ responseBody: JSON.stringify(failure.body ?? null).slice(0, 2000),
+ });
}
- return `${uri}/${auth.vhost}`;
}
+
+function readHttpFailure(error: unknown): { status: number; body: unknown } | undefined {
+ if (typeof error !== 'object' || error === null || !('response' in error)) {
+ return undefined;
+ }
+ const { response } = error;
+ if (typeof response !== 'object' || response === null || !('status' in response) || typeof response.status !== 'number') {
+ return undefined;
+ }
+ return { status: response.status, body: 'body' in response ? response.body : undefined };
+}
+
+class RabbitmqManagementError extends Error {
+ status: number;
+ responseBody: string;
+ constructor({ message, status, responseBody }: { message: string; status: number; responseBody: string }) {
+ super(message);
+ this.name = 'RabbitmqManagementError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+const publishOptionProps = {
+ persistent: Property.Checkbox({
+ displayName: 'Persistent',
+ description: 'Ask the broker to write the message to disk so it survives a broker restart (only on durable queues).',
+ required: false,
+ defaultValue: true,
+ }),
+ contentType: Property.ShortText({
+ displayName: 'Content Type',
+ description: 'MIME type set on the message. Defaults to application/json, or text/plain when the data is plain text.',
+ required: false,
+ }),
+ headers: Property.Json({
+ displayName: 'Headers',
+ description: 'Optional message headers as a JSON object, for example {"source": "activepieces"}.',
+ required: false,
+ }),
+};
+
+export const rabbitmqCommon = {
+ toPieceError,
+ runWithChannel,
+ connect,
+ withChannel,
+ publish,
+ parseContent,
+ detectContentType,
+ managementRequest,
+ encodedVhost,
+ publishOptionProps,
+};
+
+export type RabbitmqAuthProps = PiecePropValueSchema<typeof rabbitmqAuth>;
+
+export type PublishTarget =
+ | { type: 'queue'; queue: string }
+ | { type: 'exchange'; exchange: string; routingKey: string };
+
+export type PublishOptions = {
+ persistent?: boolean;
+ contentType?: string;
+ headers?: unknown;
+};
+
+export type PublishResult = {
+ success: boolean;
+ queue: string | null;
+ exchange: string | null;
+ routingKey: string;
+ sizeBytes: number;
+ persistent: boolean;
+ contentType: string;
+};
+
+export type ParsedMessage = {
+ content: unknown;
+ rawContent: string;
+ properties: Record<string, unknown>;
+ fields: {
+ deliveryTag: number;
+ redelivered: boolean;
+ exchange: string;
+ routingKey: string;
+ messageCount: number | null;
+ };
+};
+
+export const publishOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Confirmed by Broker', format: 'boolean' },
+ { key: 'queue', label: 'Queue' },
+ { key: 'exchange', label: 'Exchange' },
+ { key: 'routingKey', label: 'Routing Key' },
+ { key: 'sizeBytes', label: 'Size', format: 'filesize' },
+ { key: 'persistent', label: 'Persistent', format: 'boolean' },
+ { key: 'contentType', label: 'Content Type' },
+ ],
+};
+
+export const messageFieldsSchema: OutputSchema['fields'] = [
+ { key: 'content', label: 'Content', description: 'Parsed JSON when the body is JSON, otherwise the raw text' },
+ { key: 'rawContent', label: 'Raw Content' },
+ {
+ key: 'properties',
+ label: 'Properties',
+ children: [
+ { key: 'contentType', label: 'Content Type' },
+ { key: 'headers', label: 'Headers' },
+ { key: 'messageId', label: 'Message ID' },
+ { key: 'correlationId', label: 'Correlation ID' },
+ { key: 'timestamp', label: 'Timestamp', format: 'number' },
+ { key: 'type', label: 'Type' },
+ { key: 'appId', label: 'App ID' },
+ { key: 'deliveryMode', label: 'Delivery Mode', format: 'number' },
+ ],
+ },
+ {
+ key: 'fields',
+ label: 'Delivery',
+ children: [
+ { key: 'exchange', label: 'Exchange' },
+ { key: 'routingKey', label: 'Routing Key' },
+ { key: 'redelivered', label: 'Redelivered', format: 'boolean' },
+ { key: 'deliveryTag', label: 'Delivery Tag', format: 'number' },
+ ],
+ },
+];
diff --git a/packages/pieces/community/rabbitmq/src/lib/triggers/message-received.ts b/packages/pieces/community/rabbitmq/src/lib/triggers/message-received.ts
index 3763fda4aba..176c146e9b2 100644
--- a/packages/pieces/community/rabbitmq/src/lib/triggers/message-received.ts
+++ b/packages/pieces/community/rabbitmq/src/lib/triggers/message-received.ts
@@ -1,51 +1,43 @@
-import {
- createTrigger,
- TriggerStrategy,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
-} from '@activepieces/pieces-framework';
-import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
+import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';
import { rabbitmqAuth } from '../auth';
-import { rabbitmqConnect } from '../common';
-import dayjs from 'dayjs';
+import { RabbitmqAuthProps, rabbitmqCommon } from '../common';
-const polling: Polling<AppConnectionValueForAuthProperty<typeof rabbitmqAuth>, {
- queue: string,
- maxMessagesPerPoll: number,
-}> = {
- strategy: DedupeStrategy.LAST_ITEM,
- items: async ({ auth, propsValue }) => {
- const connection = await rabbitmqConnect(auth.props);
- const channel = await connection.createChannel();
- const messages = [];
-
- try {
- const queueInfo = await channel.checkQueue(propsValue.queue);
-
- if (queueInfo.messageCount === 0) {
- return [];
- }
-
- for (let i = 0; i < propsValue.maxMessagesPerPoll; i++) {
- const message = await channel.get(propsValue.queue);
+async function readMessages({
+ auth,
+ queue,
+ max,
+ consume,
+}: {
+ auth: RabbitmqAuthProps;
+ queue: string;
+ max: number;
+ consume: boolean;
+}): Promise<unknown[]> {
+ return rabbitmqCommon.withChannel({
+ auth,
+ fn: async (channel) => {
+ const messages: unknown[] = [];
+ let last: Awaited<ReturnType<typeof channel.get>> = false;
+ const limit = Math.max(1, Math.floor(max));
+ for (let i = 0; i < limit; i++) {
+ const message = await channel.get(queue, { noAck: false });
if (!message) {
break;
}
- messages.push({
- id: dayjs().toISOString(),
- data: JSON.parse(message.content.toString()),
- });
- channel.ack(message);
+ messages.push(rabbitmqCommon.parseContent(message).content);
+ last = message;
}
- } finally {
- await channel.close();
- await connection.close();
- }
-
- return messages;
- },
-};
+ // Ack once after the loop so a dropped connection redelivers the batch instead of losing it.
+ if (consume && last) {
+ channel.ack(last, true);
+ }
+ if (!consume) {
+ channel.nackAll(true);
+ }
+ return messages;
+ },
+ });
+}
export const messageReceived = createTrigger({
auth: rabbitmqAuth,
@@ -54,7 +46,8 @@ export const messageReceived = createTrigger({
displayName: 'Message Received',
description: 'Triggers when a message is received on a RabbitMQ queue',
aiMetadata: {
- description: 'Fires when one or more messages are available on a configured RabbitMQ queue, emitting each consumed message. Polls the queue on a schedule, pulling up to a configurable maximum number of messages per poll and acknowledging (removing) them from the queue as it reads.',
+ description:
+ 'Fires for each message on a configured RabbitMQ queue. Each poll pulls up to the configured maximum and acknowledges (removes) the messages it emits. Each output is the message body itself: JSON bodies are emitted as the parsed object, other bodies as a text string. Testing the trigger only peeks: messages are put back on the queue.',
},
props: {
queue: Property.ShortText({
@@ -69,20 +62,28 @@ export const messageReceived = createTrigger({
defaultValue: 50,
}),
},
- sampleData: {},
+ sampleData: { orderId: 'A-1001', status: 'created' },
type: TriggerStrategy.POLLING,
async test(context) {
- return await pollingHelper.test(polling, context);
+ return readMessages({
+ auth: context.auth.props,
+ queue: context.propsValue.queue,
+ max: Math.min(context.propsValue.maxMessagesPerPoll ?? 5, 5),
+ consume: false,
+ });
},
- async onEnable(context) {
- await pollingHelper.onEnable(polling, context);
+ async onEnable() {
+ return;
},
-
- async onDisable(context) {
- await pollingHelper.onDisable(polling, context);
+ async onDisable() {
+ return;
},
-
async run(context) {
- return await pollingHelper.poll(polling, context);
+ return readMessages({
+ auth: context.auth.props,
+ queue: context.propsValue.queue,
+ max: context.propsValue.maxMessagesPerPoll ?? 50,
+ consume: true,
+ });
},
});
diff --git a/packages/pieces/community/rabbitmq/test/rabbitmq.test.ts b/packages/pieces/community/rabbitmq/test/rabbitmq.test.ts
new file mode 100644
index 00000000000..1f3aeda15a2
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/test/rabbitmq.test.ts
@@ -0,0 +1,201 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => {
+ const value: FakeState = {
+ uris: [],
+ queue: [],
+ acked: 0,
+ ackAllUpTo: [],
+ nackAllRequeue: [],
+ checkQueueError: undefined,
+ };
+ return value;
+});
+
+vi.mock('amqplib', async () => {
+ const { EventEmitter: Emitter } = await import('node:events');
+ class FakeChannel extends Emitter {
+ closeCalls = 0;
+ async checkQueue(queue: string) {
+ if (state.checkQueueError) {
+ const message = state.checkQueueError;
+ setImmediate(() => {
+ this.emit('error', new Error(message));
+ this.emit('close');
+ });
+ await new Promise((r) => setTimeout(r, 5));
+ throw new Error('Channel closed');
+ }
+ return { queue, messageCount: state.queue.length, consumerCount: 0 };
+ }
+ async get() {
+ return state.queue.shift() ?? false;
+ }
+ ack(_message: unknown, allUpTo?: boolean) {
+ state.acked++;
+ state.ackAllUpTo.push(allUpTo === true);
+ }
+ nackAll(requeue: boolean) {
+ state.nackAllRequeue.push(requeue);
+ }
+ async close() {
+ this.closeCalls++;
+ if (state.checkQueueError) {
+ throw new Error('Channel already closed');
+ }
+ }
+ }
+ class FakeConnection extends Emitter {
+ async createChannel() {
+ return new FakeChannel();
+ }
+ async createConfirmChannel() {
+ return new FakeChannel();
+ }
+ async close() {
+ return;
+ }
+ }
+ const connect = async (uri: string) => {
+ state.uris.push(uri);
+ return new FakeConnection();
+ };
+ return { default: { connect }, connect };
+});
+
+import { rabbitmqCommon } from '../src/lib/common';
+import { messageReceived } from '../src/lib/triggers/message-received';
+
+const auth: TestAuth = {
+ host: 'broker.local',
+ username: 'ap user',
+ password: 'p@ss:w/rd#1',
+ port: 5672,
+ vhost: '/',
+ useTls: false,
+ managementUrl: undefined,
+};
+
+function message(text: string) {
+ return {
+ content: Buffer.from(text),
+ properties: { headers: {} },
+ fields: { deliveryTag: 1, redelivered: false, exchange: '', routingKey: 'q' },
+ };
+}
+
+function triggerContext() {
+ return { auth: { props: auth }, propsValue: { queue: 'q', maxMessagesPerPoll: 10 } };
+}
+
+beforeEach(() => {
+ state.uris = [];
+ state.queue = [];
+ state.acked = 0;
+ state.ackAllUpTo = [];
+ state.nackAllRequeue = [];
+ state.checkQueueError = undefined;
+ vi.unstubAllGlobals();
+});
+
+describe('connection URI', () => {
+ it('encodes username, password and vhost', async () => {
+ await rabbitmqCommon.withChannel({ auth, fn: async () => null });
+ expect(state.uris[0]).toBe('amqp://ap%20user:p%40ss%3Aw%2Frd%[email protected]:5672/%2F');
+ });
+
+ it('uses amqps and no vhost path when TLS on and vhost empty', async () => {
+ await rabbitmqCommon.withChannel({ auth: { ...auth, useTls: true, vhost: '', port: 5671 }, fn: async () => null });
+ expect(state.uris[0]).toBe('amqps://ap%20user:p%40ss%3Aw%2Frd%[email protected]:5671');
+ });
+});
+
+describe('channel error handling', () => {
+ it('turns a 404 channel error event into a clean message', async () => {
+ state.checkQueueError = "Channel closed by server: 404 (NOT-FOUND) with message \"NOT_FOUND - no queue 'no-such-queue' in vhost '/'\"";
+ await expect(
+ rabbitmqCommon.withChannel({ auth, fn: (channel) => channel.checkQueue('no-such-queue') }),
+ ).rejects.toThrow('Queue "no-such-queue" does not exist in vhost "/".');
+ });
+
+ it('maps a missing exchange message', () => {
+ const error = rabbitmqCommon.toPieceError(new Error("NOT_FOUND - no exchange 'ex' in vhost 'prod'"));
+ expect(error.message).toBe('Exchange "ex" does not exist in vhost "prod".');
+ });
+});
+
+describe('message received trigger', () => {
+ it('test() requeues messages instead of acking them', async () => {
+ state.queue = [message('{"a":1}'), message('plain text')];
+ const items = await messageReceived.test(fakeContext());
+ expect(items).toHaveLength(2);
+ expect(state.acked).toBe(0);
+ expect(state.nackAllRequeue).toEqual([true]);
+ });
+
+ it('run() acks the batch once and keeps non-JSON bodies as text', async () => {
+ state.queue = [message('{"a":1}'), message('plain text')];
+ const items = await messageReceived.run(fakeContext());
+ expect(state.acked).toBe(1);
+ expect(state.ackAllUpTo).toEqual([true]);
+ expect(state.nackAllRequeue).toEqual([]);
+ expect(items).toEqual([{ a: 1 }, 'plain text']);
+ });
+
+ it('run() emits a JSON message as the parsed object without a content wrapper', async () => {
+ state.queue = [message('{"orderId":"A-1001","status":"created"}')];
+ const items = await messageReceived.run(fakeContext());
+ expect(items).toEqual([{ orderId: 'A-1001', status: 'created' }]);
+ });
+});
+
+describe('managementRequest', () => {
+ it('fails clearly when the management URL is missing', async () => {
+ await expect(rabbitmqCommon.managementRequest({ auth, path: '/queues/%2F' })).rejects.toThrow(
+ 'Set "Management API URL" in the connection',
+ );
+ });
+
+ it('throws status and responseBody without credentials on non-2xx', async () => {
+ const fetchMock = vi.fn(async () => new Response('{"error":"not_authorised"}', { status: 401 }));
+ vi.stubGlobal('fetch', fetchMock);
+ const error = await rabbitmqCommon
+ .managementRequest({ auth: { ...auth, managementUrl: 'http://localhost:15672/' }, path: '/queues/%2F?columns=name' })
+ .catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(Error);
+ expect(error).toMatchObject({ status: 401, responseBody: '{"error":"not_authorised"}' });
+ const serialized = JSON.stringify({ ...Object(error), message: String(error) });
+ expect(serialized).not.toContain(auth.password);
+ expect(serialized).not.toContain(Buffer.from(`${auth.username}:${auth.password}`).toString('base64'));
+ expect(fetchMock).toHaveBeenCalledWith('http://localhost:15672/api/queues/%2F?columns=name', expect.anything());
+ });
+});
+
+function fakeContext(): Parameters<typeof messageReceived.run>[0] {
+ const ctx = triggerContext();
+ return Object.create(null, {
+ auth: { value: ctx.auth, enumerable: true },
+ propsValue: { value: ctx.propsValue, enumerable: true },
+ });
+}
+
+type FakeMessage = { content: Buffer; properties: Record<string, unknown>; fields: Record<string, unknown> };
+
+type FakeState = {
+ uris: string[];
+ queue: FakeMessage[];
+ acked: number;
+ ackAllUpTo: boolean[];
+ nackAllRequeue: boolean[];
+ checkQueueError: string | undefined;
+};
+
+type TestAuth = {
+ host: string;
+ username: string;
+ password: string;
+ port: number;
+ vhost: string;
+ useTls: boolean;
+ managementUrl: string | undefined;
+};
diff --git a/packages/pieces/community/rabbitmq/vitest.config.ts b/packages/pieces/community/rabbitmq/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/rabbitmq/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})