Skip to main content
Glama
oldcoder01
by oldcoder01

cost_explorer_by_region

Analyze AWS costs by region to identify spending patterns and optimize resource allocation across your cloud infrastructure.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
daysNo
top_nNo
authNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'cost_explorer_by_region' tool, decorated with @mcp.tool for automatic registration in FastMCP. It builds a Boto3 session and calls the supporting cost_explorer_by_dimension function with dimension set to 'REGION'.
    @mcp.tool
    def cost_explorer_by_region(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="REGION", top_n=top_n)
  • The main handler function for the MCP tool 'cost_explorer_by_region'. It is registered via @mcp.tool decorator, builds a boto3 session from auth, and delegates to the helper function with dimension set to 'REGION'.
    @mcp.tool
    def cost_explorer_by_region(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="REGION", top_n=top_n)
  • Supporting function that performs the actual AWS Cost Explorer API call (ce.get_cost_and_usage) grouped by the given dimension ('REGION' for this tool), processes results to top N by UnblendedCost, handles exceptions.
    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": []}
  • Core helper function that performs the AWS Cost Explorer API call grouped by the specified dimension (e.g., 'REGION' for the tool), processes the response to extract top costs, and handles errors.
    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 based on days back from today.
    def _dates(days: int) -> Dict[str, str]:
        end = datetime.date.today()
        start = end - datetime.timedelta(days=days)
        return {"Start": start.isoformat(), "End": end.isoformat()}
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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