cost_explorer_by_service
Analyze AWS service costs to identify spending patterns and optimize resource allocation for better budget management.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| days | No | ||
| top_n | No | ||
| auth | No |
Implementation Reference
- src/aws_mcp_audit/server.py:216-220 (handler)Handler and registration for the 'cost_explorer_by_service' tool using @mcp.tool decorator. Builds AWS session and delegates to cost_explorer_by_dimension with SERVICE dimension.@mcp.tool def cost_explorer_by_service(days: int = 30, top_n: int = 10, auth: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: session = build_boto3_session(auth) return cost_explorer_by_dimension(session, days=days, dimension="SERVICE", top_n=top_n)
- Core helper function implementing AWS Cost Explorer query grouped by dimension (e.g., SERVICE), extracts top N services by UnblendedCost, handles errors and parsing.def cost_explorer_by_dimension(session: boto3.Session, days: int, dimension: str, top_n: int = 10) -> Dict[str, Any]: ce = session.client("ce", region_name="us-east-1") rng = _dates(days) try: resp = ce.get_cost_and_usage( TimePeriod=rng, Granularity="MONTHLY" if days >= 28 else "DAILY", Metrics=["UnblendedCost"], GroupBy=[{"Type": "DIMENSION", "Key": dimension}], ) groups = [] for t in resp.get("ResultsByTime", []): for g in t.get("Groups", []): groups.append( { "keys": g.get("Keys", []), "amount": (g.get("Metrics", {}).get("UnblendedCost", {}) or {}).get("Amount"), "unit": (g.get("Metrics", {}).get("UnblendedCost", {}) or {}).get("Unit"), } ) # naive top_n by amount def amt(x): try: return float(x.get("amount") or 0.0) except Exception: return 0.0 groups.sort(key=amt, reverse=True) return {"time_period": rng, "dimension": dimension, "top": groups[:top_n]} except ClientError as e: return {"time_period": rng, "dimension": dimension, "error": str(e), "top": []}
- Helper utility to compute Start/End dates for Cost Explorer queries.def _dates(days: int) -> Dict[str, str]: end = datetime.date.today() start = end - datetime.timedelta(days=days) return {"Start": start.isoformat(), "End": end.isoformat()}