Guide · Amazon MQ · Managed Messaging

Amazon MQ for MCP Servers — Managed Message Broker Setup, Protocols, and Async Tool Dispatch

Amazon MQ is a managed message broker service for Apache ActiveMQ and RabbitMQ. For MCP server developers, it solves a specific production problem: some tool executions take seconds or minutes, but the MCP protocol expects tool calls to complete within a reasonable response window. By dispatching long-running work to a message queue and polling for results, you decouple the MCP tool handler from the underlying computation. This guide covers Amazon MQ broker creation, protocol selection, security configuration, and the patterns for wiring it into MCP tool handlers.

TL;DR

Amazon MQ brokers come in two engine types: ActiveMQ (single-instance or active/standby HA) and RabbitMQ (single-instance or cluster). ActiveMQ supports OpenWire, STOMP, AMQP 1.0, MQTT, and WebSocket; RabbitMQ supports AMQP 0-9-1 and its management HTTP API. Create brokers with CreateBrokerCommand from @aws-sdk/client-mq — the broker endpoint and credentials are returned in DescribeBrokerCommand response. Connect via VPC private endpoints; never expose broker ports to the internet. For async MCP tool dispatch, publish a task message on tool entry, return a pending handle to the calling agent, and implement a poll-or-notify completion mechanism. See the active/standby HA guide for failover patterns.

Why message brokers belong in MCP server architectures

The standard MCP tool call model is synchronous: the client sends a tools/call request and blocks until the server returns a result. This works well for fast operations — database queries, API calls, file reads — where completion happens in under a few seconds. It breaks down for operations that take minutes: document generation, video transcoding, batch data processing, model training jobs, PDF report compilation.

The problem is not just latency. Long-held HTTP connections consume server file descriptors and memory. Network proxies time out. Load balancers close idle connections. Clients that hold a connection for 90 seconds to wait for a result are fragile in any cloud environment with intermediate proxies.

Message brokers solve this with a producer/consumer decoupling pattern. The MCP tool handler publishes a task message to a queue and immediately returns a job ID. The actual work runs in a separate consumer process. The calling agent polls a status-check tool to retrieve the result when ready. This pattern keeps the MCP server responsive, makes long-running work retryable, and lets you scale consumers independently of the MCP server instances.

Amazon MQ is the managed option for teams already running ActiveMQ or RabbitMQ workloads. It handles broker provisioning, patching, storage management, and cross-AZ replication — the operational overhead that makes self-hosting a broker cluster expensive. If you are starting fresh without an existing broker technology preference, consider SQS first (it has lower operational overhead and no connection management). But if your stack already uses ActiveMQ or RabbitMQ, Amazon MQ lets you lift and shift with minimal application changes.

Broker engine choice: ActiveMQ vs RabbitMQ

The engine choice determines the protocol, client library, and feature set available to your MCP server. The two engines are architecturally different and are not interchangeable after creation:

AttributeActiveMQRabbitMQ
Supported protocolsOpenWire, STOMP, AMQP 1.0, MQTT 3.1, WebSocketAMQP 0-9-1 only (plus management HTTP API)
HA deploymentActive/standby (single-AZ failover)3-node cluster (multi-AZ quorum)
Message routingQueues and topics (pub/sub)Exchanges → bindings → queues (highly flexible)
Message modelJMS-compatible (Message selectors, XA transactions)AMQP with publisher confirms and consumer acks
Node.js clientstompit, amqplib (AMQP 1.0 partial), activemq-stompamqplib, amqp-connection-manager
Admin APIWeb console + JMXManagement HTTP API (GET /api/queues etc.)
Best forJMS legacy, complex routing selectors, MQTT IoT devicesModern AMQP workloads, flexible fan-out routing, teams already on RabbitMQ

For new MCP server projects, RabbitMQ on Amazon MQ is the cleaner choice: AMQP 0-9-1 is well-supported by amqplib, the exchange/binding model is expressive for routing tool results to specific reply queues, and the management API makes monitoring queue depths straightforward. Use ActiveMQ if your existing codebase already depends on it or you need MQTT for IoT device input.

IAM permissions for Amazon MQ management

