Skip to main content
Glama
aws-cost-mcp

aws-cost-mcp

README.md
# aws-cost-mcp

> An MCP server that lets AI agents (Claude, Cursor, Copilot, any MCP client) answer questions about your AWS bill — with guardrails, caching and zero write access.

![CI](https://img.shields.io/badge/CI-pending-lightgrey) ![npm](https://img.shields.io/badge/npm-unpublished-lightgrey) ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)

```
You: "Why did our AWS bill jump 40% last week?"
Agent → aws-cost-mcp.get_cost_breakdown(groupBy: SERVICE, granularity: DAILY)
Agent → aws-cost-mcp.get_anomalies(last: 14d)
Agent: "Most of the increase comes from NAT Gateway data transfer in us-east-1, starting Tuesday…"
```

---

## Why

Cost questions are some of the most common — and most painful — questions an engineering team asks. The answer lives in Cost Explorer, behind several clicks, filters and tag conventions that only one person on the team understands.

This project exposes AWS Cost Explorer as a **read-only, well-typed MCP server**, so that any agent can investigate spend, explain variations and suggest savings, using the same data a FinOps engineer would.

It was built from real experience migrating a campaign platform to AWS and driving its infrastructure cost down — the questions this server answers are the ones I had to answer by hand.

## Features

| Tool                 | What it does                                                              | AWS API                           |
| -------------------- | ------------------------------------------------------------------------- | --------------------------------- |
| `get_cost_breakdown` | Cost for a period, grouped by service, account, region, tag or usage type | `ce:GetCostAndUsage`              |
| `compare_periods`    | Diff between two periods, ranked by absolute and % change                 | `ce:GetCostAndUsage`              |
| `get_forecast`       | Forecast until end of month / custom date                                 | `ce:GetCostForecast`              |
| `get_anomalies`      | Recent cost anomalies with root causes                                    | `ce:GetAnomalies`                 |
| `get_rightsizing`    | EC2 rightsizing recommendations with estimated savings                    | `ce:GetRightsizingRecommendation` |
| `list_tag_values`    | Discover cost allocation tags so the agent can filter correctly           | `ce:GetTags`                      |

**Prompts**

- `investigate-cost-spike` — guided workflow: compare → break down → attribute by tag → check anomalies → forecast → explain.

**Planned:** the `aws-cost://summary/month-to-date` resource and a `monthly-finops-report` prompt.

### Design principles

- **Read-only by construction.** The server only calls `ce:Get*` APIs. A minimal IAM policy is provided below.
- **Cheap to run.** Cost Explorer charges per API request, so responses are cached in memory (LRU, TTL from `AWS_COST_MCP_CACHE_TTL`, `0` disables it) and concurrent identical requests share one call. Failed calls are never cached.
- **Agent-friendly output.** Responses are compact, sorted and truncated (top-N + "others") to save context tokens. Raw JSON is available with `format: "json"`.
- **Strict input validation.** All tool inputs are validated with Zod; invalid ranges and granularities return actionable errors the agent can fix itself.

## Quick start

### 1. Requirements

- Node.js ≥ 20
- AWS credentials with the policy below (profile, SSO or env vars)
- Cost Explorer enabled in the account

### 2. Use with Claude Desktop / Claude Code / Cursor

```json
{
  "mcpServers": {
    "aws-cost": {
      "command": "npx",
      "args": ["-y", "aws-cost-mcp"],
      "env": {
        "AWS_PROFILE": "my-readonly-profile",
        "AWS_COST_MCP_CACHE_TTL": "900"
      }
    }
  }
}
```

### 3. Run as a remote server (Streamable HTTP)

stdio is the default. For a shared deployment, serve MCP over HTTP instead:

```bash
AWS_COST_MCP_TRANSPORT=http \
AWS_COST_MCP_HTTP_TOKEN="$(openssl rand -hex 24)" \
npx aws-cost-mcp                  # POST http://127.0.0.1:3333/mcp
```

Every request must send `Authorization: Bearer <token>`. The server is stateless (no sessions, so any replica can answer), and `GET /healthz` is open for load balancers. It binds to loopback by default and refuses to start on any other interface without a token. Put TLS in front of it (reverse proxy or load balancer); it speaks plain HTTP.

### 4. Run locally (development)

```bash
git clone https://github.com/VictorCarvalho16/aws-cost-mcp
cd aws-cost-mcp
npm install
npm run dev            # stdio server with hot reload
npm run inspector      # opens the MCP Inspector against the local server
```

## Minimal IAM policy

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ce:GetCostAndUsage",
        "ce:GetCostForecast",
        "ce:GetAnomalies",
        "ce:GetRightsizingRecommendation",
        "ce:GetTags"
      ],
      "Resource": "*"
    }
  ]
}
```

## Configuration

| Variable                     | Default           | Description                                            |
| ---------------------------- | ----------------- | ------------------------------------------------------ |
| `AWS_PROFILE` / `AWS_REGION` | SDK default chain | Standard AWS credentials                               |
| `AWS_COST_MCP_CACHE_TTL`     | `900`             | Cache TTL in seconds                                   |
| `AWS_COST_MCP_MAX_ROWS`      | `15`              | Max rows returned before grouping into "others"        |
| `AWS_COST_MCP_CURRENCY`      | `USD`             | Display currency                                       |
| `AWS_COST_MCP_LOG_LEVEL`     | `info`            | `debug` logs every AWS call (to stderr — never stdout) |
| `AWS_COST_MCP_TRANSPORT`     | `stdio`           | `stdio` or `http` (Streamable HTTP)                    |
| `AWS_COST_MCP_HTTP_HOST`     | `127.0.0.1`       | Interface to bind; non-loopback requires a token       |
| `AWS_COST_MCP_HTTP_PORT`     | `3333`            | Port for the HTTP transport                            |
| `AWS_COST_MCP_HTTP_TOKEN`    | unset             | Bearer token (≥ 16 chars) required on every request    |

## Architecture

```
┌──────────────┐  stdio                    ┌──────────────────────────────┐
│  MCP client  │ ────────────────────────▶ │  aws-cost-mcp                │
│ (Claude etc.)│                           │  ├─ tools/   (Zod schemas)   │
└──────────────┘                           │  ├─ services/cost-explorer.ts│
                                           │  ├─ cache/   (LRU + dedupe)  │
                                           │  └─ format/  (md tables)     │
                                           └──────────────┬───────────────┘
                                                          │ AWS SDK v3
                                                          ▼
                                                 AWS Cost Explorer API
