AWS Cost Management · 2026-11-14 · Cost Management arc
AWS Cost Observability for MCP Server Teams: Cost Explorer, Budgets, Anomaly Detection, and Compute Optimizer
Four AWS services answer four different cost questions, and MCP server teams need all four of them. Cost Explorer answers "what did we spend?" — a historical query layer. AWS Budgets answers "are we on track?" — a threshold and alert layer. Cost Anomaly Detection answers "did something unexpected happen?" — a machine-learning spike detector. Compute Optimizer answers "where can we spend less?" — a rightsizing recommendation engine. Each service is useful alone. Together they form a complete cost observability stack that catches every failure mode: the runaway Lambda loop you discover in the monthly bill, the ECS Fargate task silently burning 2× its actual memory needs, the engineer who left a GPU instance running over a holiday weekend. This guide synthesizes all four into an integrated workflow and shows exactly where each one fails without the others.
TL;DR
The four AWS cost services form a pyramid, not a redundant stack. Cost Explorer (@aws-sdk/client-cost-explorer, always region: "us-east-1") queries historical actuals with GetCostAndUsageCommand — DAILY/MONTHLY/HOURLY granularity, up to 12 months back, with groupBy DIMENSION (SERVICE, LINKED_ACCOUNT) or TAG. It is reactive: it tells you what already happened. AWS Budgets (@aws-sdk/client-budgets, also us-east-1) is proactive: set a dollar threshold and get an SNS or email notification when actual or forecasted spend hits 80%, 100%, or any custom percentage of your limit — before the month ends. Cost Anomaly Detection (part of @aws-sdk/client-cost-explorer) is adaptive: it trains an ML model per monitor and fires when spend deviates from your historical pattern — no fixed threshold to maintain, fires on a 10× Lambda spike even if the total is still under your budget. Compute Optimizer (@aws-sdk/client-compute-optimizer) is prescriptive: after a 24–48h analysis window it tells you which Lambda functions are over-provisioned, which ECS tasks have memory headroom, and by how much — with estimated monthly savings. The coverage gap without all four: Cost Explorer alone misses in-progress month runaway spend (data is per-day, not real-time). Budgets alone misses the case where a spike is large but still under your threshold. Anomaly Detection alone can't tell you which Lambda is chronically over-provisioned vs. genuinely spiking. Compute Optimizer alone has no alerting — it's a report you have to pull. Wire all four; the IAM surface is four ce:* + budgets:* + compute-optimizer:* actions, all scoped Resource: "*".
The four layers at a glance
Before diving into each service, here is where the four cost management services stand on the dimensions that matter most for MCP server tool design:
| Service | Question answered | Time orientation | Alerting | SDK package |
|---|---|---|---|---|
| Cost Explorer | What did we spend? | Reactive — historical actuals | None — query only | @aws-sdk/client-cost-explorer |
| AWS Budgets | Are we on track? | Proactive — forecasted vs. actual | SNS or email at threshold % | @aws-sdk/client-budgets |
| Cost Anomaly Detection | Did something unexpected happen? | Adaptive — ML baseline deviation | SNS or email on anomaly | @aws-sdk/client-cost-explorer |
| Compute Optimizer | Where can we spend less? | Prescriptive — 14-day metric analysis | None — recommendations only | @aws-sdk/client-compute-optimizer |
The critical insight is that none of these services is a substitute for the others. A team that runs only Cost Explorer discovers runaway spend in the monthly bill, two weeks after it happened. A team that runs only Budgets never gets alerted to a 10× cost spike that is still under their monthly budget cap. A team that runs only Anomaly Detection never builds the habit of actively reviewing rightsizing opportunities. A team that runs only Compute Optimizer has no proactive alerting at all.
Layer 1 — Cost Explorer: the historical query layer
Cost Explorer is the foundation. Every cost investigation starts here — it's the only service that lets you answer arbitrary historical questions about your spend: which service cost the most last month, how did Lambda spend change week-over-week, which team's cost allocation tags are over their target. The key constraint that affects MCP tool design is that Cost Explorer is a global service with a single endpoint — always instantiate the client with region: "us-east-1" regardless of where your resources live:
import { CostExplorerClient, GetCostAndUsageCommand } from "@aws-sdk/client-cost-explorer";
// Always us-east-1 — Cost Explorer is a global service
const ce = new CostExplorerClient({ region: "us-east-1" });
const response = await ce.send(new GetCostAndUsageCommand({
TimePeriod: { Start: "2026-10-01", End: "2026-11-01" },
Granularity: "MONTHLY",
Metrics: ["AmortizedCost"],
GroupBy: [{ Type: "DIMENSION", Key: "SERVICE" }],
}));
The two groupBy axes — DIMENSION and TAG — answer different questions. DIMENSION groups by SERVICE, LINKED_ACCOUNT, REGION, USAGE_TYPE, or INSTANCE_TYPE — these are AWS's built-in categories. TAG groups by your own cost allocation tags (e.g., team, environment, project) — these require the tags to be activated in Cost Allocation Tag settings before they appear in Cost Explorer results. A common mistake is grouping by TAG before activating the tag in the console; the query returns empty results without an error.
For MCP server builders, the most common tool shapes are:
- Service breakdown tool: GroupBy SERVICE + MONTHLY granularity — returns a ranked list of services by spend for the current or last month.
- Team spend tool: GroupBy TAG (your team tag) + MONTHLY — shows per-team cost for FinOps dashboards.
- Forecast tool:
GetCostForecastCommandwith a futureTimePeriod.End— returns aMeanValue(point estimate) and 80% confidence interval (PredictionIntervalUpperBound/PredictionIntervalLowerBound).
Where Cost Explorer alone fails: DAILY granularity data has a 24-hour lag. HOURLY is available but only for the last 14 days, and each HOURLY call counts as 24× the quota against Cost Explorer's 1,500 requests/day rate limit. Neither gives you real-time visibility into a runaway invocation loop that started at 2 AM. That is Budgets' job.
Layer 2 — AWS Budgets: the proactive threshold layer
Budgets is the guardrail layer. Where Cost Explorer queries past spend, Budgets monitors present and forecasted spend and fires alerts when thresholds are crossed. The mental model is: a Budget is a watcher on a filtered slice of your bill, with one or more notification rules attached. The filter can be as broad as "total monthly AWS spend" or as narrow as "Lambda costs in us-east-1 tagged with team=platform".
import { BudgetsClient, CreateBudgetCommand } from "@aws-sdk/client-budgets";
const budgets = new BudgetsClient({ region: "us-east-1" });
const ACCOUNT_ID = process.env.AWS_ACCOUNT_ID!;
await budgets.send(new CreateBudgetCommand({
AccountId: ACCOUNT_ID,
Budget: {
BudgetName: "platform-lambda-monthly",
BudgetType: "COST",
TimeUnit: "MONTHLY",
BudgetLimit: { Amount: "500", Unit: "USD" },
CostFilters: { Service: ["AWS Lambda"] },
},
NotificationsWithSubscribers: [
{
Notification: {
NotificationType: "ACTUAL",
ComparisonOperator: "GREATER_THAN",
Threshold: 80,
ThresholdType: "PERCENTAGE",
},
Subscribers: [
{ SubscriptionType: "SNS", Address: "arn:aws:sns:us-east-1:123456789012:cost-alerts" },
],
},
{
Notification: {
NotificationType: "FORECASTED",
ComparisonOperator: "GREATER_THAN",
Threshold: 100,
ThresholdType: "PERCENTAGE",
},
Subscribers: [
{ SubscriptionType: "SNS", Address: "arn:aws:sns:us-east-1:123456789012:cost-alerts" },
],
},
],
}));
The ACTUAL vs FORECASTED distinction in NotificationType is the most useful nuance in Budgets. An ACTUAL alert fires when you have already spent past the threshold. A FORECASTED alert fires when AWS's model predicts you will exceed the threshold by end of period — typically with 1–3 days of warning, enough time to investigate and act. For MCP server teams, running both on the same budget gives you two signals: "you're over" and "you're headed over."
AWS Budgets free tier covers 2 budgets at no cost; additional budgets cost $0.02/day each (~$0.60/month). For most MCP server teams, 3–5 budgets covers the material spend categories: total account, Lambda, ECS/Fargate, and data transfer.
Where Budgets alone fails: Budgets fires when spend crosses a fixed percentage of a fixed limit. A $500/month Lambda budget at 80% fires when Lambda costs hit $400. It doesn't fire if Lambda costs spike 300% in a single day but are still $150 total — well under the $400 threshold. That is exactly the case that runaway Lambda invocation loops create: a function trapped in a retry loop for 6 hours can rack up $80–200 in a single incident before the month's total looks alarming. That is Anomaly Detection's job.
Layer 3 — Cost Anomaly Detection: the adaptive ML layer
Cost Anomaly Detection solves the threshold problem by learning your historical pattern and alerting when something deviates from it — without requiring you to maintain fixed dollar limits. The underlying mechanism is an ML model AWS trains per Monitor. A DIMENSIONAL monitor scoped to SERVICE trains one model per AWS service (so a Lambda spike doesn't get averaged into S3 growth). A CUSTOM monitor trains on your filtered cost category (useful for per-team or per-project spend).
import {
CostExplorerClient,
CreateAnomalyMonitorCommand,
CreateAnomalySubscriptionCommand,
} from "@aws-sdk/client-cost-explorer";
const ce = new CostExplorerClient({ region: "us-east-1" });
// Create a monitor that watches all services, one model per service
const { MonitorArn } = await ce.send(new CreateAnomalyMonitorCommand({
AnomalyMonitor: {
MonitorName: "all-services",
MonitorType: "DIMENSIONAL",
MonitorDimension: "SERVICE",
},
}));
// Subscribe: alert when a detected anomaly has an absolute impact > $20
await ce.send(new CreateAnomalySubscriptionCommand({
AnomalySubscription: {
SubscriptionName: "daily-spend-alert",
MonitorArnList: [MonitorArn!],
Subscribers: [
{ Address: "arn:aws:sns:us-east-1:123456789012:cost-alerts", Type: "SNS" },
],
Frequency: "DAILY",
ThresholdExpression: {
Dimension: {
Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
MatchOptions: ["GREATER_THAN_OR_EQUAL"],
Values: ["20"],
},
},
},
}));
The ThresholdExpression can be a single condition (absolute dollar impact or percentage impact) or a compound And expression that requires both. For MCP server teams, requiring both an absolute threshold (e.g., $20) and a relative threshold (e.g., 50% above baseline) prevents alert fatigue from small-dollar anomalies in low-spend services while still catching meaningful incidents.
// Compound threshold: > $20 AND > 50% above baseline
ThresholdExpression: {
And: [
{
Dimension: {
Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
MatchOptions: ["GREATER_THAN_OR_EQUAL"],
Values: ["20"],
},
},
{
Dimension: {
Key: "ANOMALY_TOTAL_IMPACT_PERCENTAGE",
MatchOptions: ["GREATER_THAN_OR_EQUAL"],
Values: ["50"],
},
},
],
}
When an anomaly fires, query the detected anomalies with GetAnomaliesCommand. Each anomaly includes RootCauses — an ordered list of service/region/usage-type combinations ranked by their contribution to the anomaly. This is the most actionable field in the response: it tells you which specific Lambda function ARN or EC2 instance type drove the spike.
import { GetAnomaliesCommand } from "@aws-sdk/client-cost-explorer";
const { Anomalies } = await ce.send(new GetAnomaliesCommand({
MonitorArn,
DateInterval: {
StartDate: "2026-11-01",
EndDate: "2026-11-15",
},
Feedback: "YES", // only confirmed anomalies, not false-positives
}));
for (const anomaly of Anomalies ?? []) {
console.log(`Anomaly: $${anomaly.Impact?.TotalImpact} total impact`);
for (const rc of anomaly.RootCauses ?? []) {
console.log(` ${rc.Service} / ${rc.Region} / ${rc.UsageType}: ${rc.LinkedAccount}`);
}
}
Detection latency: Anomaly Detection has a 12–36 hour detection latency — it typically takes 1–2 days of data before the first model is trained, and anomalies from a given day appear in GetAnomaliesCommand results the next morning. This is fast enough to catch runaway loops that persist for hours but not fast enough to stop a 15-minute burst. For sub-hour alerting, AWS CloudWatch Alarms on Lambda Errors and Throttles metrics are the right tool (outside the cost management layer).
Where Anomaly Detection alone fails: It tells you that Lambda costs spiked and identifies which function drove it. It does not tell you whether that function was already over-provisioned before the spike — whether you were wasting money on 3 GB of memory when the function only uses 400 MB. That chronic inefficiency is invisible to any alerting system; it only surfaces in Compute Optimizer.
Layer 4 — Compute Optimizer: the prescriptive rightsizing layer
Compute Optimizer analyses 14 days of CloudWatch utilization metrics for Lambda functions, EC2 instances, ECS services on Fargate, Auto Scaling groups, EBS volumes, and RDS instances. It produces a Finding (OVER_PROVISIONED, UNDER_PROVISIONED, OPTIMIZED, NOT_OPTIMIZED) and a set of option recommendations with estimated monthly savings. For MCP server teams, Lambda and ECS Fargate are the two resource types that consistently have actionable findings — Lambda memory over-provisioning is the most common cost inefficiency in serverless-first architectures.
Compute Optimizer requires explicit opt-in before any recommendations appear. This is a one-time operation per account:
import {
ComputeOptimizerClient,
UpdateEnrollmentStatusCommand,
GetEnrollmentStatusCommand,
} from "@aws-sdk/client-compute-optimizer";
const optimizer = new ComputeOptimizerClient({ region: "us-east-1" });
const { Status } = await optimizer.send(new GetEnrollmentStatusCommand({}));
if (Status !== "ACTIVE") {
await optimizer.send(new UpdateEnrollmentStatusCommand({
Status: "Active", // title-case in input, UPPERCASE in response — SDK inconsistency
IncludeMemberAccounts: false,
}));
// First recommendations available in 24-48 hours
}
After the opt-in window, query Lambda function recommendations filtered to over-provisioned functions:
import { GetLambdaFunctionRecommendationsCommand } from "@aws-sdk/client-compute-optimizer";
const { LambdaFunctionRecommendations } = await optimizer.send(
new GetLambdaFunctionRecommendationsCommand({
Filters: [{ name: "Finding", values: ["OVER_PROVISIONED"] }],
MaxResults: 50,
})
);
for (const rec of LambdaFunctionRecommendations ?? []) {
const savings = rec.MemorySizeRecommendationOptions?.[0]?.SavingsOpportunity;
console.log(
`${rec.FunctionArn}: ${rec.MemorySize}MB → ` +
`${rec.MemorySizeRecommendationOptions?.[0]?.MemorySize}MB, ` +
`est. $${savings?.EstimatedMonthlySavings?.Value}/month savings`
);
}
For ECS Fargate, the query is GetECSServiceRecommendationsCommand. The critical prerequisite is Container Insights — Compute Optimizer can only analyse ECS services where Container Insights is enabled on the cluster. Without it, the finding returns NOT_OPTIMIZED with the reason InsufficientData:
import { GetECSServiceRecommendationsCommand } from "@aws-sdk/client-compute-optimizer";
const { EcsServiceRecommendations } = await optimizer.send(
new GetECSServiceRecommendationsCommand({
filters: [{ name: "Finding", values: ["OVER_PROVISIONED"] }],
})
);
for (const rec of EcsServiceRecommendations ?? []) {
for (const opt of rec.serviceRecommendationOptions ?? []) {
console.log(
`${rec.serviceArn}: ` +
`${rec.currentServiceConfiguration?.cpu} CPU / ${rec.currentServiceConfiguration?.memory} memory → ` +
`${opt.containerRecommendations?.[0]?.memorySizeConfiguration?.memory} memory, ` +
`${opt.savingsOpportunity?.estimatedMonthlySavings?.value} savings/month`
);
}
}
Where Compute Optimizer alone fails: It has no alerting. If you only run Compute Optimizer, you have to remember to query it — it doesn't tell you when a new over-provisioned function appears. Pairing it with a weekly MCP tool that queries recommendations and posts a Slack digest closes that gap. And it still doesn't tell you when costs are running away from normal patterns in real-time — that remains Anomaly Detection's job.
Wiring all four into an integrated cost observability workflow
The practical integration pattern is: install all four services, wire a shared SNS topic to both Budgets and Anomaly Detection, and schedule a weekly Compute Optimizer digest. The SNS topic receives two classes of cost alerts — threshold-based (Budgets) and pattern-based (Anomaly Detection) — and routes both to your team's alert channel. Compute Optimizer runs on demand or via a scheduled Lambda, not in the alert path.
// Consolidated IAM policy for all four cost services
const costPolicy = {
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: [
// Cost Explorer (includes Anomaly Detection)
"ce:GetCostAndUsage",
"ce:GetCostForecast",
"ce:GetDimensionValues",
"ce:GetTags",
"ce:CreateAnomalyMonitor",
"ce:CreateAnomalySubscription",
"ce:GetAnomalies",
"ce:GetAnomalyMonitors",
"ce:GetAnomalySubscriptions",
"ce:ProvideAnomalyFeedback",
// Budgets
"budgets:CreateBudget",
"budgets:DescribeBudgets",
"budgets:UpdateBudget",
"budgets:DeleteBudget",
"budgets:DescribeBudgetActionsForBudget",
// Compute Optimizer
"compute-optimizer:GetEnrollmentStatus",
"compute-optimizer:UpdateEnrollmentStatus",
"compute-optimizer:GetLambdaFunctionRecommendations",
"compute-optimizer:GetEC2InstanceRecommendations",
"compute-optimizer:GetECSServiceRecommendations",
],
Resource: "*", // cost APIs cannot be scoped to specific resources
},
],
};
The four MCP tools that map to this stack:
| Tool name | Parameters | Returns | Calls |
|---|---|---|---|
get_cost_breakdown |
startDate, endDate, groupBy (SERVICE | TAG), tagKey? |
Ranked list of services/tags by cost | GetCostAndUsageCommand |
get_cost_forecast |
endDate, granularity |
Forecasted spend + confidence interval | GetCostForecastCommand |
get_active_anomalies |
monitorArn, startDate, endDate |
List of anomalies with root causes and impact | GetAnomaliesCommand |
get_rightsizing_opportunities |
resourceType (lambda | ecs | ec2), finding? |
Over-provisioned resources with estimated savings | Get[ResourceType]RecommendationsCommand |
The coverage gaps without each layer
To make the dependency concrete: here are the specific incidents that each service catches that the others miss.
| Incident type | Caught by | Missed by |
|---|---|---|
| Lambda retry loop runs for 6 hours, $150 extra spend | Anomaly Detection (pattern deviation) | Budgets (still under monthly threshold), Cost Explorer (day-delayed data) |
| Month-to-date spend is on track to exceed budget by 15% | Budgets (FORECASTED alert) | Cost Explorer (no alerting), Anomaly Detection (not an anomaly — consistent growth pattern) |
| Lambda function is provisioned at 3 GB, uses 400 MB every invocation | Compute Optimizer (OVER_PROVISIONED finding) | All others (no spend spike, no threshold crossing — just silent waste) |
| Which service cost the most last quarter, broken down by team? | Cost Explorer (historical query with GroupBy TAG) | All others (Budgets and Anomaly Detection have no historical query surface) |
| ECS Fargate task over-provisioned; Container Insights not enabled | Neither Compute Optimizer nor any other cost service — requires enabling Container Insights first | All — blind spot until Container Insights is active |
The last row is worth emphasizing: Compute Optimizer has a hard dependency on CloudWatch data being available. For Lambda, invocation metrics flow to CloudWatch automatically — no configuration needed. For ECS, Container Insights must be enabled on the cluster or Compute Optimizer returns InsufficientData for all services on that cluster. For EC2, the CloudWatch Agent must be installed for memory metrics; without it, Compute Optimizer can only see CPU utilization, which makes memory-based rightsizing recommendations unavailable.
Operational considerations for MCP server builders
Three implementation details that trip up MCP server builders working across all four services:
1. All four cost services use us-east-1
Cost Explorer, AWS Budgets, and Cost Anomaly Detection all require region: "us-east-1" — they are global services with single endpoints. Compute Optimizer is regional, but for most queries targeting Lambda or ECS in a single account, instantiating the client with the account's primary region works. The common mistake is using an environment variable like AWS_DEFAULT_REGION that points to a non-us-east-1 region — Cost Explorer and Budgets return InvalidParameterException or connection errors that look like network issues but are actually region misrouting.
2. Cost Explorer quota is per-account, shared across all callers
The Cost Explorer API has a limit of 1,500 requests per day per account. This quota is shared across all callers: the AWS console, all SDK clients, all MCP server instances. HOURLY granularity queries are particularly expensive — a single HOURLY query covering 14 days returns 336 time periods and uses approximately 1 quota unit, but the console's billing dashboard also makes HOURLY calls. For MCP server tools, cache GetCostAndUsageCommand MONTHLY results (they don't change more than once per day) and avoid HOURLY queries from tool invocations unless the user explicitly requests last-N-hours granularity.
3. Anomaly Detection latency means it's not real-time
The 12–36 hour detection latency is a hard constraint of the ML pipeline. When a runaway Lambda loop fires at 2 AM, Cost Explorer has day-delayed data, Anomaly Detection won't surface the anomaly until the next morning at the earliest, and Budgets fires only if the total crossed a threshold. The gap is intentional — AWS trades detection latency for accuracy (fewer false positives). For real-time cost anomaly detection (sub-hour), the right tool is CloudWatch Alarms on EstimatedCharges metric with an SNS action — that fires within minutes but requires manually set thresholds. Many teams run both: CloudWatch Alarms for immediate large-dollar incidents, Anomaly Detection for sustained-but-below-threshold deviations over days.
Package installation summary
All four services require separate installs (except Anomaly Detection, which is part of the Cost Explorer package):
# Cost Explorer + Anomaly Detection (same package)
npm install @aws-sdk/client-cost-explorer
# AWS Budgets
npm install @aws-sdk/client-budgets
# Compute Optimizer
npm install @aws-sdk/client-compute-optimizer
Client instantiation pattern for all four — region discipline is the most important configuration:
import { CostExplorerClient } from "@aws-sdk/client-cost-explorer";
import { BudgetsClient } from "@aws-sdk/client-budgets";
import { ComputeOptimizerClient } from "@aws-sdk/client-compute-optimizer";
// Cost Explorer, Budgets, Anomaly Detection: always us-east-1
const ce = new CostExplorerClient({ region: "us-east-1" });
const budgets = new BudgetsClient({ region: "us-east-1" });
// Compute Optimizer: regional — use the region where your resources live
const optimizer = new ComputeOptimizerClient({ region: process.env.AWS_REGION ?? "us-east-1" });
Where AliveMCP fits
AliveMCP monitors the operational health of your MCP server endpoints — not the AWS billing layer. The two monitoring surfaces are complementary: AliveMCP tells you when your MCP server is down or returning malformed responses; the four AWS cost services tell you when the infrastructure running that server is behaving unexpectedly from a cost perspective. A runaway Lambda retry loop surfaces in both: AliveMCP sees the error rate spike on the endpoint, Anomaly Detection sees the cost spike two hours later. Running both lets you correlate the operational incident with its billing consequence — and gives you the evidence to right-size the function afterward with Compute Optimizer.
Related pages
- AWS Cost Explorer for MCP Servers — Query Costs and Forecasts with the SDK
- AWS Budgets for MCP Servers — Cost Thresholds, Alerts, and Budget Management
- AWS Cost Anomaly Detection for MCP Servers — Detect Unexpected Spend Spikes
- AWS Compute Optimizer for MCP Servers — Rightsize Lambda, EC2, and ECS
- MCP Server CloudWatch Alarms — real-time metric alerting for operational incidents
- MCP Server Lambda Provisioned Concurrency — eliminate cold starts and control costs
- MCP Server ECS Service Autoscaling — scale Fargate tasks on demand
- MCP Server Observability Stack — metrics, traces, logs, and health endpoints
- Building MCP Tools for Data Infrastructure — PostgreSQL, MySQL, S3, Kafka, and DSPy