The Amazon MQ AWS SDK is for control-plane operations: creating and describing brokers, managing users, rotating credentials. The actual message send/receive happens over the broker protocol (AMQP/STOMP/OpenWire), not through IAM-signed API calls. This means your MCP server's execution role needs two distinct permission sets:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AmazonMQControlPlane",
      "Effect": "Allow",
      "Action": [
        "mq:DescribeBroker",
        "mq:ListBrokers",
        "mq:DescribeUser",
        "mq:ListUsers"
      ],
      "Resource": "arn:aws:mq:us-east-1:123456789012:broker:my-mcp-broker:*"
    },
    {
      "Sid": "SecretsForBrokerCredentials",
      "Effect": "Allow",
      "Action": [
        "secretsmanager:GetSecretValue"
      ],
      "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:mcp/broker/*"
    }
  ]
}

The mq:CreateBroker and mq:DeleteBroker permissions belong in a separate provisioning role, not in the MCP server runtime role. Keep the runtime role read-only on the control plane — it only needs to look up broker endpoints and retrieve credentials from Secrets Manager.

Broker authentication uses native credentials (a username and password configured on the broker), not IAM. Store these credentials in Secrets Manager and retrieve them at startup. Never hardcode broker passwords in environment variables or code.

Creating an Amazon MQ broker with the AWS SDK

Use @aws-sdk/client-mq for broker lifecycle management. Creating a broker is a long-running async operation — the broker enters a CREATION_IN_PROGRESS state and takes 5–15 minutes to reach RUNNING:

import { MqClient, CreateBrokerCommand, DescribeBrokerCommand } from "@aws-sdk/client-mq";

const mq = new MqClient({ region: "us-east-1" });

// Create a single-instance RabbitMQ broker for development
const { BrokerId } = await mq.send(new CreateBrokerCommand({
  BrokerName: "mcp-tools-broker",
  EngineType: "RABBITMQ",
  EngineVersion: "3.13",
  HostInstanceType: "mq.m5.large",
  DeploymentMode: "SINGLE_INSTANCE",  // Use CLUSTER_MULTI_AZ for production
  PubliclyAccessible: false,           // Always false — connect via VPC only
  SubnetIds: ["subnet-0abc123def456789"],
  SecurityGroups: ["sg-0mcp1234broker56"],
  Users: [
    {
      Username: "mcp-service",
      Password: process.env.BROKER_PASSWORD,  // 12-250 chars, no commas
      Groups: []  // RabbitMQ virtual host membership managed separately
    }
  ],
  Logs: {
    General: true  // Enable CloudWatch log delivery
  },
  Tags: {
    Service: "mcp-server",
    Environment: "production"
  }
}));

console.log(`Broker creation started: ${BrokerId}`);

// Poll until RUNNING (typically 5-15 minutes)
async function waitForBroker(brokerId, maxWaitMs = 900000) {
  const start = Date.now();
  while (Date.now() - start < maxWaitMs) {
    const { BrokerState, BrokerInstances } = await mq.send(
      new DescribeBrokerCommand({ BrokerId: brokerId })
    );
    console.log(`Broker state: ${BrokerState}`);
    if (BrokerState === "RUNNING") {
      return BrokerInstances;
    }
    if (BrokerState === "CREATION_FAILED") {
      throw new Error(`Broker creation failed for ${brokerId}`);
    }
    await new Promise(r => setTimeout(r, 30000));  // Poll every 30s
  }
  throw new Error("Broker creation timed out");
}

const instances = await waitForBroker(BrokerId);
console.log("AMQP endpoint:", instances[0].Endpoints.find(e => e.startsWith("amqps://")));

For production, use DeploymentMode: "CLUSTER_MULTI_AZ" for RabbitMQ — this creates a 3-node cluster across availability zones. See the active/standby HA guide for ActiveMQ's ACTIVE_STANDBY_MULTI_AZ mode and the failover URI patterns that come with it.

Network access: VPC, security groups, and private endpoints

Amazon MQ brokers run inside a VPC and communicate over broker-protocol ports. Never set PubliclyAccessible: true in production — this exposes AMQP, STOMP, and the management console to the internet. Configure access through security group rules:

// Broker security group: allow inbound from MCP server instances only
// AMQP:    5671 (TLS) for RabbitMQ
// AMQP:    5671 (TLS) for ActiveMQ  
// STOMP:   61614 (TLS) for ActiveMQ
// OpenWire: 61617 (TLS) for ActiveMQ
// Web console: 443 (HTTPS) for both engines