```

```
src/
├── index.ts              # entrypoint (stdio or HTTP transport)
├── http.ts               # stateless Streamable HTTP server with bearer auth
├── server.ts             # McpServer registration (tools, prompts)
├── tools/                # one file per tool: schema + handler
├── prompts/              # guided workflows
├── services/
│   └── cost-explorer.ts  # thin typed wrapper over @aws-sdk/client-cost-explorer
├── cache/                # TTL + LRU cache with in-flight request sharing
├── format/               # markdown/JSON formatters, top-N truncation
├── dates.ts              # UTC date helpers and range checks
└── config.ts
test/
├── unit/                 # handlers with mocked SDK (aws-sdk-client-mock), in-memory MCP, HTTP
└── e2e/                  # the real entrypoint as a child process, over stdio
```

**Stack:** TypeScript · `@modelcontextprotocol/sdk` · AWS SDK v3 · Zod · Vitest · tsup · GitHub Actions

## Testing

```bash
npm test               # unit + e2e tests (no AWS needed — SDK is mocked / never reached)
npm run lint && npm run typecheck
```

## Roadmap

### v0.1 — MVP

- [x] Project scaffold (TypeScript, tsup, Vitest, ESLint, Prettier)
- [x] `get_cost_breakdown` with Zod validation
- [x] Markdown formatter with top-N truncation
- [x] Unit tests with `aws-sdk-client-mock`
- [x] CI on GitHub Actions (lint, typecheck, test)

### v0.2 — Useful

- [x] `compare_periods`, `get_forecast`, `list_tag_values`
- [x] LRU cache + request dedupe
- [x] `investigate-cost-spike` prompt
- [ ] Publish to npm, add to the MCP Registry

### v0.3 — Production-grade (code complete, not yet run against real AWS)

- [x] `get_anomalies`, `get_rightsizing`
- [x] Streamable HTTP transport (for remote/shared deployments)
- [x] E2E tests over stdio
- [ ] Verify against a real AWS account (v0.3 was built and tested against mocks only)
- [ ] Demo GIF in this README
- [ ] Blog post: "Giving an AI agent read-only access to your AWS bill"

### Ideas

- Multi-account (Organizations) support
- Savings Plans / RI coverage tools
- Export a report as CSV resource

## Security

- Never request write permissions — the server has no code path that mutates AWS resources.
- Logs go to **stderr** only (stdout is reserved for the MCP protocol).
- Credentials are resolved by the AWS SDK default chain and never logged or returned to the client.

Found a vulnerability? Please open a private security advisory instead of an issue.

## Contributing

Issues and PRs are welcome. Run `npm test` before opening a PR and follow Conventional Commits.

## License

MIT © Victor Hugo Araújo de Carvalho

TDQS

A4.1/5.0

Scored across 6 tools

Disambiguation5/5

Each tool maps to a distinct cost-analysis task: single-period breakdown, period-over-period diff, forecast, tag discovery, anomaly detection, and rightsizing. The only potential overlap (get_cost_breakdown vs compare_periods) is explicitly clarified by descriptions that differ in output shape and intent. No tool appears to duplicate another's purpose.

Naming Consistency5/5

All six names follow a consistent verb_noun snake_case pattern (get_*, list_*, compare_*). The conventions are predictable and readable throughout, with no mixed casing or stylistic outliers.

Tool Count5/5

Six tools is a tight, well-scoped surface for AWS cost analysis, with each tool earning its place. There is no filler or redundant tool, and the set is not so thin that core workflows would be impossible.

Completeness4/5

The surface covers the main cost lifecycle: breakdown, comparison, forecast, tag discovery, anomalies, and rightsizing. Minor gaps exist around commitment utilization (Savings Plans/RI coverage), budget status, and resource-level cost detail, but agents can work around these for most spend-investigation tasks.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues