Guide · AWS Cloud Map · Service Registration
AWS Cloud Map Service Registration for MCP Servers — RegisterInstance, Custom Attributes, and Health Status
AWS Cloud Map's RegisterInstance is the call that puts an MCP server instance into the service registry, making it discoverable by DNS resolution or DiscoverInstances API calls. The required instance attributes depend on the DNS record type configured in the parent service: A-record services require AWS_INSTANCE_IPV4 and optionally AWS_INSTANCE_PORT; CNAME services require AWS_INSTANCE_CNAME; SRV services require both IP and port. Beyond the required routing attributes, you can attach any number of custom key-value attributes — MCP protocol version, region affinity, instance capability flags — that callers can filter on when calling DiscoverInstances. This guide covers the full instance lifecycle: registration, custom attribute patterns, health status management with UpdateInstanceCustomHealthStatus, and clean deregistration. For namespace and service creation, see Cloud Map Overview. For ECS task definition integration, see Cloud Map ECS Integration. For discovery patterns, see Cloud Map DiscoverInstances.
TL;DR
RegisterInstance requires at minimum AWS_INSTANCE_IPV4 for A-record services. The InstanceId must be unique within the service — use a stable identifier like the ECS task ARN or EC2 instance ID, not a random UUID (random IDs prevent idempotent retry). RegisterInstance is itself idempotent: calling it again with the same InstanceId and Attributes is a no-op; calling it with the same InstanceId but different Attributes atomically replaces all attributes. The API is asynchronous for DNS-backed services — poll GetOperation until SUCCESS before the instance appears in DNS. DeregisterInstance removes the DNS record and excludes the instance from DiscoverInstances immediately once the operation completes, but DNS caches persist for the service TTL duration.
RegisterInstance attribute requirements by DNS record type
The Attributes map passed to RegisterInstance must contain specific reserved keys depending on the DNS record type configured in the parent service's DnsConfig. Missing a required attribute causes a InvalidInput error with a message like "The 'AWS_INSTANCE_IPV4' attribute is required."
| DNS record type | Required attributes | Optional attributes | MCP server use case |
|---|---|---|---|
| A | AWS_INSTANCE_IPV4 |
AWS_INSTANCE_PORT, custom attrs |
ECS Fargate IP-mode tasks, EC2 instances |
| AAAA | AWS_INSTANCE_IPV6 |
AWS_INSTANCE_PORT, custom attrs |
IPv6-only VPC environments |
| CNAME | AWS_INSTANCE_CNAME |
Custom attrs only | Registering an ALB DNS name in Cloud Map |
| SRV | AWS_INSTANCE_IPV4 + AWS_INSTANCE_PORT |
AWS_INSTANCE_IPV6, custom attrs |
Services where both host and port must be carried in DNS |
| HTTP namespace (no DNS) | None required (but AWS_INSTANCE_IPV4 + AWS_INSTANCE_PORT recommended) |
Any custom key-value pairs | API-only discovery where DNS is not used |
AWS_INSTANCE_PORT is optional for A-record services but highly recommended: when present, it is included in SRV record extensions and in DiscoverInstances responses, allowing callers to construct the full host:port connection string without needing to know the port out-of-band.
RegisterInstance: basic registration and idempotency
import {
ServiceDiscoveryClient,
RegisterInstanceCommand,
DeregisterInstanceCommand,
GetOperationCommand,
GetInstancesHealthStatusCommand,
type RegisterInstanceCommandInput,
} from "@aws-sdk/client-servicediscovery";
import { hostname } from "os";
const cloudMap = new ServiceDiscoveryClient({ region: process.env.AWS_REGION! });
// Called at MCP server startup
async function registerMcpServerInstance(
serviceId: string,
privateIp: string,
port: number,
instanceId: string // stable ID: ECS task ARN, EC2 instance ID, or hostname
): Promise<void> {
const input: RegisterInstanceCommandInput = {
ServiceId: serviceId,
InstanceId: instanceId, // must be stable and unique within the service
// CreatorRequestId provides idempotency for the registration call itself
CreatorRequestId: `register-${serviceId}-${instanceId}`,
Attributes: {
// Required for A-record services
AWS_INSTANCE_IPV4: privateIp,
AWS_INSTANCE_PORT: String(port),
// Custom attributes — discoverable via DiscoverInstances QueryParameters filter
MCP_PROTOCOL_VERSION: "2024-11-05",
MCP_SERVER_VERSION: process.env.APP_VERSION ?? "unknown",
REGION: process.env.AWS_REGION ?? "us-east-1",
STARTUP_TIME: new Date().toISOString(),
},
};
const { OperationId } = await cloudMap.send(
new RegisterInstanceCommand(input)
);
// For DNS-backed services, registration is async — wait for DNS propagation
if (OperationId) {
await waitForOperation(OperationId);
}
console.log(`Registered MCP server instance ${instanceId} in Cloud Map`);
}
async function waitForOperation(operationId: string): Promise<void> {
for (let i = 0; i < 20; i++) {
await new Promise((r) => setTimeout(r, 2000));
const { Operation } = await cloudMap.send(
new GetOperationCommand({ OperationId: operationId })
);
if (Operation?.Status === "SUCCESS") return;
if (Operation?.Status === "FAIL") {
throw new Error(`Cloud Map operation failed: ${Operation.ErrorMessage}`);
}
}
throw new Error("Cloud Map registration timed out");
}
The key design decision is the InstanceId value. For ECS tasks, use the task ARN (process.env.ECS_CONTAINER_METADATA_URI_V4 → GET metadata → .TaskARN). For EC2 instances, use the instance ID from the IMDS (curl http://169.254.169.254/latest/meta-data/instance-id). For bare-metal or on-premises servers, use the hostname. Never use a random UUID as the instance ID. A random UUID means that retried registrations after a network timeout create duplicate entries rather than updating the existing one, filling the service with phantom instances.
Custom attributes: routing metadata for MCP server instances
Custom attributes are free-form key-value pairs stored with each instance. They serve as routing metadata that callers can use to filter instances when calling DiscoverInstances. Cloud Map allows up to 30 attributes per instance (combined reserved AWS_* attributes and custom attributes), each with a key up to 255 characters and a value up to 1,024 characters.
Useful custom attributes for MCP server deployments:
// Example: registering a specialized MCP server instance
// that handles only certain tool categories
const attributes = {
AWS_INSTANCE_IPV4: privateIp,
AWS_INSTANCE_PORT: "3000",
// Tool capability flags — filter to instances that support specific tools
TOOLS_AVAILABLE: "web-search,code-execution,file-system",
TOOLS_DISABLED: "",
// Model backend affinity — route tool calls to instances near the model endpoint
MODEL_REGION: "us-east-1",
MODEL_PROVIDER: "anthropic",
// Resource tier — route heavy tool calls to large instances
INSTANCE_CLASS: "compute-optimized", // "standard" | "compute-optimized" | "memory-optimized"
MAX_CONCURRENT_TOOLS: "20",
// Deployment metadata for traffic management
DEPLOY_COLOR: "blue", // "blue" | "green" for blue/green deployments
APP_VERSION: "1.4.2",
BUILD_SHA: process.env.GIT_SHA ?? "unknown",
};
// Caller filters on DEPLOY_COLOR=green for canary traffic:
// discoverInstances({ QueryParameters: { DEPLOY_COLOR: "green" } })
// Caller filters on TOOLS_AVAILABLE=code-execution:
// discoverInstances({ QueryParameters: { TOOLS_AVAILABLE: "code-execution" } })
// NOTE: QueryParameters matching is exact-string — "code-execution" matches
// ONLY if the attribute value is exactly "code-execution". Substring matching
// is not supported — design attribute values for exact-match filtering.
The critical limitation of QueryParameters filtering is that it is exact-match only. Cloud Map does not support substring matching, prefix matching, or contains semantics. If you need to filter on tool capability (e.g., find instances that support code-execution among others), you have two options: (1) register one boolean attribute per capability (TOOL_CODE_EXECUTION: "true") and filter on that, or (2) handle the filtering client-side after retrieving all instances.
Updating instance attributes
To update an instance's attributes (changing version, updating capability flags after a hot-reload, adjusting routing metadata), call RegisterInstance again with the same InstanceId and new Attributes. This is a complete replacement — it atomically overwrites all attributes, not a partial update. Any attribute not included in the new call is deleted.
// Updating attributes: re-call RegisterInstance with the same InstanceId
// All previous attributes are replaced atomically.
async function updateInstanceAttributes(
serviceId: string,
instanceId: string,
newAttributes: Record<string, string>
): Promise<void> {
// Always include required routing attributes when updating
const { OperationId } = await cloudMap.send(
new RegisterInstanceCommand({
ServiceId: serviceId,
InstanceId: instanceId,
// No CreatorRequestId on updates — this is an overwrite, not a create
Attributes: {
AWS_INSTANCE_IPV4: currentPrivateIp, // must re-include required attrs
AWS_INSTANCE_PORT: "3000",
...newAttributes,
},
})
);
if (OperationId) await waitForOperation(OperationId);
}
// Example: mark instance as draining before shutdown
await updateInstanceAttributes(serviceId, instanceId, {
AWS_INSTANCE_IPV4: currentIp,
AWS_INSTANCE_PORT: "3000",
DRAINING: "true",
DRAIN_STARTED_AT: new Date().toISOString(),
});
Health status management with UpdateInstanceCustomHealthStatus
When a service has HealthCheckCustomConfig configured, the health status of each instance is controlled via UpdateInstanceCustomHealthStatusCommand. This is the pattern ECS uses: the ECS container agent calls this API to mark tasks as healthy when they pass their container health check, and as unhealthy when they fail or are stopped.
import {
UpdateInstanceCustomHealthStatusCommand,
} from "@aws-sdk/client-servicediscovery";
// Mark instance as healthy (call after MCP server /health probe passes)
async function markInstanceHealthy(
serviceId: string,
instanceId: string
): Promise<void> {
await cloudMap.send(
new UpdateInstanceCustomHealthStatusCommand({
ServiceId: serviceId,
InstanceId: instanceId,
Status: "HEALTHY",
})
);
}
// Mark instance as unhealthy (call before graceful shutdown or on health probe failure)
async function markInstanceUnhealthy(
serviceId: string,
instanceId: string
): Promise<void> {
await cloudMap.send(
new UpdateInstanceCustomHealthStatusCommand({
ServiceId: serviceId,
InstanceId: instanceId,
Status: "UNHEALTHY",
})
);
// After marking unhealthy, wait for DNS TTL to expire before proceeding
// with shutdown to avoid sending traffic to a stopping instance.
// If your service TTL is 30 seconds, wait at least 30 seconds here.
await new Promise((r) => setTimeout(r, 35_000));
}
// Graceful shutdown sequence for an MCP server instance
async function gracefulShutdown(
serviceId: string,
instanceId: string
): Promise<void> {
// 1. Mark unhealthy to stop receiving new connections via Cloud Map
await markInstanceUnhealthy(serviceId, instanceId);
// 2. Wait for existing SSE connections to drain
// (your MCP server should stop accepting new sessions and
// wait for active sessions to complete or timeout)
await waitForSessionDrain();
// 3. Deregister from Cloud Map
const { OperationId } = await cloudMap.send(
new DeregisterInstanceCommand({
ServiceId: serviceId,
InstanceId: instanceId,
})
);
if (OperationId) await waitForOperation(OperationId);
console.log("Instance deregistered from Cloud Map");
}
The HEALTHY/UNHEALTHY distinction matters: DiscoverInstances with HealthStatus: "HEALTHY" will exclude instances marked UNHEALTHY. DNS responses also exclude UNHEALTHY instances from MULTIVALUE results once the Cloud Map DNS record change propagates. Setting status to UNHEALTHY before deregistering, and waiting for the TTL, ensures no new traffic routes to a shutting-down instance even during the brief window between marking unhealthy and completing deregistration.
Checking instance health status
// Get health status for all instances in a service
async function getServiceHealthSummary(
serviceId: string
): Promise<Map<string, "HEALTHY" | "UNHEALTHY" | "UNKNOWN">> {
const result = new Map<string, "HEALTHY" | "UNHEALTHY" | "UNKNOWN">();
let nextToken: string | undefined;
do {
const { Status, NextToken } = await cloudMap.send(
new GetInstancesHealthStatusCommand({
ServiceId: serviceId,
NextToken: nextToken,
})
);
for (const [instanceId, status] of Object.entries(Status ?? {})) {
result.set(instanceId, status as "HEALTHY" | "UNHEALTHY" | "UNKNOWN");
}
nextToken = NextToken;
} while (nextToken);
const healthy = [...result.values()].filter((s) => s === "HEALTHY").length;
const total = result.size;
console.log(`Service health: ${healthy}/${total} instances healthy`);
return result;
}
The UNKNOWN status appears when an instance was registered with HealthCheckCustomConfig but UpdateInstanceCustomHealthStatusCommand has never been called for it. ECS-managed instances transition from UNKNOWN to HEALTHY quickly after the container health check passes; manually registered instances remain UNKNOWN until you call UpdateInstanceCustomHealthStatus for the first time. Cloud Map treats UNKNOWN instances as discoverable (they are included in DiscoverInstances results when HealthStatus is not filtered).
Deregistration and cleanup
// Full deregistration with operation polling
async function deregisterInstance(
serviceId: string,
instanceId: string
): Promise<void> {
try {
const { OperationId } = await cloudMap.send(
new DeregisterInstanceCommand({
ServiceId: serviceId,
InstanceId: instanceId,
})
);
if (OperationId) {
await waitForOperation(OperationId);
}
} catch (err: any) {
// InstanceNotFound: instance was already deregistered — safe to ignore
if (err.name === "InstanceNotFound") {
console.log(`Instance ${instanceId} was already deregistered`);
return;
}
throw err;
}
}
// SIGTERM handler for Node.js MCP servers on ECS/EC2
process.on("SIGTERM", async () => {
console.log("SIGTERM received — beginning graceful shutdown");
// 1. Stop accepting new MCP connections
server.close();
// 2. Mark Cloud Map instance unhealthy
if (cloudMapServiceId && cloudMapInstanceId) {
await markInstanceUnhealthy(cloudMapServiceId, cloudMapInstanceId);
}
// 3. Wait for in-flight tool calls to complete (max 25 seconds for ECS)
await Promise.race([
waitForPendingToolCalls(),
new Promise((r) => setTimeout(r, 25_000)),
]);
// 4. Deregister from Cloud Map
if (cloudMapServiceId && cloudMapInstanceId) {
await deregisterInstance(cloudMapServiceId, cloudMapInstanceId);
}
process.exit(0);
});
ECS sends SIGTERM to containers when a task is stopped, then waits for stopTimeout seconds (default 30, configurable up to 120) before sending SIGKILL. Your shutdown handler must complete within this window. The sequence above takes roughly 35–40 seconds if the service TTL is 30 seconds — configure stopTimeout: 60 in your ECS task definition to give the graceful shutdown enough time to complete.
Production gotchas for instance registration
- InstanceId uniqueness is per-service, not global. Two different services can have instances with the same
InstanceId— the ID is scoped to the service. Use IDs that are stable within a service's lifetime (task ARN, EC2 instance ID). - Attribute overwrite on retry is intentional, not a bug. If a Lambda that calls
RegisterInstancetimes out and retries, using the sameInstanceIdandCreatorRequestIdreturns the original operation result without side effects. If you change attributes between the failed call and the retry, the second call wins. - DNS TTL persists after deregistration. After
DeregisterInstancecompletes, the DNS record is removed from Route 53 but clients that have already cached the A record will continue routing to the deregistered IP for up to TTL seconds. Mark the instance UNHEALTHY first and wait for TTL before proceeding with hard shutdown. - Custom health check config vs Route53 health check config are mutually exclusive. A service can have one or the other, but not both. If you configure
HealthCheckCustomConfig, Route53 does not probe your instances; you are fully responsible for callingUpdateInstanceCustomHealthStatus. If you configureHealthCheckConfig(Route53-managed), Cloud Map ignoresUpdateInstanceCustomHealthStatuscalls. - HTTP namespace registration is synchronous. For services within HTTP namespaces,
RegisterInstancedoes not return anOperationIdand the instance is immediately discoverable viaDiscoverInstances. Skip the operation polling for HTTP namespace services.