Guide · AWS Cost Anomaly Detection · Cost Management
AWS Cost Anomaly Detection for MCP Servers — Detect Unexpected Spend Spikes
AWS Cost Anomaly Detection uses machine learning to identify cost increases that deviate from your account's normal spending pattern — without requiring you to manually set thresholds. Unlike AWS Budgets (which fires when spend exceeds a fixed limit), Cost Anomaly Detection learns your usage patterns and alerts you when something unexpected happens: a runaway Lambda invocation loop, an EC2 instance left running in a forgotten region, or an S3 bucket serving data at 100x normal transfer volume. For MCP server builders, the Cost Explorer API's anomaly endpoints let you query detected anomalies, create monitors scoped to specific services or cost categories, and configure alerting subscriptions programmatically. This guide covers the full SDK workflow.
TL;DR
Cost Anomaly Detection has two objects: a Monitor (what to watch — a service, linked account, cost category, or the whole account) and a Subscription (when and how to alert — an absolute dollar threshold + SNS or email). Create both with CreateAnomalyMonitorCommand and CreateAnomalySubscriptionCommand, then query detected anomalies with GetAnomaliesCommand. The API lives in the @aws-sdk/client-cost-explorer package (not a separate package) and always requires region: "us-east-1".
Package and client setup
Cost Anomaly Detection is part of the Cost Explorer API package — no additional install required if you already have @aws-sdk/client-cost-explorer:
npm install @aws-sdk/client-cost-explorer
import {
CostExplorerClient,
CreateAnomalyMonitorCommand,
CreateAnomalySubscriptionCommand,
GetAnomaliesCommand,
GetAnomalyMonitorsCommand,
GetAnomalySubscriptionsCommand,
} from "@aws-sdk/client-cost-explorer";
// Always us-east-1 — Cost Explorer is a global service
const ce = new CostExplorerClient({ region: "us-east-1" });
Monitor types
A monitor defines the scope of anomaly detection. AWS Anomaly Detection trains a separate ML model per monitor:
| MonitorType | Scope | Use case |
|---|---|---|
DIMENSIONAL |
An AWS service, linked account, or region dimension | Monitor a specific service (e.g., "AWS Lambda") or account for cost spikes |
CUSTOM |
A custom cost category or tag-based filter expression | Monitor spend attributed to a specific team or project via tags |
CreateAnomalyMonitor — DIMENSIONAL (service-level)
Monitor all AWS services — AWS creates one ML model per service, so a Lambda spike doesn't get averaged out by S3 growth:
const { MonitorArn } = await ce.send(new CreateAnomalyMonitorCommand({
AnomalyMonitor: {
MonitorName: "all-services-monitor",
MonitorType: "DIMENSIONAL",
MonitorDimension: "SERVICE", // one of: SERVICE, LINKED_ACCOUNT
},
}));
console.log("Monitor ARN:", MonitorArn);
You can only have one DIMENSIONAL monitor per dimension type per account. Attempting to create a second SERVICE dimension monitor returns LimitExceededException.
CreateAnomalyMonitor — CUSTOM (tag-based)
Custom monitors use Cost Explorer filter expressions to scope detection to resources matching specific tags or cost categories:
// Monitor only resources tagged with team=platform
const { MonitorArn: platformMonitorArn } = await ce.send(
new CreateAnomalyMonitorCommand({
AnomalyMonitor: {
MonitorName: "platform-team-cost-anomaly",
MonitorType: "CUSTOM",
MonitorSpecification: JSON.stringify({
Tags: {
Key: "team",
Values: ["platform"],
MatchOptions: ["EQUALS"],
},
}),
},
})
);
The MonitorSpecification value is a JSON string containing a Cost Explorer filter expression — the same filter structure used in GetCostAndUsage. The MonitorSpecification cannot be changed after creation; you must delete and recreate the monitor to modify the scope.
CreateAnomalySubscription — configure alert thresholds
A subscription binds one or more monitors to a notification channel and defines the dollar threshold above which anomalies are reported:
await ce.send(new CreateAnomalySubscriptionCommand({
AnomalySubscription: {
SubscriptionName: "cost-spike-alerts",
MonitorArnList: [MonitorArn!], // attach to the service monitor
Subscribers: [
{
Address: "arn:aws:sns:us-east-1:123456789012:cost-alerts",
Type: "SNS",
},
{
Address: "ops-team@example.com",
Type: "EMAIL",
},
],
// Alert if anomaly impact exceeds $20 total or $5/day
Threshold: 20, // deprecated field — use ThresholdExpression
ThresholdExpression: JSON.stringify({
Dimensions: {
Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
MatchOptions: ["GREATER_THAN_OR_EQUAL"],
Values: ["20"], // $20 total impact threshold
},
}),
Frequency: "DAILY", // IMMEDIATE | DAILY | WEEKLY
},
}));
Threshold expressions
The ThresholdExpression JSON string uses three special dimensions to control sensitivity:
| Dimension key | What it filters on | Example value |
|---|---|---|
ANOMALY_TOTAL_IMPACT_ABSOLUTE |
Total dollar impact of the anomaly (actual − expected) | "20" — alert if spike costs $20+ total |
ANOMALY_TOTAL_IMPACT_PERCENTAGE |
% above expected spend this anomaly represents | "50" — alert if 50% above expected |
Use an And expression to require both a minimum dollar impact AND a minimum percentage impact — this prevents alerting on a 1000% spike that only costs $0.50:
ThresholdExpression: JSON.stringify({
And: [
{
Dimensions: {
Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
MatchOptions: ["GREATER_THAN_OR_EQUAL"],
Values: ["20"], // at least $20
},
},
{
Dimensions: {
Key: "ANOMALY_TOTAL_IMPACT_PERCENTAGE",
MatchOptions: ["GREATER_THAN_OR_EQUAL"],
Values: ["25"], // at least 25% above expected
},
},
],
})
Frequency options
| Frequency | Behavior | Best for |
|---|---|---|
IMMEDIATE |
Alert as soon as anomaly is detected, once per anomaly | Critical accounts where every dollar counts |
DAILY |
Daily digest of anomalies detected in the past day | Standard operational monitoring — reduces alert fatigue |
WEEKLY |
Weekly summary of all anomalies | Low-spend development accounts |
GetAnomalies — query detected anomalies
Query anomalies detected by your monitors over a date range:
import { GetAnomaliesCommand } from "@aws-sdk/client-cost-explorer";
const response = await ce.send(new GetAnomaliesCommand({
DateInterval: {
StartDate: "2026-10-01",
EndDate: "2026-11-01",
},
MonitorArn: MonitorArn, // optional — omit to get all monitors' anomalies
MaxResults: 20,
}));
for (const anomaly of response.Anomalies ?? []) {
const impact = anomaly.Impact;
console.log(`
Anomaly ID: ${anomaly.AnomalyId}
Period: ${anomaly.AnomalyStartDate} → ${anomaly.AnomalyEndDate}
Root cause: ${anomaly.RootCauses?.map(r => r.Service + "/" + r.Region).join(", ")}
Actual spend: $${impact?.TotalActualSpend?.toFixed(2)}
Expected spend: $${impact?.TotalExpectedSpend?.toFixed(2)}
Impact: $${impact?.TotalImpact?.toFixed(2)} (${impact?.TotalImpactPercentage?.toFixed(1)}% above expected)
Feedback: ${anomaly.Feedback ?? "not reviewed"}
`.trim());
}
Impact fields explained
| Field | Description |
|---|---|
TotalActualSpend |
What you actually spent during the anomaly period |
TotalExpectedSpend |
What the ML model predicted you would spend based on historical patterns |
TotalImpact |
TotalActualSpend - TotalExpectedSpend — the extra cost the anomaly caused |
TotalImpactPercentage |
(TotalImpact / TotalExpectedSpend) * 100 — severity as a percentage |
MaxImpact |
Peak single-day dollar impact during the anomaly period |
Root cause structure
Each anomaly includes a RootCauses array, ordered by estimated impact contribution. Each root cause identifies the service, region, usage type, and usage type group that drove the spike:
for (const rc of anomaly.RootCauses ?? []) {
console.log({
service: rc.Service, // e.g., "AWS Lambda"
region: rc.Region, // e.g., "us-east-1"
linkedAccount: rc.LinkedAccount, // 12-digit account ID in org
usageType: rc.UsageType, // e.g., "USE1-Lambda-GB-Second"
usageTypeGroup: rc.UsageTypeGroup, // e.g., "Lambda: Duration"
});
}
Pagination and feedback
Results are paginated with NextPageToken. After reviewing an anomaly, mark it as a true positive or false positive using ProvideAnomalyFeedbackCommand — this improves the model's future accuracy:
import {
GetAnomaliesCommand,
ProvideAnomalyFeedbackCommand,
} from "@aws-sdk/client-cost-explorer";
// Paginate all anomalies
async function getAllAnomalies(startDate: string, endDate: string) {
const all = [];
let nextToken: string | undefined;
do {
const r = await ce.send(new GetAnomaliesCommand({
DateInterval: { StartDate: startDate, EndDate: endDate },
NextPageToken: nextToken,
}));
all.push(...(r.Anomalies ?? []));
nextToken = r.NextPageToken;
} while (nextToken);
return all;
}
// Mark a known false positive (e.g., intentional data migration)
await ce.send(new ProvideAnomalyFeedbackCommand({
AnomalyId: "some-anomaly-id",
Feedback: "NO", // "YES" = true positive, "NO" = false positive, "PLANNED_ACTIVITY"
}));
GetAnomalyMonitors and GetAnomalySubscriptions
List your monitors and subscriptions to audit what's configured:
// List all monitors
const { AnomalyMonitors } = await ce.send(
new GetAnomalyMonitorsCommand({ MaxResults: 100 })
);
for (const m of AnomalyMonitors ?? []) {
console.log(`${m.MonitorName} [${m.MonitorType}] status=${m.MonitorStatus}`);
console.log(` Last evaluated: ${m.LastUpdatedDate}`);
console.log(` Dimension: ${m.MonitorDimension ?? "(custom)"}`);
}
// List all subscriptions
const { AnomalySubscriptions } = await ce.send(
new GetAnomalySubscriptionsCommand({ MaxResults: 100 })
);
for (const s of AnomalySubscriptions ?? []) {
console.log(`${s.SubscriptionName} freq=${s.Frequency}`);
console.log(` Monitors: ${s.MonitorArnList?.join(", ")}`);
for (const sub of s.Subscribers ?? []) {
console.log(` Subscriber: ${sub.Type} → ${sub.Address} (${sub.Status})`);
}
}
Complete MCP tool: query recent anomalies
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
CostExplorerClient,
GetAnomaliesCommand,
} from "@aws-sdk/client-cost-explorer";
import { z } from "zod";
const ce = new CostExplorerClient({ region: "us-east-1" });
const server = new McpServer({ name: "cost-anomaly-tool", version: "1.0.0" });
server.tool(
"get_cost_anomalies",
"Return AWS cost anomalies detected in a date range, sorted by impact",
{
days_back: z.number().int().min(1).max(90).default(30)
.describe("How many days back to look for anomalies"),
min_impact_usd: z.number().min(0).default(10)
.describe("Only return anomalies with total impact above this dollar amount"),
},
async ({ days_back, min_impact_usd }) => {
const end = new Date();
const start = new Date();
start.setDate(end.getDate() - days_back);
const fmt = (d: Date) => d.toISOString().split("T")[0];
const anomalies = [];
let nextToken: string | undefined;
do {
const r = await ce.send(new GetAnomaliesCommand({
DateInterval: { StartDate: fmt(start), EndDate: fmt(end) },
MaxResults: 20,
NextPageToken: nextToken,
}));
anomalies.push(...(r.Anomalies ?? []));
nextToken = r.NextPageToken;
} while (nextToken);
const filtered = anomalies
.filter(a => (a.Impact?.TotalImpact ?? 0) >= min_impact_usd)
.sort((a, b) => (b.Impact?.TotalImpact ?? 0) - (a.Impact?.TotalImpact ?? 0));
if (filtered.length === 0) {
return {
content: [{
type: "text",
text: `No cost anomalies with impact ≥ $${min_impact_usd} in the last ${days_back} days.`,
}],
};
}
const lines = filtered.map(a => {
const impact = a.Impact;
const rootCause = a.RootCauses?.[0];
return [
`• $${impact?.TotalImpact?.toFixed(2)} impact (${impact?.TotalImpactPercentage?.toFixed(0)}% above expected)`,
` Period: ${a.AnomalyStartDate} → ${a.AnomalyEndDate ?? "ongoing"}`,
` Top root cause: ${rootCause?.Service ?? "?"} in ${rootCause?.Region ?? "?"} (${rootCause?.UsageTypeGroup ?? "?"})`,
` Actual: $${impact?.TotalActualSpend?.toFixed(2)} | Expected: $${impact?.TotalExpectedSpend?.toFixed(2)}`,
` Feedback: ${a.Feedback ?? "none"}`,
].join("\n");
});
return {
content: [{
type: "text",
text: [
`Cost anomalies in the last ${days_back} days (${filtered.length} with impact ≥ $${min_impact_usd}):`,
"",
lines.join("\n\n"),
].join("\n"),
}],
};
}
);
IAM permissions
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ce:CreateAnomalyMonitor",
"ce:CreateAnomalySubscription",
"ce:DeleteAnomalyMonitor",
"ce:DeleteAnomalySubscription",
"ce:GetAnomalies",
"ce:GetAnomalyMonitors",
"ce:GetAnomalySubscriptions",
"ce:ProvideAnomalyFeedback",
"ce:UpdateAnomalyMonitor",
"ce:UpdateAnomalySubscription"
],
"Resource": "*"
}
]
}
Key limits and constraints
| Limit | Value | Notes |
|---|---|---|
| DIMENSIONAL monitors per account | 2 (one SERVICE, one LINKED_ACCOUNT) | Fixed — cannot be increased |
| CUSTOM monitors per account | 500 | Default; contact AWS Support to raise |
| Subscriptions per account | 500 | Default |
| Anomaly history retention | 90 days | GetAnomalies date range cannot exceed 90 days back |
| Detection latency | 12–36 hours | ML model evaluates daily — real-time detection is not supported |
| Minimum training data | 3 days of data | Newly created monitors need 3 days before first anomaly can be detected |
Common errors
| Error | Cause and fix |
|---|---|
LimitExceededException: DIMENSIONAL monitor already exists |
You already have a SERVICE or LINKED_ACCOUNT dimensional monitor. Use GetAnomalyMonitorsCommand to find the existing one and reuse it. |
InvalidParameterException: MonitorSpecification is invalid |
The filter JSON in MonitorSpecification is malformed or uses an unsupported dimension. Validate the JSON string — it must be a valid Cost Explorer filter expression. |
UnknownSubscriberException |
The SNS topic ARN does not exist or the Budgets/CE service principal is not allowed to publish to it. Add the SNS topic policy allowing ce.amazonaws.com. |
AccessDeniedException |
Missing ce: permissions. For Organization management accounts, also check that consolidated billing is enabled. |