Guide · AWS Cloud Map · Service Discovery
AWS Cloud Map DiscoverInstances for MCP Servers — HTTP Namespace Lookup, Health Filtering, and DNS Resolution
AWS Cloud Map's DiscoverInstances API returns the current set of healthy registered instances for a service, with support for custom attribute filtering, health status filtering, and revision-based change detection. Unlike DNS-based discovery (which is limited to 8 A records per MULTIVALUE query and cannot filter on custom attributes), DiscoverInstances returns the full instance payload including all registered attributes — enabling sophisticated routing decisions like load-balancing to instances that support specific MCP tools, routing to instances in a preferred region, or returning only instances running a minimum protocol version. This guide covers the DiscoverInstances call, the HealthStatus filter and its three values, QueryParameters custom attribute matching, DiscoverInstancesRevision for polling-free change detection, DNS resolution for private DNS namespaces, and client-side load balancing patterns. For namespace and service setup, see Cloud Map Overview. For instance registration, see Service Registration and Instances. For ECS integration, see Cloud Map ECS Integration.
TL;DR
DiscoverInstances works for all three namespace types (private DNS, public DNS, HTTP). Always set HealthStatus: "HEALTHY" — the default is "ALL" which includes UNHEALTHY and UNKNOWN instances, causing clients to connect to degraded or unregistered endpoints. Use QueryParameters for exact-match custom attribute filtering; substring matching is not supported. DiscoverInstancesRevision returns only the revision number, not the full instance list — use it in a polling loop to detect changes cheaply, then call DiscoverInstances only when the revision increments. For private DNS namespaces, DNS resolution is an alternative to DiscoverInstances but limited to 8 instances maximum and no custom attribute filtering. The IAM action is servicediscovery:DiscoverInstances.
DiscoverInstances: the basic call
import {
ServiceDiscoveryClient,
DiscoverInstancesCommand,
DiscoverInstancesRevisionCommand,
type HttpInstanceSummary,
} from "@aws-sdk/client-servicediscovery";
const cloudMap = new ServiceDiscoveryClient({ region: process.env.AWS_REGION! });
// Basic discovery: get all HEALTHY MCP server instances
async function discoverMcpServers(
namespaceName: string,
serviceName: string
): Promise<HttpInstanceSummary[]> {
const { Instances } = await cloudMap.send(
new DiscoverInstancesCommand({
NamespaceName: namespaceName, // e.g., "mcp.internal"
ServiceName: serviceName, // e.g., "mcp-server"
// ALWAYS specify HealthStatus — default is "ALL" which includes
// UNHEALTHY and UNKNOWN instances. This is the most common
// DiscoverInstances mistake.
HealthStatus: "HEALTHY",
MaxResults: 100, // default is 100; set explicitly for clarity
})
);
if (!Instances || Instances.length === 0) {
throw new Error(`No healthy MCP server instances found in ${namespaceName}/${serviceName}`);
}
return Instances;
}
// Extract connection info from discovered instance
function getConnectionUrl(instance: HttpInstanceSummary): string {
const ip = instance.Attributes?.["AWS_INSTANCE_IPV4"];
const port = instance.Attributes?.["AWS_INSTANCE_PORT"] ?? "3000";
if (!ip) throw new Error(`Instance ${instance.InstanceId} has no IP`);
return `http://${ip}:${port}`;
}
// Usage
const instances = await discoverMcpServers("mcp.internal", "mcp-server");
const urls = instances.map(getConnectionUrl);
console.log("Available MCP servers:", urls);
// ["http://10.0.1.44:3000", "http://10.0.2.17:3000", "http://10.0.3.8:3000"]
The NamespaceName parameter takes the namespace's DNS name (e.g., "mcp.internal"), not its ID. The ServiceName takes the service's name, not its ARN. This is different from most other Cloud Map API calls that use IDs — DiscoverInstances is designed for use at service runtime where you know the logical names but may not have the IDs available.
HealthStatus filter values and when to use each
The HealthStatus parameter controls which instances are included in the response based on their current health state in Cloud Map:
HealthStatus value |
Included instances | Use case |
|---|---|---|
"HEALTHY" |
Instances with HEALTHY status only | Standard production use. Never routes to degraded instances. |
"UNHEALTHY" |
Instances with UNHEALTHY status only | Debugging: find which instances are currently failing. Not for routing. |
"ALL" |
HEALTHY + UNHEALTHY + UNKNOWN instances | Default if omitted. Use only for auditing or during initial rollout before all instances pass their first health check. |
"HEALTHY_OR_ELSE_ALL" |
HEALTHY instances if any exist; otherwise ALL | Fault-tolerant fallback: routes to any instance during total outage. Useful for internal tooling that must remain accessible even during partial failures. |
The "HEALTHY_OR_ELSE_ALL" value is a useful safety net for MCP server health checkers and monitoring agents: if all instances are unhealthy (e.g., during a mass deployment failure), it still returns instances so the monitoring tool can attempt connections and report on what it finds, rather than returning an empty list that prevents any diagnosis.
QueryParameters: custom attribute filtering
QueryParameters is a map of custom attribute key-value pairs that instances must match exactly to be included in the results. It enables attribute-based routing without requiring the client to retrieve all instances and filter client-side.
// Find only MCP server instances that support code-execution tool
// and are deployed as the green (canary) version
const { Instances: canaryInstances } = await cloudMap.send(
new DiscoverInstancesCommand({
NamespaceName: "mcp.internal",
ServiceName: "mcp-server",
HealthStatus: "HEALTHY",
QueryParameters: {
DEPLOY_COLOR: "green", // exact match: value must be exactly "green"
TOOL_CODE_EXECUTION: "true", // exact match: boolean as string
},
})
);
// Find instances in us-east-1 running a minimum version
// (QueryParameters can only do exact match — not "version >= 1.4.0")
// Design your attributes for the exact-match constraint:
const { Instances: v2Instances } = await cloudMap.send(
new DiscoverInstancesCommand({
NamespaceName: "mcp.internal",
ServiceName: "mcp-server",
HealthStatus: "HEALTHY",
QueryParameters: {
MCP_PROTOCOL_VERSION: "2024-11-05",
REGION: "us-east-1",
},
})
);
// QueryParameters with no matching instances returns empty array, not an error.
// Always check for empty result:
if (!v2Instances || v2Instances.length === 0) {
// Fall back to any healthy instance
const { Instances: fallback } = await cloudMap.send(
new DiscoverInstancesCommand({
NamespaceName: "mcp.internal",
ServiceName: "mcp-server",
HealthStatus: "HEALTHY",
})
);
return fallback ?? [];
}
The exact-match constraint of QueryParameters means attribute value design matters. Avoid storing compound values like TOOLS_AVAILABLE: "web-search,code-execution,file-system" if you plan to filter on individual tools — the filter would only match instances where the attribute value is exactly that comma-separated string. Instead, store one boolean attribute per capability: TOOL_WEB_SEARCH: "true", TOOL_CODE_EXECUTION: "true", etc., so each can be filtered independently.
DiscoverInstancesRevision: change-detection without polling the full instance list
When a client needs to keep its local instance cache up to date without calling DiscoverInstances continuously, DiscoverInstancesRevision provides a lightweight change-detection signal. It returns a single StreamingExpirationTime and revision counter — if the revision counter has changed since the last call, fetch the full instance list; otherwise, skip it.
import { DiscoverInstancesRevisionCommand } from "@aws-sdk/client-servicediscovery";
class McpServerPool {
private instances: HttpInstanceSummary[] = [];
private lastRevision: bigint = 0n;
private roundRobinIndex = 0;
async refresh(): Promise<void> {
// Check if the registry changed since last poll
const { Revision } = await cloudMap.send(
new DiscoverInstancesRevisionCommand({
NamespaceName: "mcp.internal",
ServiceName: "mcp-server",
})
);
const currentRevision = BigInt(Revision ?? 0);
if (currentRevision === this.lastRevision) {
// No change — skip full DiscoverInstances call (saves API cost)
return;
}
// Revision changed — fetch fresh instance list
const { Instances } = await cloudMap.send(
new DiscoverInstancesCommand({
NamespaceName: "mcp.internal",
ServiceName: "mcp-server",
HealthStatus: "HEALTHY",
MaxResults: 100,
})
);
this.instances = Instances ?? [];
this.lastRevision = currentRevision;
console.log(
`Instance pool updated: ${this.instances.length} healthy instances (revision ${currentRevision})`
);
}
// Round-robin selection from the current healthy pool
next(): HttpInstanceSummary {
if (this.instances.length === 0) {
throw new Error("No healthy MCP server instances available");
}
const instance = this.instances[this.roundRobinIndex % this.instances.length];
this.roundRobinIndex++;
return instance;
}
startPolling(intervalMs = 10_000): void {
// Poll every 10 seconds; full refresh only when revision changes
setInterval(() => this.refresh().catch(console.error), intervalMs);
}
}
const pool = new McpServerPool();
await pool.refresh(); // initial load
pool.startPolling(10_000);
// Use pool.next() to get the next MCP server instance
const instance = pool.next();
const url = `http://${instance.Attributes!.AWS_INSTANCE_IPV4}:${instance.Attributes!.AWS_INSTANCE_PORT}`;
The polling interval of 10 seconds means changes (new deployments, instance failures) are reflected in the client's view within 10 seconds. For MCP server clients that make tool calls on behalf of users, this means a briefly stale instance list may cause one or two requests to route to a just-stopped instance — your client should handle connection errors by calling pool.refresh() immediately and retrying with a different instance.
DNS resolution for private DNS namespaces
For services in private DNS namespaces, Cloud Map creates Route 53 A records that are resolvable via DNS from within the associated VPC. This is the simplest form of service discovery — no SDK calls, just DNS resolution:
// DNS-based discovery: resolve the Cloud Map service DNS name
// Works only within the VPC associated with the private DNS namespace
// DNS name format: {serviceName}.{namespaceName}
// e.g., mcp-server.mcp.internal
import { resolve4 } from "dns/promises";
async function discoverViaDns(
serviceName: string,
namespaceName: string,
port: number
): Promise<string[]> {
const hostname = `${serviceName}.${namespaceName}`;
// dns.resolve4 returns all A records — up to 8 for MULTIVALUE routing policy
const ipAddresses = await resolve4(hostname);
return ipAddresses.map((ip) => `http://${ip}:${port}`);
}
// Usage:
const urls = await discoverViaDns("mcp-server", "mcp.internal", 3000);
// ["http://10.0.1.44:3000", "http://10.0.2.17:3000"] — up to 8 entries
DNS-based discovery has three limitations compared to DiscoverInstances:
- 8 instance limit: MULTIVALUE routing returns at most 8 A records per DNS query, even if more healthy instances are registered. If you scale an MCP server pool beyond 8 instances, DNS clients will only see a subset.
- No custom attribute access: DNS responses contain only IP addresses, not the rich attribute payload. You cannot filter by tool capability or deployment color via DNS.
- TTL latency: DNS clients cache results for the service TTL (e.g., 30 seconds). After an instance is deregistered, DNS clients that cached the IP may continue routing to it for up to TTL seconds.
DiscoverInstancesalways returns the current state without caching.
DNS is the right choice for simple deployments where the pool stays below 8 instances and you don't need attribute-based routing. Use DiscoverInstances when pool size exceeds 8, when you need custom attribute filtering, or when you need sub-TTL freshness in your instance list.
Client-side load balancing with the discovered instance list
// Production-grade client-side load balancing for MCP servers
class SmartMcpClient {
private pool: McpServerPool;
constructor(pool: McpServerPool) {
this.pool = pool;
}
async callTool(toolName: string, params: unknown): Promise<unknown> {
const maxRetries = 3;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const instance = this.pool.next();
const url = `http://${instance.Attributes!.AWS_INSTANCE_IPV4}:${instance.Attributes!.AWS_INSTANCE_PORT}`;
try {
// Make the MCP tool call
const response = await fetch(`${url}/mcp`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
method: "tools/call",
params: { name: toolName, arguments: params },
id: randomUUID(),
}),
signal: AbortSignal.timeout(30_000), // 30s timeout per attempt
});
if (!response.ok) {
throw new Error(`HTTP ${response.status} from ${url}`);
}
return await response.json();
} catch (err: any) {
const isConnectionError = (
err.name === "TypeError" || // fetch connection refused
err.code === "ECONNREFUSED" ||
err.code === "ECONNRESET" ||
err.name === "TimeoutError"
);
if (isConnectionError && attempt < maxRetries) {
// Connection-level failure: refresh the instance pool immediately
// (the instance may have been deregistered)
await this.pool.refresh();
console.warn(
`Connection failed to ${url}, attempt ${attempt}/${maxRetries} — refreshed pool`
);
continue;
}
throw err; // non-retryable error or max retries exceeded
}
}
throw new Error(`All ${maxRetries} attempts to call tool ${toolName} failed`);
}
}
function randomUUID(): string {
return crypto.randomUUID();
}
The key design is the connection-error handler that calls pool.refresh() immediately when a connection is refused. This handles the edge case where an instance was deregistered from Cloud Map but the client's cached pool still contains its IP — the refresh fetches the current state, dropping the deregistered instance from the pool before the next retry attempt.
ListInstances vs DiscoverInstances: when to use each
Cloud Map offers two APIs for listing registered instances:
DiscoverInstances— optimized for service consumers. Returns healthy instances with health filtering and attribute filtering. Uses namespace name + service name (not IDs). Billed as a service discovery API call.ListInstances— optimized for service administrators. Returns all registered instances regardless of health status. Uses service ID (not names). Paginated. Used for inventory, debugging, and drift detection.
import { ListInstancesCommand } from "@aws-sdk/client-servicediscovery";
// Admin tool: enumerate all instances in a service (for debugging/auditing)
async function listAllInstances(serviceId: string): Promise<void> {
let nextToken: string | undefined;
let totalCount = 0;
do {
const { Instances, NextToken } = await cloudMap.send(
new ListInstancesCommand({
ServiceId: serviceId, // ListInstances takes service ID, not name
NextToken: nextToken,
MaxResults: 100,
})
);
for (const instance of Instances ?? []) {
console.log(
`${instance.Id}: IP=${instance.Attributes?.AWS_INSTANCE_IPV4}, ` +
`port=${instance.Attributes?.AWS_INSTANCE_PORT}, ` +
`version=${instance.Attributes?.MCP_SERVER_VERSION ?? "unknown"}`
);
totalCount++;
}
nextToken = NextToken;
} while (nextToken);
console.log(`Total instances registered: ${totalCount}`);
}
ListInstances is the right tool for auditing your Cloud Map registry for stale instances — instances that were registered but never deregistered (e.g., because a task was force-stopped without sending SIGTERM). Cross-reference ListInstances results with the actual running ECS tasks to find orphan registrations that should be cleaned up.
Use AliveMCP to continuously probe the health endpoint of each discovered MCP server instance and correlate downtime with Cloud Map health status changes — when an instance goes from HEALTHY to UNHEALTHY in Cloud Map, you want to know whether that was because of an application error or an infrastructure event, and AliveMCP's logs give you the timeline.