Guide · Amazon MQ · ActiveMQ

ActiveMQ on Amazon MQ for MCP Servers — Queues, Topics, Durable Subscribers, and STOMP Client Patterns

Apache ActiveMQ on Amazon MQ gives MCP server developers a managed JMS-compatible broker with five supported protocols: OpenWire, STOMP, AMQP 1.0, MQTT, and WebSocket. Understanding ActiveMQ's destination model — queues for point-to-point, topics for fan-out publish/subscribe — and its virtual destinations feature for combining both patterns is essential for building reliable async tool dispatch systems. This guide covers STOMP and OpenWire client setup in Node.js, durable topic subscriptions, message selector filtering, and virtual topic patterns that make ActiveMQ flexible for multi-consumer MCP tool architectures.

TL;DR

ActiveMQ destinations are either queues (queue://name) for competing consumers — one message delivered to exactly one consumer — or topics (topic://name) for broadcast — each message delivered to all active subscribers. Durable topic subscribers (clientId + subscriptionName) receive messages that arrived while they were disconnected. Virtual topics bridge the two: publish to VirtualTopic.orders, and consumers subscribe to Consumer.serviceA.VirtualTopic.orders — each service gets its own queue-backed copy of the topic stream. Use STOMP (stompit npm package) for simple Node.js clients; OpenWire requires a JVM bridge or the ActiveMQ JavaScript client. For broker setup, see the Amazon MQ overview.

ActiveMQ destination model for MCP tool architectures

ActiveMQ organizes messages into named destinations. The destination type determines delivery semantics, and choosing the wrong type for your use case creates bugs that are difficult to diagnose under load.

Queues implement the competing-consumers pattern. When multiple consumers connect to the same queue, ActiveMQ distributes messages among them in round-robin order. Each message is consumed by exactly one consumer. This is the right model for task dispatch: multiple worker processes share a queue://mcp.tasks destination and each worker processes one task at a time. Failed tasks are nacked and either requeued or sent to a dead-letter queue.

Topics implement broadcast. Every active subscriber receives a copy of every message. This is the right model for event notification: when a tool execution completes, publish a completion event to topic://mcp.tool.completed and every interested subscriber (dashboard, audit log, another tool handler) receives it simultaneously. The critical limitation: non-durable topic subscribers miss messages that arrive while they are disconnected.

Virtual topics combine the benefits of both. A producer publishes to a virtual topic (VirtualTopic.taskResults). Each consumer subscribes to its own queue-backed copy (Consumer.reportingService.VirtualTopic.taskResults). Every consumer gets every message, but messages are durably queued per-consumer — so if the reporting service restarts, it picks up missed messages from its queue. This pattern is ideal for MCP tool result distribution: multiple downstream services independently consume tool results without racing against each other or missing events during restarts.

STOMP client setup for Node.js MCP servers

STOMP (Simple Text Oriented Message Protocol) is the easiest ActiveMQ protocol to use from Node.js. The stompit package implements STOMP 1.0, 1.1, and 1.2 and handles reconnection natively. Amazon MQ requires TLS on port 61614 for STOMP:

import stompit from "stompit";
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";

async function createStompChannel(): Promise {
  const sm = new SecretsManagerClient({ region: process.env.AWS_REGION });
  const { SecretString } = await sm.send(new GetSecretValueCommand({
    SecretId: "mcp/broker/activemq-credentials"
  }));
  const { username, password, host } = JSON.parse(SecretString!);

  return new Promise((resolve, reject) => {
    // stompit.connect handles TLS when ssl: true
    stompit.connect(
      {
        host,
        port: 61614,
        ssl: true,
        connectHeaders: {
          host: "/",
          login: username,
          passcode: password,
          "heart-beat": "10000,10000",   // 10s heartbeat in both directions
          "accept-version": "1.1,1.2"
        }
      },
      (err, client) => {
        if (err) return reject(err);

        // Channel wraps the client with queue-based send buffering
        const channel = stompit.createChannel(client);
        resolve(channel);
      }
    );
  });
}

// Send a task message to a queue
async function sendTask(channel: stompit.Channel, task: object): Promise {
  await new Promise((resolve, reject) => {
    channel.send(
      {
        destination: "/queue/mcp.tasks",
        "content-type": "application/json",
        persistent: "true",           // Survive broker restart
        priority: "5"                 // 0-9, higher = higher priority
      },
      (err) => err ? reject(err) : resolve(),
      JSON.stringify(task)
    );
  });
}

// Subscribe to a queue for task processing
async function consumeTasks(channel: stompit.Channel, handler: (task: object) => Promise) {
  await new Promise((resolve, reject) => {
    channel.subscribe(
      {
        destination: "/queue/mcp.tasks",
        ack: "client-individual",    // Explicit ack required per message
        prefetch: "10"               // Max 10 unacked messages in flight
      },
      async (err, message, unsubscribe) => {
        if (err) return reject(err);

        const body = await new Promise((res, rej) => {
          let data = "";
          message.on("data", chunk => { data += chunk; });
          message.on("end", () => res(data));
          message.on("error", rej);
        });

        try {
          await handler(JSON.parse(body));
          message.ack();             // Acknowledge successful processing
        } catch (processingError) {
          console.error("Task processing failed:", processingError);
          message.nack();            // Nack → requeue (up to max redelivery count)
        }
      }
    );
    resolve();
  });
}

The ack: "client-individual" mode is critical for reliable processing: messages are only removed from the queue after your handler explicitly calls message.ack(). With ack: "auto" (the default), messages are acknowledged on delivery — if your handler throws an exception before completing the work, the message is lost. Always use client-individual for task queues.

Durable topic subscriptions for event streams

Non-durable topic subscribers miss messages that arrive while they are disconnected. For MCP tool result notifications that must be delivered even when the subscriber restarts, use durable subscriptions. A durable subscriber is identified by a client-id (set in the CONNECT frame) and a subscription-name (set in the SUBSCRIBE frame). ActiveMQ retains messages for durable subscribers while they are offline:

// Durable subscription requires a unique client-id per subscriber instance
// (not per connection — it persists across reconnections)
stompit.connect(
  {
    host,
    port: 61614,
    ssl: true,
    connectHeaders: {
      host: "/",
      login: username,
      passcode: password,
      "client-id": "mcp-audit-service"   // Unique per logical subscriber, not per process
    }
  },
  (err, client) => {
    const channel = stompit.createChannel(client);

    // Subscribe with a durable subscription name
    channel.subscribe(
      {
        destination: "/topic/mcp.tool.completed",
        ack: "client-individual",
        "subscription-name": "audit-log-subscription",   // Persistent subscription name
        "durable-subscriber-name": "audit-log-subscription"  // ActiveMQ header
      },
      async (err, message) => {
        if (err) throw err;
        const body = await readMessage(message);
        await writeAuditLog(JSON.parse(body));
        message.ack();
      }
    );
  }
);

Durable subscriptions have an important constraint: a given client-id can only have one active connection to the broker at a time. If you scale your audit service to three instances, each needs a distinct client-id (e.g., mcp-audit-service-1, mcp-audit-service-2). But then each instance holds its own durable subscription and each receives every message — which may or may not be what you want. For competing-consumer durability across multiple instances of the same logical service, use virtual topics instead.

Virtual topics for durable fan-out

Virtual topics are ActiveMQ's solution to the "durable fan-out to multiple independent consumers" problem. The pattern uses naming conventions rather than explicit configuration: any queue named Consumer.<subscriberName>.VirtualTopic.<topicName> automatically receives copies of messages published to VirtualTopic.<topicName>.

// Producer: publish to the virtual topic (looks like a topic to the publisher)
channel.send(
  {
    destination: "/topic/VirtualTopic.tool.results",   // "topic" prefix for publisher
    "content-type": "application/json",
    persistent: "true"
  },
  (err) => { if (err) throw err; },
  JSON.stringify({ toolName: "generate_report", jobId: "abc123", status: "complete", result: {...} })
);

// Consumer A (reporting service): subscribes to its own queue copy
channel.subscribe(
  {
    destination: "/queue/Consumer.reporting.VirtualTopic.tool.results",
    ack: "client-individual"
  },
  async (err, message) => {
    const body = await readMessage(message);
    await updateReportDashboard(JSON.parse(body));
    message.ack();
  }
);

// Consumer B (audit service): subscribes to its own independent queue copy
channel.subscribe(
  {
    destination: "/queue/Consumer.audit.VirtualTopic.tool.results",
    ack: "client-individual"
  },
  async (err, message) => {
    const body = await readMessage(message);
    await appendAuditLog(JSON.parse(body));
    message.ack();
  }
);

Both consumers receive every message published to VirtualTopic.tool.results, but their queues are independent — the reporting service's queue depth does not affect the audit service's queue depth. Each consumer can scale to multiple instances using the competing-consumers pattern against its own named queue. Messages persist in each consumer's queue until acknowledged, so restarts don't cause message loss.

Virtual topics require no broker-side configuration in Amazon MQ — the naming convention is handled by the broker automatically. The only requirement is that the ActiveMQ configuration (the broker's activemq.xml) has virtual topic support enabled, which is the default on Amazon MQ. Confirm by checking the destination advisory or by publishing a test message and verifying both consumer queues receive it.

Message selectors for routing in MCP tool handlers

ActiveMQ supports JMS message selectors — SQL-92-like expressions evaluated against message headers. Selectors let a single queue serve multiple consumer types without routing logic in your code. This is useful when you have one task queue feeding different worker types that specialize in specific tool types:

// Producer: set headers for selector routing
channel.send(
  {
    destination: "/queue/mcp.tasks",
    "content-type": "application/json",
    persistent: "true",
    toolType: "document_generation",    // Custom header for selector routing
    priority_tier: "high"
  },
  (err) => { if (err) throw err; },
  JSON.stringify({ toolName: "generate_report", params: {...} })
);

// Consumer for document generation tasks only
channel.subscribe(
  {
    destination: "/queue/mcp.tasks",
    ack: "client-individual",
    selector: "toolType = 'document_generation'"    // JMS message selector
  },
  async (err, message) => {
    // Only receives messages with toolType = 'document_generation' header
    const body = await readMessage(message);
    await generateDocument(JSON.parse(body));
    message.ack();
  }
);

// Consumer for data processing tasks only
channel.subscribe(
  {
    destination: "/queue/mcp.tasks",
    ack: "client-individual",
    selector: "toolType = 'data_processing' AND priority_tier = 'high'"
  },
  async (err, message) => {
    const body = await readMessage(message);
    await processData(JSON.parse(body));
    message.ack();
  }
);

Selectors are evaluated at the broker before delivery, so non-matching messages stay in the queue for other consumers. This avoids the "fetch and discard" anti-pattern where every consumer receives every message and discards those it cannot handle. However, mismatched selectors create ghost messages — tasks that no consumer selects pile up indefinitely. Monitor queue depth per destination to detect unrouted messages.

Dead-letter queue handling for failed MCP tasks

When a message is nacked or reaches its maximum redelivery count, ActiveMQ moves it to a dead-letter destination. By default, all dead-lettered messages go to ActiveMQ.DLQ. For MCP tool architectures, configure per-destination DLQs so failed report generation tasks are separated from failed data processing tasks:

// ActiveMQ broker XML configuration (set via Amazon MQ configuration resource)
// This is set in the broker's activemq.xml, not in application code.
// Amazon MQ lets you specify a custom broker configuration XML at creation time.

/*
<destinationPolicy>
  <policyMap>
    <policyEntries>
      <policyEntry queue="mcp.tasks.>" producerFlowControl="true">
        <deadLetterStrategy>
          <individualDeadLetterStrategy
            queuePrefix="DLQ."
            useQueueForQueueMessages="true"
            processNonPersistent="true"
            processExpired="true"
          />
        </deadLetterStrategy>
        <redeliveryPlugin fallbackToDeadLetter="true">
          <redeliveryPolicyMap>
            <redeliveryPolicyEntries>
              <redeliveryPolicy
                queue="mcp.tasks.*"
                maximumRedeliveries="3"
                redeliveryDelay="5000"
                backOffMultiplier="2"
                useExponentialBackOff="true"
              />
            </redeliveryPolicyEntries>
          </redeliveryPolicyMap>
        </redeliveryPlugin>
      </policyEntry>
    </policyEntries>
  </policyMap>
</destinationPolicy>
*/

// Application-level DLQ processor: MCP tool for replaying failed tasks
server.tool(
  "list_failed_tasks",
  "List messages in the dead-letter queue for a task destination.",
  { queueName: z.string().describe("Original task queue name, e.g. 'mcp.tasks.reports'") },
  async ({ queueName }) => {
    // Subscribe to the DLQ for this queue with a short browse timeout
    const dlqName = `DLQ.${queueName}`;
    const messages = [];
    // Use STOMP SUBSCRIBE with browse: "true" header to non-destructively read DLQ
    // then allow operator to decide: replay or discard
    return { content: [{ type: "text", text: JSON.stringify({ dlq: dlqName, count: messages.length }) }] };
  }
);

Redelivery with exponential backoff (3 retries, starting at 5 seconds) is the standard pattern. The individualDeadLetterStrategy with queuePrefix: "DLQ." creates a DLQ.mcp.tasks destination for dead messages from the mcp.tasks queue, keeping dead letters from different task types separated for diagnosis.

Related guides in this arc

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