// In your CDK/CloudFormation or Terraform, the broker security group ingress:
// { protocol: "tcp", port: 5671, source: mcpServerSecurityGroup }
// { protocol: "tcp", port: 443, source: bastionSecurityGroup }  // console access

The broker endpoint is an AMQP URI in the form amqps://broker-id.mq.region.amazonaws.com:5671. Retrieve it programmatically from DescribeBrokerCommand at MCP server startup rather than hardcoding it in environment variables — broker endpoints can change after maintenance events:

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

async function getBrokerConfig(brokerId: string) {
  const mq = new MqClient({ region: process.env.AWS_REGION });
  const sm = new SecretsManagerClient({ region: process.env.AWS_REGION });

  const [broker, secret] = await Promise.all([
    mq.send(new DescribeBrokerCommand({ BrokerId: brokerId })),
    sm.send(new GetSecretValueCommand({ SecretId: "mcp/broker/credentials" }))
  ]);

  const amqpsEndpoint = broker.BrokerInstances
    .flatMap(i => i.Endpoints)
    .find(e => e.startsWith("amqps://"));

  if (!amqpsEndpoint) throw new Error("No AMQPS endpoint found for broker");

  const { username, password } = JSON.parse(secret.SecretString);

  return {
    url: amqpsEndpoint,
    username,
    password
  };
}

For cross-VPC access — when your MCP server runs in a different VPC than the broker — use VPC peering or AWS PrivateLink. Amazon MQ does not currently support VPC endpoints (Interface Endpoints) natively, so VPC peering is the standard approach for multi-VPC topologies.

Async tool dispatch pattern for MCP servers

The core pattern for long-running tools: on tool entry, publish a task to the broker queue and return a correlation ID; a separate worker process consumes the queue; a status-check tool polls for the result. This keeps the MCP server's connection handler free while work runs in background consumers.

import amqplib from "amqplib";
import { randomUUID } from "crypto";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

let channel: amqplib.Channel;
const pendingResults = new Map();

async function initBrokerChannel(brokerUrl: string, username: string, password: string) {
  const conn = await amqplib.connect({
    hostname: new URL(brokerUrl).hostname,
    port: 5671,
    username,
    password,
    protocol: "amqps",
    vhost: "/"
  });
  channel = await conn.createChannel();

  // Task queue: durable, survives broker restart
  await channel.assertQueue("mcp-tasks", { durable: true });

  // Result queue: exclusive, auto-delete for this server instance
  const { queue: replyQueue } = await channel.assertQueue("", {
    exclusive: true,
    autoDelete: true
  });

  // Consume results posted back by workers
  channel.consume(replyQueue, (msg) => {
    if (!msg) return;
    const correlationId = msg.properties.correlationId;
    const result = JSON.parse(msg.content.toString());
    const pending = pendingResults.get(correlationId);
    if (pending) {
      clearTimeout(pending.timer);
      pendingResults.delete(correlationId);
      pending.resolve(result);
    }
    channel.ack(msg);
  }, { noAck: false });

  return replyQueue;
}

async function dispatchTask(task: object, replyQueue: string, timeoutMs = 300000): Promise {
  const correlationId = randomUUID();

  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      pendingResults.delete(correlationId);
      reject(new Error(`Task ${correlationId} timed out after ${timeoutMs}ms`));
    }, timeoutMs);

    pendingResults.set(correlationId, { resolve, timer });

    channel.sendToQueue(
      "mcp-tasks",
      Buffer.from(JSON.stringify(task)),
      {
        correlationId,
        replyTo: replyQueue,
        persistent: true,  // Survive broker restart
        contentType: "application/json"
      }
    );
  });
}

// MCP server wiring
const server = new McpServer({ name: "async-tools", version: "1.0.0" });

