Guide · AWS Cost Explorer · Cost Management
AWS Cost Explorer for MCP Servers — Query Costs and Forecasts with the SDK
AWS Cost Explorer gives MCP server tools programmatic access to your account's cost and usage data — the same data behind the AWS console billing dashboards, but queryable by service, region, tag, account, and time granularity. For MCP server builders, Cost Explorer unlocks tools like "show me this month's Lambda spend by function," "forecast our EC2 cost through end of quarter," or "which team's resources are over budget?" All through a single API surface with the @aws-sdk/client-cost-explorer package. This guide covers the SDK end-to-end: querying costs, grouping by dimensions and tags, filtering, paginating, and forecasting.
TL;DR
Cost Explorer has three primary queries: GetCostAndUsage (historical actuals with groupBy and filter), GetCostForecast (predicted spend through a future date), and GetDimensionValues (discover valid filter values). Every call requires a TimePeriod with Start and End in YYYY-MM-DD format, a Granularity (DAILY, MONTHLY, or HOURLY — HOURLY only for the last 14 days), and one or more Metrics. 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. The IAM action is ce:GetCostAndUsage; it cannot be scoped to resources.
Package installation and client setup
Cost Explorer lives in its own SDK package separate from the main AWS SDK services:
npm install @aws-sdk/client-cost-explorer
The client must always use us-east-1 — Cost Explorer has a single global endpoint and returns InvalidParameterException if you specify any other region:
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" });
GetCostAndUsage — the core query
GetCostAndUsageCommand returns a time series of cost and usage data. The minimum required fields are TimePeriod, Granularity, and Metrics:
import {
CostExplorerClient,
GetCostAndUsageCommand,
} from "@aws-sdk/client-cost-explorer";
const ce = new CostExplorerClient({ region: "us-east-1" });
const response = await ce.send(new GetCostAndUsageCommand({
TimePeriod: {
Start: "2026-10-01",
End: "2026-11-01", // exclusive — Nov 1 means "through Oct 31"
},
Granularity: "MONTHLY",
Metrics: ["BlendedCost", "UsageQuantity"],
}));
for (const result of response.ResultsByTime ?? []) {
const cost = result.Total?.BlendedCost;
console.log(`${result.TimePeriod?.Start}: $${cost?.Amount} ${cost?.Unit}`);
}
Metric types
Cost Explorer supports six metric types. Picking the right one avoids confusing numbers:
| Metric | What it measures | When to use |
|---|---|---|
BlendedCost |
Blended rate across all accounts in an organization | Default for most queries; smooths RI/SP savings across accounts |
UnblendedCost |
Actual per-account charge at list price or discounted rate | Single-account; shows what each account actually paid |
AmortizedCost |
Upfront RI/SP fees spread daily over the reservation term | Best for forecasting and trend analysis — no RI upfront cost spikes |
NetAmortizedCost |
AmortizedCost minus AWS private pricing discounts | Enterprise discount program accounts |
UsageQuantity |
Units consumed (GB, hours, requests) | Pair with a service filter for capacity planning |
NormalizedUsageAmount |
EC2 usage normalized to m1.small equivalent hours | RI utilization analysis |
GroupBy — slice costs by dimension or tag
GroupBy lets you break costs down by one or two dimensions. Up to two group-by entries are supported at once:
// Group monthly costs by AWS service
const byService = await ce.send(new GetCostAndUsageCommand({
TimePeriod: { Start: "2026-10-01", End: "2026-11-01" },
Granularity: "MONTHLY",
Metrics: ["UnblendedCost"],
GroupBy: [{ Type: "DIMENSION", Key: "SERVICE" }],
}));
for (const result of byService.ResultsByTime ?? []) {
for (const group of result.Groups ?? []) {
const svc = group.Keys?.[0];
const cost = group.Metrics?.UnblendedCost;
console.log(` ${svc}: $${cost?.Amount}`);
}
}
Common DIMENSION keys:
| Key | What it splits on |
|---|---|
SERVICE |
AWS service name (e.g., "Amazon EC2", "AWS Lambda") |
REGION |
AWS region code (e.g., "us-east-1") |
LINKED_ACCOUNT |
12-digit account ID (useful in Organizations) |
INSTANCE_TYPE |
EC2 instance type (e.g., "t3.medium") |
USAGE_TYPE |
Detailed usage type string (e.g., "USW2-BoxUsage:t3.medium") |
OPERATION |
API operation (e.g., "RunInstances", "PutObject") |
PURCHASE_TYPE |
On-Demand, Spot, Reserved Instance, Savings Plans |
AZ |
Availability zone |
Group by tag
Grouping by cost allocation tags lets you attribute costs to teams, projects, or environments. Tags must be activated in the Billing console before they appear in Cost Explorer:
// Group by the "team" cost allocation tag
const byTeam = await ce.send(new GetCostAndUsageCommand({
TimePeriod: { Start: "2026-10-01", End: "2026-11-01" },
Granularity: "MONTHLY",
Metrics: ["UnblendedCost"],
GroupBy: [{ Type: "TAG", Key: "team" }],
}));
for (const result of byTeam.ResultsByTime ?? []) {
for (const group of result.Groups ?? []) {
// Keys[0] is formatted as "team$" — split on "$"
const [, teamName] = (group.Keys?.[0] ?? "").split("$");
const cost = group.Metrics?.UnblendedCost;
console.log(` team=${teamName || "(untagged)"}: $${cost?.Amount}`);
}
}
Key format for tag groups is "<tagKey>$<tagValue>". Resources without the tag appear as "<tagKey>$" (empty value after the $).
Filter expressions — narrow results before grouping
The Filter parameter uses a nested expression tree with And, Or, Not, Dimensions, Tags, and CostCategories nodes:
import {
CostExplorerClient,
GetCostAndUsageCommand,
} from "@aws-sdk/client-cost-explorer";
const ce = new CostExplorerClient({ region: "us-east-1" });
// Lambda costs only, in us-east-1 and us-west-2
const lambdaCosts = await ce.send(new GetCostAndUsageCommand({
TimePeriod: { Start: "2026-10-01", End: "2026-11-01" },
Granularity: "DAILY",
Metrics: ["UnblendedCost"],
Filter: {
And: [
{
Dimensions: {
Key: "SERVICE",
Values: ["AWS Lambda"],
MatchOptions: ["EQUALS"],
},
},
{
Dimensions: {
Key: "REGION",
Values: ["us-east-1", "us-west-2"],
MatchOptions: ["EQUALS"],
},
},
],
},
}));
MatchOptions controls how the value list is applied:
| MatchOption | Behavior |
|---|---|
EQUALS |
Exact match — default for dimensions |
STARTS_WITH |
Prefix match — useful for USAGE_TYPE filtering |
ENDS_WITH |
Suffix match |
CONTAINS |
Substring match |
ABSENT |
Resource has no value for this dimension (useful with tags) |
GetCostForecast — predict future spend
GetCostForecastCommand uses historical data to project costs through a future date. The TimePeriod must start in the future (tomorrow or later):
import {
CostExplorerClient,
GetCostForecastCommand,
} from "@aws-sdk/client-cost-explorer";
const ce = new CostExplorerClient({ region: "us-east-1" });
// Forecast total cost for the rest of Q4
const today = new Date();
const startDate = new Date(today);
startDate.setDate(today.getDate() + 1); // tomorrow
const forecast = await ce.send(new GetCostForecastCommand({
TimePeriod: {
Start: startDate.toISOString().split("T")[0],
End: "2026-12-31",
},
Granularity: "MONTHLY",
Metric: "UNBLENDED_COST", // note: singular "Metric" (not Metrics)
}));
const total = forecast.Total;
console.log(`Forecasted total: $${total?.Amount} ${total?.Unit}`);
// MeanValue ± (UpperBound - LowerBound) gives the confidence interval
for (const point of forecast.ForecastResultsByTime ?? []) {
console.log(
`${point.TimePeriod?.Start}: mean=$${point.MeanValue} ` +
`[${point.PredictionIntervalLowerBound}–${point.PredictionIntervalUpperBound}]`
);
}
The prediction interval represents 80% confidence by default (PredictionIntervalLevel defaults to 80). You can narrow it to 95 for a wider band, or 70 for a tighter one. Forecasts are unavailable for accounts with fewer than three months of billing history — the API returns DataUnavailableException.
Pagination with NextPageToken
Results are paginated when GroupBy produces many groups or the time range spans many days. Use the NextPageToken for continuation:
async function getAllCostResults(params: Parameters<typeof ce.send>[0]) {
const results = [];
let nextPageToken: string | undefined;
do {
const response = await ce.send(
new GetCostAndUsageCommand({
...params as any,
NextPageToken: nextPageToken,
})
);
results.push(...(response.ResultsByTime ?? []));
nextPageToken = response.NextPageToken;
} while (nextPageToken);
return results;
}
GetDimensionValues — discover valid filter values
Before filtering, you may not know exactly which service names or account IDs exist in your data. GetDimensionValuesCommand returns the actual values present in a time range:
import {
CostExplorerClient,
GetDimensionValuesCommand,
} from "@aws-sdk/client-cost-explorer";
const ce = new CostExplorerClient({ region: "us-east-1" });
// List all services that generated cost last month
const dimensions = await ce.send(new GetDimensionValuesCommand({
TimePeriod: { Start: "2026-10-01", End: "2026-11-01" },
Dimension: "SERVICE",
}));
for (const dv of dimensions.DimensionValues ?? []) {
console.log(dv.Value); // e.g., "Amazon EC2", "AWS Lambda", "Amazon S3"
}
// List all active cost allocation tag values for "environment"
const tagValues = await ce.send(new GetDimensionValuesCommand({
TimePeriod: { Start: "2026-10-01", End: "2026-11-01" },
Dimension: "TAG",
// Not needed for dimensions — but for tags use GetTags instead:
}));
For tag values specifically, use GetTagsCommand which accepts a TagKey parameter:
import { GetTagsCommand } from "@aws-sdk/client-cost-explorer";
const tags = await ce.send(new GetTagsCommand({
TimePeriod: { Start: "2026-10-01", End: "2026-11-01" },
TagKey: "environment", // returns "prod", "staging", "dev" etc.
}));
console.log(tags.Tags); // string[]
Complete MCP tool: query costs by service
Here is a production-ready MCP tool that returns last-month costs grouped by service:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
CostExplorerClient,
GetCostAndUsageCommand,
} from "@aws-sdk/client-cost-explorer";
import { z } from "zod";
const ce = new CostExplorerClient({ region: "us-east-1" });
const server = new McpServer({ name: "cost-explorer-tool", version: "1.0.0" });
function lastMonthRange(): { Start: string; End: string } {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
const end = new Date(now.getFullYear(), now.getMonth(), 1);
const fmt = (d: Date) => d.toISOString().split("T")[0];
return { Start: fmt(start), End: fmt(end) };
}
server.tool(
"get_aws_costs_by_service",
"Return last-month AWS costs grouped by service, sorted descending by cost",
{
top_n: z.number().int().min(1).max(50).default(10)
.describe("Number of top services to return"),
metric: z.enum(["BlendedCost", "UnblendedCost", "AmortizedCost"])
.default("UnblendedCost"),
},
async ({ top_n, metric }) => {
const response = await ce.send(new GetCostAndUsageCommand({
TimePeriod: lastMonthRange(),
Granularity: "MONTHLY",
Metrics: [metric],
GroupBy: [{ Type: "DIMENSION", Key: "SERVICE" }],
}));
const groups = response.ResultsByTime?.[0]?.Groups ?? [];
const sorted = groups
.map(g => ({
service: g.Keys?.[0] ?? "Unknown",
amount: parseFloat(g.Metrics?.[metric]?.Amount ?? "0"),
unit: g.Metrics?.[metric]?.Unit ?? "USD",
}))
.filter(g => g.amount > 0)
.sort((a, b) => b.amount - a.amount)
.slice(0, top_n);
const timePeriod = response.ResultsByTime?.[0]?.TimePeriod;
const lines = sorted.map(
g => ` ${g.service}: $${g.amount.toFixed(2)} ${g.unit}`
);
return {
content: [{
type: "text",
text: [
`AWS costs by service (${metric}) — ${timePeriod?.Start} to ${timePeriod?.End}`,
"",
...lines,
"",
`Total shown: $${sorted.reduce((s, g) => s + g.amount, 0).toFixed(2)} USD`,
].join("\n"),
}],
};
}
);
server.tool(
"forecast_aws_cost",
"Forecast AWS spend through end of month or a specified date using Cost Explorer",
{
end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/)
.describe("Forecast through this date (YYYY-MM-DD), exclusive"),
service: z.string().optional()
.describe("Filter to a specific service name, e.g. 'AWS Lambda'"),
},
async ({ end_date, service }) => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const startStr = tomorrow.toISOString().split("T")[0];
const filter = service
? { Dimensions: { Key: "SERVICE" as const, Values: [service], MatchOptions: ["EQUALS" as const] } }
: undefined;
const { Total, ForecastResultsByTime } = await ce.send(
new GetCostForecastCommand({
TimePeriod: { Start: startStr, End: end_date },
Granularity: "MONTHLY",
Metric: "UNBLENDED_COST",
Filter: filter,
})
);
const lines = (ForecastResultsByTime ?? []).map(p =>
` ${p.TimePeriod?.Start}: ~$${parseFloat(p.MeanValue ?? "0").toFixed(2)} ` +
`[$${parseFloat(p.PredictionIntervalLowerBound ?? "0").toFixed(2)}–` +
`$${parseFloat(p.PredictionIntervalUpperBound ?? "0").toFixed(2)}]`
);
return {
content: [{
type: "text",
text: [
`Cost forecast${service ? ` for ${service}` : ""} through ${end_date}:`,
"",
...lines,
"",
`Forecasted total: ~$${parseFloat(Total?.Amount ?? "0").toFixed(2)} USD`,
"(range is 80% prediction interval)",
].join("\n"),
}],
};
}
);
IAM permissions
Cost Explorer permissions are billing permissions, not service-level ones. They must be granted on the management account or via IAM billing access:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ce:GetCostAndUsage",
"ce:GetCostForecast",
"ce:GetDimensionValues",
"ce:GetTags",
"ce:GetUsageForecast"
],
"Resource": "*"
}
]
}
Note: ce:* actions cannot be scoped to specific resources — the Resource must always be "*". In an AWS Organizations setup, member accounts can only query their own costs unless the management account grants cross-account billing access or uses Cost Explorer's linked-account features.
Common errors
| Error | Cause and fix |
|---|---|
InvalidParameterException: Region not supported |
Client initialized with a region other than us-east-1. Always use region: "us-east-1". |
DataUnavailableException |
Forecast requested but account has fewer than 3 months of billing history, or the time range starts in the past for GetCostForecast. Ensure Start is tomorrow or later. |
BillExpiredException |
TimePeriod.End is older than 13 months. Cost Explorer retains data for 13 months. |
LimitExceededException |
Default rate limit is 20 requests per second per API. Add exponential backoff with jitter. |
AccessDeniedException |
Missing ce: permissions or IAM billing access is disabled at the account level. Enable "Activate IAM access" in Billing preferences. |
RequestChangeTooLarge |
Filter or GroupBy combination produces too many result groups. Add more filters to narrow the query. |
HOURLY granularity constraints
HOURLY granularity is only available for the last 14 days. It also supports only a subset of dimensions in GroupBy: SERVICE, USAGE_TYPE, and OPERATION. Using REGION, LINKED_ACCOUNT, or tags with HOURLY returns InvalidParameterException. HOURLY data also becomes available with a delay of up to 24 hours for some services, so recent hours may show $0.00 until billing data catches up.
Cost allocation tags — activation required
Tags only appear in Cost Explorer after they are activated as cost allocation tags. The activation process:
- Apply tags to AWS resources (e.g.,
team=platform,env=prod) - Go to Billing → Cost allocation tags (or use
ce:CreateCostCategoryDefinitionfor programmatic activation) - Activate the tag keys — there is a delay of up to 24 hours before activated tags appear in Cost Explorer data
- Tags only appear in Cost Explorer data from the activation date forward — historical data before activation is not retroactively tagged
To discover which tag keys are already active: use ListCostAllocationTagsCommand with Status: "Active". To activate new keys programmatically: UpdateCostAllocationTagsStatusCommand (requires ce:UpdateCostAllocationTagsStatus permission on the management account).