Guide · Amazon MQ · RabbitMQ

RabbitMQ on Amazon MQ for MCP Servers — Exchanges, Bindings, Publisher Confirms, and Management API

RabbitMQ on Amazon MQ uses AMQP 0-9-1, a binary protocol with a richer routing model than most message queue services. Instead of sending messages directly to queues, producers publish to exchanges, and exchanges route to queues based on bindings. This indirection enables flexible routing patterns — direct, topic (wildcard), fanout, and headers matching — without changing producer code. This guide covers the exchange and binding model for MCP tool architectures, the amqplib client patterns for Node.js including publisher confirms, dead-letter exchange configuration, quorum queues for durability, and the management HTTP API for monitoring queue depths from MCP tools.

TL;DR

All RabbitMQ messaging flows through an exchange first. Use a direct exchange for task queues (routing key = queue name), a topic exchange with #/* wildcards for event routing, and a fanout exchange to broadcast to all bound queues. Enable publisher confirms (channel.confirmSelect()) to get broker-level acknowledgement of every message persisted. Configure a dead-letter exchange (DLX) per queue so nacked or expired messages flow to a separate DLQ for inspection. Use quorum queues (x-queue-type: quorum) for high-durability workloads on Amazon MQ cluster deployments. Query queue depths via the management API at https://broker-endpoint:443/api/queues using HTTP Basic Auth. For broker creation and VPC setup, see the Amazon MQ overview.

Exchange types and when to use each

RabbitMQ's exchange model separates the publishing decision (producer sends to exchange X with routing key K) from the routing decision (exchange delivers to queues whose bindings match K). This means you can change routing topology by updating bindings without redeploying producers or consumers.

Exchange typeRouting mechanismMCP tool use case
directMessage routing key must exactly match binding keyTask dispatch: publish with key generate_report, bind a worker queue to that exact key
topicRouting key matched with * (one word) and # (zero or more words) wildcardsEvent routing: publish with key tool.report.completed, bind analytics queue to tool.# and billing queue to tool.*.completed
fanoutMessage delivered to all bound queues regardless of routing keyBroadcast: publish a system event and deliver to audit, dashboard, and notification queues simultaneously
headersMessage headers matched against binding header table (x-match: all or any)Fine-grained routing: route high-priority tool calls to premium workers based on priority: high header

The default exchange is a special pre-declared direct exchange with an empty name. Queues are automatically bound to the default exchange with their queue name as the routing key. This means you can publish directly to a queue by name without declaring an explicit exchange — but it bypasses the routing model and limits flexibility. For production MCP tool architectures, always declare and use named exchanges.

amqplib connection and channel setup

The amqplib package is the standard AMQP 0-9-1 client for Node.js. Amazon MQ requires AMQPS (TLS) on port 5671. Use amqp-connection-manager as a wrapper for automatic reconnection — bare amqplib does not reconnect after network interruptions:

import amqp from "amqp-connection-manager";
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
import type { ConfirmChannel } from "amqplib";

async function getBrokerUrl(): Promise {
  const sm = new SecretsManagerClient({ region: process.env.AWS_REGION });
  const { SecretString } = await sm.send(new GetSecretValueCommand({
    SecretId: "mcp/broker/rabbitmq-credentials"
  }));
  const { username, password, host } = JSON.parse(SecretString!);
  return `amqps://${username}:${encodeURIComponent(password)}@${host}:5671`;
}

let channelWrapper: amqp.ChannelWrapper;

async function initRabbitMQ() {
  const url = await getBrokerUrl();

  const connection = amqp.connect([url], {
    reconnectTimeInSeconds: 5,
    heartbeatIntervalInSeconds: 10
  });

  connection.on("connect", () => console.log("RabbitMQ connected"));
  connection.on("disconnect", ({ err }) => console.error("RabbitMQ disconnected:", err?.message));
  connection.on("connectFailed", ({ err }) => console.error("RabbitMQ connect failed:", err?.message));

  // channelWrapper auto-recreates channel on reconnection and replays setup
  channelWrapper = connection.createChannel({
    json: false,
    setup: async (channel: ConfirmChannel) => {
      // Exchanges
      await channel.assertExchange("mcp.tasks", "direct", { durable: true });
      await channel.assertExchange("mcp.events", "topic", { durable: true });
      await channel.assertExchange("mcp.dlx", "direct", { durable: true });  // Dead-letter exchange

      // Queues with DLX configuration
      await channel.assertQueue("mcp.tasks.reports", {
        durable: true,
        arguments: {
          "x-dead-letter-exchange": "mcp.dlx",
          "x-dead-letter-routing-key": "dlq.reports",
          "x-message-ttl": 1800000,   // 30-minute TTL; expired → DLX
          "x-queue-type": "quorum"    // Quorum queue for durability
        }
      });

      await channel.assertQueue("dlq.reports", {
        durable: true,
        arguments: { "x-queue-type": "classic" }  // DLQ uses classic queue
      });

      // Bindings
      await channel.bindQueue("mcp.tasks.reports", "mcp.tasks", "generate_report");
      await channel.bindQueue("dlq.reports", "mcp.dlx", "dlq.reports");

      // Enable publisher confirms on this channel
      await channel.confirmSelect();

      console.log("RabbitMQ topology asserted");
    }
  });

  return channelWrapper;
}

