Skip to main content
Glama
oldcoder01
by oldcoder01

cost_explorer_by_service

Analyze AWS service costs to identify spending patterns and optimize resource allocation for better budget management.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
daysNo
top_nNo
authNo

Implementation Reference

  • 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()}

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/oldcoder01/aws-mcp-audit'

If you have feedback or need assistance with the MCP directory API, please join our Discord server