server.tool(
  "generate_report",
  "Generate a comprehensive PDF report from data sources. Takes 30-120 seconds.",
  {
    reportType: z.enum(["financial", "operational", "compliance"]),
    dateRange: z.object({
      start: z.string().describe("ISO 8601 date"),
      end: z.string().describe("ISO 8601 date")
    }),
    format: z.enum(["pdf", "xlsx"]).default("pdf")
  },
  async (params, { replyQueue }) => {
    const result = await dispatchTask(
      { type: "generate_report", params },
      replyQueue,
      180000  // 3-minute timeout for report generation
    );

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

		

For tools with unpredictable completion times (exceeding a few minutes), the timeout-based approach above becomes fragile. In that case, return the correlation ID immediately and implement a separate get_task_result tool that the agent can poll. Store task results in DynamoDB or ElastiCache with TTL — the worker writes the result, the status tool reads it. This is cleaner than holding connections open for multi-minute operations.

Monitoring broker health from MCP server startup

Include a broker health check in your MCP server's startup sequence. A tool server that connects to a downed broker will fail silently — tool calls will timeout rather than return a clear error. Early detection prevents this:

import { MqClient, DescribeBrokerCommand } from "@aws-sdk/client-mq";

async function assertBrokerHealthy(brokerId: string) {
  const mq = new MqClient({ region: process.env.AWS_REGION });
  const broker = await mq.send(new DescribeBrokerCommand({ BrokerId: brokerId }));

  if (broker.BrokerState !== "RUNNING") {
    throw new Error(`Broker ${brokerId} is in state ${broker.BrokerState}, expected RUNNING`);
  }

  // Check pending maintenance that could cause a reboot
  if (broker.PendingSecurityGroups || broker.PendingEngineVersion) {
    console.warn(`Broker ${brokerId} has pending changes — expect maintenance window`);
  }

  return broker.BrokerInstances.flatMap(i => i.Endpoints);
}

// At startup:
const endpoints = await assertBrokerHealthy(process.env.BROKER_ID);
const replyQueue = await initBrokerChannel(endpoints[0], username, password);

For production health monitoring, track broker queue depth and consumer count using the RabbitMQ management API or CloudWatch metrics published by Amazon MQ. Set CloudWatch alarms on AmazonMQ/MessageCount and AmazonMQ/ConsumerCount to detect queue backlog and consumer failure before your MCP server clients experience slowdowns. AliveMCP can monitor your MCP server endpoint health with alerting to Slack and email when the tool server becomes unreachable.

Common failures and fixes

Error / symptomCauseFix
Connection refused on port 5671 Security group does not allow inbound 5671 from MCP server's security group, or broker is not yet RUNNING Check DescribeBroker for RUNNING state; verify security group inbound rule allows TCP 5671 from the MCP server's SG
Authentication failure (ACCESS_REFUSED) Wrong username/password, or RabbitMQ user lacks / virtual host permission Use DescribeUser to verify the user exists; for RabbitMQ, set virtual host permissions via management API; rotate credential in Secrets Manager and redeploy
Broker state stays CREATION_IN_PROGRESS for 30+ minutes VPC subnet has insufficient IP space, security group has restrictive outbound rules, or service quota exceeded Verify subnet has at least 5 free IPs; allow all outbound traffic on the broker SG (or at least HTTPS to AWS endpoints); check Service Quotas for max brokers per region
Messages lost after broker restart Queue was not declared as durable: true or messages sent without persistent: true Assert queues with durable: true; send messages with deliveryMode: 2 (persistent); for RabbitMQ also enable quorum queues for durability guarantees
High memory alarm, broker stops accepting publishes Consumer lag — messages accumulate faster than consumers process them; broker memory threshold exceeded Scale consumer count; monitor AmazonMQ/MessageCount CloudWatch metric; set consumer prefetch count appropriately (channel.prefetch(10))
TLS handshake failure with Node.js amqplib Node.js SSL verification fails on Amazon MQ's certificate, or wrong port (5672 instead of 5671) Use amqps:// URL scheme; ensure port is 5671 for TLS; Amazon MQ uses a valid ACM-issued certificate — do not disable SSL verification in production

Amazon MQ arc — related guides

This guide covers broker setup and the core async dispatch pattern. The arc continues with engine-specific implementation guides:

  • ActiveMQ on Amazon MQ — queues vs topics, durable subscribers, virtual destinations, OpenWire and STOMP client patterns for Node.js
  • RabbitMQ on Amazon MQ — exchanges and bindings, amqplib publisher confirms, management API for queue metrics, dead-letter exchange patterns
  • Active/standby HA and failover — ActiveMQ active/standby with failover URIs, RabbitMQ cluster deployment, reconnection handling in MCP tool handlers

For monitoring your MCP server's availability when broker-dependent tools go dark, AliveMCP provides uptime and latency monitoring with Slack and email alerting.