The amqp-connection-manager channelWrapper.setup() callback runs every time a channel is created or recreated. This means assertExchange, assertQueue, and bindQueue calls run on initial connect and after every reconnect — which is safe because assert operations are idempotent. Never put one-time operations (like publishing a startup message) in the setup callback.

Publisher confirms for reliable task dispatch

Without publisher confirms, amqplib's channel.publish() returns true or false based on the in-memory write buffer — it does not indicate that the broker actually persisted the message. For MCP tool task dispatch, losing a task silently means the agent waits forever for a result that will never come. Publisher confirms solve this by giving a broker-level ack for every published message:

// Publish with confirm (channel must have confirmSelect() called in setup)
async function publishTask(
  exchange: string,
  routingKey: string,
  task: object,
  options: { priority?: number } = {}
): Promise {
  await channelWrapper.publish(
    exchange,
    routingKey,
    Buffer.from(JSON.stringify(task)),
    {
      persistent: true,                    // Message survives broker restart
      contentType: "application/json",
      messageId: randomUUID(),             // For deduplication tracking
      timestamp: Math.floor(Date.now() / 1000),
      headers: {
        "x-retry-count": 0,
        "x-source": "mcp-server"
      },
      priority: options.priority ?? 5      // 0-9; quorum queues support priorities 0-255
    }
  );
  // channelWrapper.publish() returns a Promise that resolves on broker ack
  // and rejects on nack (message rejected by broker, e.g. queue full)
}

// MCP tool handler using confirmed publish
server.tool(
  "queue_report_generation",
  "Queue a report generation task. Returns a job ID for status polling.",
  {
    reportType: z.enum(["financial", "compliance", "operational"]),
    parameters: z.object({}).passthrough()
  },
  async ({ reportType, parameters }) => {
    const jobId = randomUUID();

    try {
      await publishTask("mcp.tasks", "generate_report", {
        jobId,
        reportType,
        parameters,
        queuedAt: new Date().toISOString()
      });
    } catch (err) {
      // Broker nacked the message — queue may be full or exchange not found
      throw new Error(`Failed to queue report task: ${err.message}`);
    }

    return {
      content: [{
        type: "text",
        text: JSON.stringify({ jobId, status: "queued", message: "Use get_task_status to poll for results" })
      }]
    };
  }
);

Publisher confirms have a performance cost: each message publish incurs a broker round-trip for acknowledgement. For high-throughput scenarios, batch confirms — publish multiple messages then wait for all confirms to arrive — are more efficient than waiting for each individual confirm. amqp-connection-manager's publish() method returns a promise that resolves per-message, so you can use Promise.all() for batch confirms.

Dead-letter exchange patterns for failed MCP tasks

RabbitMQ dead-letter exchanges (DLX) route messages that are rejected, nacked without requeue, or expire to a designated dead-letter queue. This provides a safety net for tasks that fail processing — they are preserved for diagnosis and optional replay rather than silently lost.

// Consumer with DLX-aware nacking
channelWrapper.addSetup(async (channel: ConfirmChannel) => {
  // Set prefetch to avoid overwhelming consumers
  await channel.prefetch(5);

  channel.consume("mcp.tasks.reports", async (msg) => {
    if (!msg) return;  // null = consumer cancelled

    const task = JSON.parse(msg.content.toString());
    const retryCount = (msg.properties.headers["x-retry-count"] ?? 0) as number;

    try {
      await generateReport(task);
      channel.ack(msg);                // Success: remove from queue
    } catch (err) {
      console.error(`Report task ${task.jobId} failed (retry ${retryCount}):`, err);

      if (retryCount < 2) {
        // Re-publish with incremented retry count (manual retry with backoff)
        await channelWrapper.publish(
          "mcp.tasks",
          "generate_report",
          msg.content,
          {
            ...msg.properties,
            headers: {
              ...msg.properties.headers,
              "x-retry-count": retryCount + 1,
              "x-last-error": err.message.slice(0, 200)
            }
          }
        );
        channel.ack(msg);              // Ack original; retried copy is in queue
      } else {
        // Max retries exceeded: nack without requeue → flows to DLX
        channel.nack(msg, false, false);
      }
    }
  }, { noAck: false });
});

