Skip to main content
Glama

get_cost_by_compartment

Retrieve cost breakdown by compartment for Oracle Cloud Infrastructure tenancies to analyze spending across organizational units.

Instructions

Get cost breakdown by compartment for a tenancy.

Args:
    tenant_id: OCID of the tenancy
    time_usage_started: Start time in ISO format (YYYY-MM-DD)
    time_usage_ended: End time in ISO format (YYYY-MM-DD)

Returns:
    List of costs grouped by compartment with total cost per compartment

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tenant_idYes
time_usage_startedYes
time_usage_endedYes

Implementation Reference

  • Core handler function that executes the tool logic: queries OCI Usage API for usage data grouped by compartmentName, aggregates total costs per compartment, and returns the breakdown.
    def get_cost_by_compartment(usage_api_client: oci.usage_api.UsageapiClient,
                                tenant_id: str,
                                time_usage_started: str,
                                time_usage_ended: str) -> List[Dict[str, Any]]:
        """
        Get cost breakdown by compartment.
    
        Args:
            usage_api_client: OCI UsageApi client
            tenant_id: OCID of the tenancy
            time_usage_started: Start time in ISO format (YYYY-MM-DD)
            time_usage_ended: End time in ISO format (YYYY-MM-DD)
    
        Returns:
            List of costs grouped by compartment
        """
        try:
            request_summarized_usages_details = oci.usage_api.models.RequestSummarizedUsagesDetails(
                tenant_id=tenant_id,
                time_usage_started=time_usage_started,
                time_usage_ended=time_usage_ended,
                granularity="DAILY",
                group_by=["compartmentName"]
            )
    
            usage_response = oci.pagination.list_call_get_all_results(
                usage_api_client.request_summarized_usages,
                request_summarized_usages_details=request_summarized_usages_details
            )
    
            # Aggregate by compartment
            compartment_costs = {}
            for item in usage_response.data.items:
                compartment = item.compartment_name
                if compartment not in compartment_costs:
                    compartment_costs[compartment] = {
                        "compartment_name": compartment,
                        "compartment_id": item.compartment_id,
                        "total_cost": 0.0,
                        "currency": item.currency,
                    }
                compartment_costs[compartment]["total_cost"] += float(item.computed_amount) if item.computed_amount else 0.0
    
            result = list(compartment_costs.values())
            logger.info(f"Retrieved cost breakdown for {len(result)} compartments")
            return result
    
        except Exception as e:
            logger.exception(f"Error getting cost by compartment: {e}")
            raise
  • MCP tool registration with @mcp.tool and wrapper function that invokes the core handler using the initialized OCI usage_api client.
    @mcp.tool(name="get_cost_by_compartment")
    @mcp_tool_wrapper(
        start_msg="Getting cost breakdown by compartment...",
        error_prefix="Error getting cost by compartment"
    )
    async def mcp_get_cost_by_compartment(ctx: Context, tenant_id: str, time_usage_started: str,
                                          time_usage_ended: str) -> List[Dict[str, Any]]:
        """
        Get cost breakdown by compartment for a tenancy.
    
        Args:
            tenant_id: OCID of the tenancy
            time_usage_started: Start time in ISO format (YYYY-MM-DD)
            time_usage_ended: End time in ISO format (YYYY-MM-DD)
    
        Returns:
            List of costs grouped by compartment with total cost per compartment
        """
        return get_cost_by_compartment(oci_clients["usage_api"], tenant_id, time_usage_started, time_usage_ended)
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool retrieves cost data but doesn't mention whether this is a read-only operation, requires specific permissions, has rate limits, or involves data freshness considerations. For a tool that likely accesses billing/financial data, this lack of behavioral context is a significant gap.

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

Conciseness4/5

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

The description is well-structured and appropriately sized. It begins with a clear purpose statement, followed by organized sections for 'Args' and 'Returns'. Each sentence serves a specific function without redundancy. Minor improvements could include more explicit formatting, but overall it's efficient and front-loaded.

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

Completeness3/5

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

Given the tool's moderate complexity (3 parameters, no output schema, no annotations), the description is partially complete. It adequately covers parameters and return format but lacks behavioral context and usage guidance. Without annotations or output schema, the description should ideally mention more about authentication needs, error conditions, or data limitations to be fully comprehensive.

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

Parameters4/5

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

The description adds substantial value beyond the input schema, which has 0% description coverage. It clearly explains each parameter's purpose: 'tenant_id: OCID of the tenancy', 'time_usage_started: Start time in ISO format (YYYY-MM-DD)', and 'time_usage_ended: End time in ISO format (YYYY-MM-DD)'. This provides essential semantic context that the schema alone lacks, though it could benefit from mentioning format constraints or examples.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Get cost breakdown by compartment for a tenancy.' It specifies the verb ('Get'), resource ('cost breakdown'), and scope ('by compartment for a tenancy'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from its sibling 'get_cost_by_service' or other cost-related tools, which prevents a perfect score.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'get_cost_by_service' or 'get_cost_usage_summary', nor does it specify prerequisites, exclusions, or appropriate contexts for usage. This leaves the agent without clear direction on tool selection.

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/jopsis/mcp-server-oci'

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