Metadata-Version: 2.5
Name: aws-iac-cost-estimator-mcp-server
Version: 0.1.0
Summary: An MCP server that estimates AWS monthly costs from Terraform and CDK infrastructure-as-code files
Author-email: Sarath Kumar Kallayil Sreedharan <ssars@amazon.com>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: aws,cdk,cost,infrastructure,mcp,pricing,terraform
Requires-Python: >=3.10
Requires-Dist: boto3>=1.28.0
Requires-Dist: mcp<2.0.0,>=1.0.0
Requires-Dist: python-hcl2<5.0.0,>=4.0.0
Requires-Dist: pyyaml<7.0,>=6.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Description-Content-Type: text/markdown

# AWS IaC Cost Estimator MCP Server

An MCP server that estimates monthly AWS costs from Terraform and CDK infrastructure-as-code files **before deployment**.

> "What will this infrastructure cost?" — answered at authoring time, not after the bill arrives.

## Why?

AWS has separate MCP servers for [Pricing](https://github.com/awslabs/mcp/tree/main/src/aws-pricing-mcp-server) (manual lookup) and [IaC](https://github.com/awslabs/mcp/tree/main/src/aws-iac-mcp-server) (authoring help), but nothing that **combines them** — automatically reading your infrastructure code and estimating the cost. This server bridges that gap.

## Features

- **Terraform Support**: Parses `.tf` files and extracts AWS resource declarations
- **CloudFormation Support**: Parses YAML/JSON templates with intrinsic function handling
- **CDK Support**: Reads synthesized CloudFormation from `cdk.out/` (any CDK language)
- **Terraform Plan Support**: Parses `terraform show -json` output for accurate estimates with resolved variables
- **50+ Resource Types**: EC2, RDS, Aurora, DynamoDB, ElastiCache, Redshift, OpenSearch, Lambda, ECS/EKS, S3, EBS, EFS, ALB/NLB, NAT GW, API Gateway, CloudFront, VPC Endpoints, Transit GW, Route 53, SQS, SNS, Kinesis, Step Functions, MQ, KMS, WAF, GuardDuty, SageMaker, Cognito, EventBridge, and more
- **Nested Stack Resolution**: Automatically downloads and parses nested CloudFormation stacks (local paths + public S3 URLs)
- **SAM Support**: Recognizes `AWS::Serverless::Function` and `AWS::Serverless::Api`
- **Free Resource Recognition**: IAM roles, policies, security groups, SSM resources etc. recognized as $0 (not "unsupported")
- **Cost Diff**: Compare two versions of IaC and see cost impact (PR-ready markdown)
- **Smart Usage Questions**: Proactively asks about usage-based services with impact ranges
- **Multi-Region Comparison**: Compare costs across regions to find the cheapest
- **API Caching**: Avoids duplicate pricing API calls for the same instance types
- **Path Security**: Validates all inputs to prevent access to sensitive directories
- **On-Demand Pricing**: Queries the live AWS Price List API
- **MCP Compatible**: Works with Kiro, Cursor, VS Code, Claude Code, Cline, Windsurf

## Quick Start

### Install

```bash
# Using uvx (recommended)
uvx aws-iac-cost-estimator-mcp-server@latest

# Or install with pip
pip install aws-iac-cost-estimator-mcp-server
```

### How It Works

1. **You run it** — point at your Terraform/CDK/CloudFormation project
2. **It estimates** — instance-based resources (EC2, RDS) get accurate pricing immediately
3. **It asks** — for usage-based resources (Lambda, S3, DynamoDB), it asks you about expected usage
4. **You answer or skip** — provide your estimates for accuracy, or say "skip" to use defaults
5. **You get results** — full breakdown with confidence indicators (✅ accurate, ⚠️ estimated)

No config files needed. No setup beyond AWS credentials. Just run and go.

### Quick CLI (for testing)

```bash
cd aws-iac-cost-estimator-mcp-server
source .venv/bin/activate
python3 estimate.py /path/to/your/terraform
python3 estimate.py /path/to/template.yaml
python3 estimate.py /path/to/cdk-project --type cdk
```

### Configure in Kiro

Add to `~/.kiro/settings/mcp.json`:

```json
{
  "mcpServers": {
    "aws-iac-cost-estimator": {
      "command": "uvx",
      "args": ["aws-iac-cost-estimator-mcp-server@latest"],
      "env": {
        "AWS_REGION": "us-east-1",
        "AWS_PROFILE": "your-profile"
      }
    }
  }
}
```

### Configure in Cursor

Add to `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "aws-iac-cost-estimator": {
      "command": "uvx",
      "args": ["aws-iac-cost-estimator-mcp-server@latest"],
      "env": {
        "AWS_REGION": "us-east-1"
      }
    }
  }
}
```

## Usage Examples

### Estimate a Terraform project

> "Estimate the monthly cost for my Terraform project in ./infrastructure"

The server will:
1. Parse all `.tf` files in the directory
2. Extract AWS resources (EC2 instances, RDS databases, load balancers, etc.)
3. Query the AWS Price List API for each resource
4. Return a total monthly and annual estimate

### Estimate from a Terraform plan

```bash
# Generate plan JSON
terraform plan -out=tfplan
terraform show -json tfplan > plan.json
```

> "Estimate costs from my Terraform plan at ./plan.json"

### Quick single-resource estimate

> "How much would 3 m5.xlarge EC2 instances cost in eu-west-1?"

## Available Tools

| Tool | Description |
|------|-------------|
| `estimate_terraform_cost` | Estimate costs for a Terraform project directory |
| `estimate_tfplan_cost` | Estimate costs from a Terraform plan JSON file |
| `estimate_cloudformation_cost` | Estimate costs from CloudFormation templates (YAML/JSON) |
| `estimate_cdk_cost` | Estimate costs from a CDK project (any language) |
| `estimate_resource_cost` | Estimate cost for a single resource type |
| `cost_diff` | Compare two IaC versions and show cost impact (PR-ready markdown) |
| `compare_region_costs` | Compare costs across multiple AWS regions |
| `list_supported_resources` | List all supported resource types (Terraform + CFN) |

## Supported Resources

> **Note:** The estimator is designed to grow over time. If your IaC contains resources we don't yet support, they will be clearly listed as "skipped" in the output with a coverage percentage, so you always know what's included and what's not. Contributions to add new resource types are welcome!

### What happens with unsupported resources?

The estimator **never silently ignores** resources. If your project has 10 AWS resources and we support 7 of them, the output will show:

```json
{
  "coverage": {
    "estimated_resources": 7,
    "skipped_resources": 3,
    "total_resources_found": 10,
    "coverage_percentage": 70.0,
    "note": "The total estimate only includes supported resources. Actual costs will be HIGHER if skipped resources incur charges."
  },
  "skipped_resources": [
    {"resource_type": "aws_api_gateway_rest_api", "reason": "Resource type not yet supported"},
    {"resource_type": "aws_ebs_volume", "reason": "Resource type not yet supported"},
    {"resource_type": "aws_waf_web_acl", "reason": "Resource type not yet supported"}
  ]
}
```

### Currently Supported

**50 Terraform + 50 CloudFormation resource types** — see the full list with `list_supported_resources` tool or in the Services Roadmap section below.

## Prerequisites

- Python 3.10+
- AWS credentials configured (for Price List API access)
- `pricing:GetProducts` IAM permission (read-only)

### Minimum IAM Policy

```json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["pricing:GetProducts"],
    "Resource": "*"
  }]
}
```

## Privacy & Security

This tool runs **entirely locally**. Your IaC source code never leaves your machine.

The only external call is to the **AWS Price List API** (`pricing:GetProducts`) which receives only generic resource parameters (e.g., `instanceType=m5.large`, `region=us-east-1`) — not your project's code, resource names, file paths, or configuration details.

**Security features:**
- Path validation blocks access to system directories (`/etc`, `~/.aws`, `~/.ssh`)
- File size limits prevent memory exhaustion (50MB per file, 500 files max)
- CDK synth only runs on directories with `cdk.json` present
- No telemetry, no analytics, no data collection
- All processing happens on your machine

## Advanced: Usage File for CI/CD

For CI/CD pipelines or repeated use where interactive questions aren't practical, you can create a `usage.yml` file alongside your IaC. The tool will auto-read it and skip questions.

```yaml
# usage.yml — place in your IaC project root
aws_lambda_function.processor:
  monthly_requests: 5000000
  avg_duration_ms: 200

aws_s3_bucket.assets:
  storage_gb: 500
  monthly_get_requests: 10000000
  monthly_put_requests: 500000

aws_dynamodb_table.sessions:
  monthly_read_units: 2000000
  monthly_write_units: 1000000

aws_nat_gateway.main:
  monthly_data_processed_gb: 250
```

When this file exists, the tool uses it silently — no questions, no defaults, just your numbers.

## Services Roadmap

We're continuously adding support for more AWS services. Here's the current status:

| Category | Services | Status |
|----------|----------|--------|
| **Compute** | EC2, Lambda, ECS (Fargate tasks), EKS, Auto Scaling, Spot Fleet | ✅ Supported |
| **Database** | RDS, Aurora, DynamoDB, ElastiCache, Redshift, OpenSearch, DocumentDB, Neptune | ✅ Supported |
| **Networking** | ALB/NLB, NAT Gateway, CloudFront, API Gateway (REST + HTTP), VPC Endpoints, Transit Gateway, Route 53, EIP, VPN Connection | ✅ Supported |
| **Storage** | S3, EBS (gp3/gp2/io2/io1/st1/sc1), EFS, FSx (Lustre + Windows) | ✅ Supported |
| **Messaging & Integration** | SQS, SNS, Kinesis Data Streams, Kinesis Firehose, Step Functions, Amazon MQ | ✅ Supported |
| **Security** | KMS, Secrets Manager, WAF, GuardDuty, AWS Config | ✅ Supported |
| **Containers** | EKS, ECS (Fargate task definitions), ECR | ✅ Supported |
| **Analytics** | Athena, Glue, Redshift | ✅ Supported |
| **GenAI / ML** | SageMaker (notebooks + endpoints), Bedrock Agent | ✅ Supported |
| **Monitoring** | CloudWatch Logs, CloudWatch Alarms | ✅ Supported |
| **Not yet supported** | Shield, EMR, QuickSight, App Runner, EventBridge, AppSync, MSK, Timestream | 📋 Planned |

**50 Terraform resource types + 50 CloudFormation resource types** covering 30+ AWS services.

**Want a service added?** Open an issue or submit a PR with the resource mapping.

## Sample Output

```json
{
  "region": "us-east-1",
  "total_monthly_estimate_usd": 847.32,
  "total_annual_estimate_usd": 10167.84,
  "resources_found": 6,
  "resource_estimates": [
    {
      "resource_type": "aws_instance",
      "resource_name": "web_server",
      "count": 2,
      "unit_price_usd": 0.096,
      "unit": "Hrs",
      "monthly_cost": 140.16
    },
    {
      "resource_type": "aws_db_instance",
      "resource_name": "main_db",
      "count": 1,
      "unit_price_usd": 0.35,
      "unit": "Hrs",
      "monthly_cost": 255.50
    }
  ],
  "disclaimer": "These are estimates based on On-Demand pricing..."
}
```

## Supported IaC Formats

| Format | Tool | Input |
|--------|------|-------|
| **Terraform** | `estimate_terraform_cost` | Directory with `.tf` files |
| **Terraform Plan** | `estimate_tfplan_cost` | JSON from `terraform show -json` |
| **CloudFormation** | `estimate_cloudformation_cost` | YAML/JSON template file or directory |
| **CDK** | `estimate_cdk_cost` | CDK project (reads `cdk.out/` or runs `cdk synth`) |
| **Any single resource** | `estimate_resource_cost` | Resource type + attributes |
| **Multi-region comparison** | `compare_region_costs` | Project path + list of regions |

## Roadmap

- [x] Terraform HCL file parsing (50 resource types)
- [x] Terraform Plan JSON parsing
- [x] CloudFormation YAML/JSON template parsing (50 resource types)
- [x] CDK project support (via synthesized CloudFormation)
- [x] Multi-region cost comparison
- [x] Single resource quick estimation
- [x] Cost diff between two IaC versions with PR-ready markdown
- [x] Smart usage questions with impact ranges
- [x] usage.yml for CI/CD silent mode
- [x] API response caching
- [x] Path validation security
- [ ] Reserved Instance / Savings Plan comparison
- [ ] Data transfer cost estimation
- [ ] CI/CD integration (GitHub Action for PR comments)
- [ ] Pulumi support

## Contributing

Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## License

Apache-2.0

## Authors

- Sarath Kumar Kallayil Sreedharan (ssars@)

## Changelog

### v0.1.0 (2026-06-12) — Initial Release

- ✅ 50 Terraform + 50 CloudFormation resource types
- ✅ Terraform, CloudFormation, and CDK parsing
- ✅ Live AWS Pricing API for instance-based resources
- ✅ Known fixed prices for networking/security services (NAT GW, ALB, EKS, KMS, etc.)
- ✅ Smart usage questions with impact ranges for usage-based services
- ✅ Cost diff between two IaC versions with PR-ready markdown
- ✅ Multi-region cost comparison
- ✅ usage.yml support for CI/CD pipelines
- ✅ API response caching (avoids duplicate calls)
- ✅ Path validation security (blocks system/sensitive directories)
- ✅ Coverage reporting (skipped/unsupported resources clearly listed)
- ✅ Handles CloudFormation intrinsic functions (!Ref, !GetAtt, etc.)
- ✅ Region auto-detection from Terraform provider or AWS config
- ✅ Simple CLI wrapper (`estimate.py`) for quick testing

---

## Development Notes

This is an active project. Track progress, ideas, and decisions here.

### Testing the project locally

```bash
cd aws-iac-cost-estimator-mcp-server
python3 -m venv .venv
source .venv/bin/activate
pip install -e .

# Estimate a Terraform project
python3 estimate.py examples/sample-infra

# Estimate a CloudFormation template
python3 estimate.py examples/sample-cfn/template.yaml

# Estimate a CDK project
python3 estimate.py examples/sample-cdk --type cdk

# Compare regions
python3 estimate.py examples/sample-infra --region eu-west-1

# Run full test suite
python3 tests/run_tests.py
```

### Testing cost diff

```bash
python3 estimate.py --diff examples/sample-infra examples/sample-infra-v2
```

### Known Limitations

- Terraform modules with remote sources are not resolved (use `terraform plan -json` for accuracy)
- Region multiplier for known-price resources is an approximation (~10-15%)
- Usage-based services use default assumptions unless user provides input or usage.yml
- `python-hcl2` wraps string values in quotes — parser strips them but edge cases may exist

### Architecture Decisions

- **Direct AWS Price List API** — No middleman, no SaaS dependency, all processing stays local
- **MCP-first** — Built as an MCP server so it works in any AI IDE (Kiro, Cursor, VS Code, Claude Code)
- **Parsers return (supported, skipped) tuples** — Users always know coverage percentage
- **Usage file is optional** — Defaults are provided, but accuracy improves with usage.yml
- **PR comment is pre-formatted markdown** — Can be directly pasted into GitHub/GitLab PRs