Nacking with requeue: false sends the message to the queue's configured x-dead-letter-exchange. The DLX then routes it to the DLQ using the x-dead-letter-routing-key. The dead-lettered message preserves the original headers plus a x-death header array added by RabbitMQ, documenting the death reason, count, and original queue — useful for debugging why tasks failed in production.

RabbitMQ management API for queue metrics

Amazon MQ exposes the RabbitMQ management HTTP API at port 443 (HTTPS) on the broker endpoint. Use it from MCP tools to surface queue health metrics — queue depth, consumer count, message rates — without additional CloudWatch setup:

import https from "https";

interface QueueMetrics {
  name: string;
  messages: number;
  consumers: number;
  messageRate: number;
  memoryBytes: number;
}

async function getQueueMetrics(
  brokerHost: string,
  username: string,
  password: string,
  vhost = "%2F"
): Promise {
  const url = `https://${brokerHost}/api/queues/${vhost}`;
  const auth = Buffer.from(`${username}:${password}`).toString("base64");

  const response = await fetch(url, {
    headers: { Authorization: `Basic ${auth}` }
  });

  if (!response.ok) {
    throw new Error(`Management API error: ${response.status} ${await response.text()}`);
  }

  const queues = await response.json();
  return queues.map((q: any) => ({
    name: q.name,
    messages: q.messages ?? 0,
    consumers: q.consumers ?? 0,
    messageRate: q.messages_details?.rate ?? 0,
    memoryBytes: q.memory ?? 0
  }));
}

// MCP tool for broker health inspection
server.tool(
  "get_broker_queue_health",
  "Return current message counts and consumer status for all MCP task queues.",
  {},
  async () => {
    const { host, username, password } = await getBrokerCredentials();
    const queues = await getQueueMetrics(host, username, password);

    // Filter to MCP-relevant queues only
    const mcpQueues = queues.filter(q => q.name.startsWith("mcp.") || q.name.startsWith("dlq."));

    const warnings = mcpQueues
      .filter(q => q.consumers === 0 && q.messages > 0)
      .map(q => `Queue ${q.name} has ${q.messages} messages but 0 consumers`);

    return {
      content: [{
        type: "text",
        text: JSON.stringify({ queues: mcpQueues, warnings })
      }]
    };
  }
);

The management API returns comprehensive queue statistics including memory usage, message rates (publish/deliver/ack/nack per second), consumer utilisation, and idle-since timestamps. For queues with consumers: 0 and growing messages count, your worker processes have crashed — set a CloudWatch alarm or alert through AliveMCP to get notified before the queue depth becomes operationally significant.

Quorum queues for production durability on Amazon MQ cluster

Classic queues in RabbitMQ have known data-loss risks under node failure. Quorum queues use a Raft-based replication protocol to guarantee durability across cluster nodes — a message is only confirmed to the producer after a quorum of nodes have written it. On Amazon MQ's CLUSTER_MULTI_AZ RabbitMQ deployment (3 nodes across AZs), quorum queues provide AZ-failure tolerance for task messages:

// Declare a quorum queue — requires x-queue-type: quorum argument
await channel.assertQueue("mcp.tasks.critical", {
  durable: true,   // Required for quorum queues (non-durable quorum queues are not allowed)
  arguments: {
    "x-queue-type": "quorum",
    "x-quorum-initial-group-size": 3,  // Replicate across all 3 nodes in the cluster
    "x-dead-letter-exchange": "mcp.dlx",
    "x-delivery-limit": 3              // Max redelivery count before DLX routing (replaces nack loop)
  }
});

// Key differences vs classic queues:
// 1. x-delivery-limit replaces manual retry counting — broker tracks delivery count
// 2. priority levels 0-255 supported (classic supports 0-255 too but with memory overhead)
// 3. Consumer cancellation on node failure is automatic — amqp-connection-manager handles reconnect
// 4. Per-message TTL (expiration property) is NOT supported — use x-message-ttl on the queue instead

Quorum queues have restrictions: you cannot change x-queue-type after creation; you cannot use per-message TTL via the expiration property (use queue-level x-message-ttl); and mirrored queue policies (the old HA mechanism) have no effect on quorum queues — quorum queues handle their own replication. Migrate existing classic queues to quorum queues by draining the classic queue and creating a new quorum queue with the same name and bindings.

Related guides in this arc

Monitor your MCP server's availability and tool latency with AliveMCP — Slack and email alerts when your broker-dependent tools stop responding.