Skip to main content
Glama
krzko

Google Cloud MCP Server

by krzko

Analyse Billing Costs

gcp-billing-analyse-costs

Analyze Google Cloud billing costs to identify trends, filter by project or service, and optimize spending with detailed insights.

Instructions

Perform detailed cost analysis with trends and insights for Google Cloud billing data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
billingAccountNameYesBilling account name (e.g., 'billingAccounts/123456-789ABC-DEF012')
startDateYesStart date for cost analysis (ISO format: YYYY-MM-DD)
endDateYesEnd date for cost analysis (ISO format: YYYY-MM-DD)
projectIdNoOptional project ID to filter costs
serviceIdNoOptional service ID to filter costs
groupByNoGroup costs by project, service, SKU, or timeservice

Implementation Reference

  • The core handler function for the 'gcp-billing-analyse-costs' tool. It uses mock data to simulate cost analysis, computes percentage changes for trends, formats the output as Markdown, and returns structured content. Note that this is a mock implementation requiring BigQuery export for real data.
    async ({
      billingAccountName,
      startDate,
      endDate,
      projectId,
      serviceId,
      groupBy,
    }) => {
      try {
        logger.debug(
          `Analysing costs for billing account: ${billingAccountName}`,
        );
    
        // Use project hierarchy: provided -> state manager -> auth default
        const actualProjectId =
          projectId ||
          stateManager.getCurrentProjectId() ||
          (await getProjectId());
    
        // Note: This is a mock implementation since BigQuery billing export or
        // Cloud Billing Report API would be needed for actual cost data
        const mockCostData: CostData[] = [
          {
            billingAccountName,
            projectId: actualProjectId || "example-project-1",
            serviceId: serviceId || "compute.googleapis.com",
            cost: { amount: 1250.5, currency: "USD" },
            usage: { amount: 100, unit: "hours" },
            period: { startTime: startDate, endTime: endDate },
            labels: { environment: "production" },
          },
          {
            billingAccountName,
            projectId: actualProjectId || "example-project-2",
            serviceId: serviceId || "storage.googleapis.com",
            cost: { amount: 89.25, currency: "USD" },
            usage: { amount: 500, unit: "GB" },
            period: { startTime: startDate, endTime: endDate },
            labels: { environment: "development" },
          },
        ];
    
        // Calculate trends using our percentage change function
        const previousMonthCosts = [
          { amount: 1150.25, currency: "USD" },
          { amount: 95.75, currency: "USD" },
        ];
    
        let trendsAnalysis = `\n## Cost Trends Analysis\n\n`;
        mockCostData.forEach((cost, index) => {
          const previousCost = previousMonthCosts[index]?.amount || 0;
          const percentageChange = calculatePercentageChange(
            cost.cost.amount,
            previousCost,
          );
          const changeDirection = percentageChange > 0 ? "📈" : "📉";
          const changeIcon = Math.abs(percentageChange) > 20 ? "⚠️" : "✅";
    
          trendsAnalysis += `**${cost.projectId} (${cost.serviceId}):** `;
          trendsAnalysis += `${changeIcon} ${changeDirection} ${percentageChange.toFixed(1)}% `;
          trendsAnalysis += `(${formatCurrency(previousCost)} → ${formatCurrency(cost.cost.amount)})\n`;
        });
    
        let response = `# Cost Analysis\n\n`;
        response += `**Billing Account:** ${billingAccountName}\n`;
        response += `**Period:** ${startDate} to ${endDate}\n`;
        response += `**Grouped By:** ${groupBy}\n\n`;
    
        response += `⚠️ **Note:** This is a demonstration with mock data. `;
        response += `For actual cost analysis, you would need to:\n`;
        response += `1. Enable BigQuery billing export\n`;
        response += `2. Use Cloud Billing Report API\n`;
        response += `3. Query the billing export dataset\n\n`;
    
        response += formatCostData(mockCostData);
        response += trendsAnalysis;
    
        const totalCost = mockCostData.reduce(
          (sum, cost) => sum + cost.cost.amount,
          0,
        );
        response += `\n**Total Cost:** ${formatCurrency(totalCost)}\n`;
    
        return {
          content: [
            {
              type: "text",
              text: response,
            },
          ],
        };
      } catch (error: any) {
        logger.error(`Error analysing costs: ${error.message}`);
        throw new GcpMcpError(
          `Failed to analyse costs: ${error.message}`,
          error.code || "UNKNOWN",
          error.status || 500,
        );
      }
    },
  • Zod input schema defining the parameters for the tool: required billing account and dates, optional filters for project/service, and grouping option.
    inputSchema: {
      billingAccountName: z
        .string()
        .describe(
          "Billing account name (e.g., 'billingAccounts/123456-789ABC-DEF012')",
        ),
      startDate: z
        .string()
        .describe("Start date for cost analysis (ISO format: YYYY-MM-DD)"),
      endDate: z
        .string()
        .describe("End date for cost analysis (ISO format: YYYY-MM-DD)"),
      projectId: z
        .string()
        .optional()
        .describe("Optional project ID to filter costs"),
      serviceId: z
        .string()
        .optional()
        .describe("Optional service ID to filter costs"),
      groupBy: z
        .enum(["project", "service", "sku", "time"])
        .default("service")
        .describe("Group costs by project, service, SKU, or time"),
    },
  • Registration of the 'gcp-billing-analyse-costs' tool on the MCP server using server.registerTool, including title, description, input schema, and handler function.
    server.registerTool(
      "gcp-billing-analyse-costs",
      {
        title: "Analyse Billing Costs",
        description:
          "Perform detailed cost analysis with trends and insights for Google Cloud billing data",
        inputSchema: {
          billingAccountName: z
            .string()
            .describe(
              "Billing account name (e.g., 'billingAccounts/123456-789ABC-DEF012')",
            ),
          startDate: z
            .string()
            .describe("Start date for cost analysis (ISO format: YYYY-MM-DD)"),
          endDate: z
            .string()
            .describe("End date for cost analysis (ISO format: YYYY-MM-DD)"),
          projectId: z
            .string()
            .optional()
            .describe("Optional project ID to filter costs"),
          serviceId: z
            .string()
            .optional()
            .describe("Optional service ID to filter costs"),
          groupBy: z
            .enum(["project", "service", "sku", "time"])
            .default("service")
            .describe("Group costs by project, service, SKU, or time"),
        },
      },
      async ({
        billingAccountName,
        startDate,
        endDate,
        projectId,
        serviceId,
        groupBy,
      }) => {
        try {
          logger.debug(
            `Analysing costs for billing account: ${billingAccountName}`,
          );
    
          // Use project hierarchy: provided -> state manager -> auth default
          const actualProjectId =
            projectId ||
            stateManager.getCurrentProjectId() ||
            (await getProjectId());
    
          // Note: This is a mock implementation since BigQuery billing export or
          // Cloud Billing Report API would be needed for actual cost data
          const mockCostData: CostData[] = [
            {
              billingAccountName,
              projectId: actualProjectId || "example-project-1",
              serviceId: serviceId || "compute.googleapis.com",
              cost: { amount: 1250.5, currency: "USD" },
              usage: { amount: 100, unit: "hours" },
              period: { startTime: startDate, endTime: endDate },
              labels: { environment: "production" },
            },
            {
              billingAccountName,
              projectId: actualProjectId || "example-project-2",
              serviceId: serviceId || "storage.googleapis.com",
              cost: { amount: 89.25, currency: "USD" },
              usage: { amount: 500, unit: "GB" },
              period: { startTime: startDate, endTime: endDate },
              labels: { environment: "development" },
            },
          ];
    
          // Calculate trends using our percentage change function
          const previousMonthCosts = [
            { amount: 1150.25, currency: "USD" },
            { amount: 95.75, currency: "USD" },
          ];
    
          let trendsAnalysis = `\n## Cost Trends Analysis\n\n`;
          mockCostData.forEach((cost, index) => {
            const previousCost = previousMonthCosts[index]?.amount || 0;
            const percentageChange = calculatePercentageChange(
              cost.cost.amount,
              previousCost,
            );
            const changeDirection = percentageChange > 0 ? "📈" : "📉";
            const changeIcon = Math.abs(percentageChange) > 20 ? "⚠️" : "✅";
    
            trendsAnalysis += `**${cost.projectId} (${cost.serviceId}):** `;
            trendsAnalysis += `${changeIcon} ${changeDirection} ${percentageChange.toFixed(1)}% `;
            trendsAnalysis += `(${formatCurrency(previousCost)} → ${formatCurrency(cost.cost.amount)})\n`;
          });
    
          let response = `# Cost Analysis\n\n`;
          response += `**Billing Account:** ${billingAccountName}\n`;
          response += `**Period:** ${startDate} to ${endDate}\n`;
          response += `**Grouped By:** ${groupBy}\n\n`;
    
          response += `⚠️ **Note:** This is a demonstration with mock data. `;
          response += `For actual cost analysis, you would need to:\n`;
          response += `1. Enable BigQuery billing export\n`;
          response += `2. Use Cloud Billing Report API\n`;
          response += `3. Query the billing export dataset\n\n`;
    
          response += formatCostData(mockCostData);
          response += trendsAnalysis;
    
          const totalCost = mockCostData.reduce(
            (sum, cost) => sum + cost.cost.amount,
            0,
          );
          response += `\n**Total Cost:** ${formatCurrency(totalCost)}\n`;
    
          return {
            content: [
              {
                type: "text",
                text: response,
              },
            ],
          };
        } catch (error: any) {
          logger.error(`Error analysing costs: ${error.message}`);
          throw new GcpMcpError(
            `Failed to analyse costs: ${error.message}`,
            error.code || "UNKNOWN",
            error.status || 500,
          );
        }
      },
    );
  • Helper function formatCostData used by the tool handler to generate a Markdown table from CostData array for the analysis report.
    export function formatCostData(costs: CostData[]): string {
      if (costs.length === 0) {
        return "No cost data available for the specified period.";
      }
    
      let result = "## Cost Analysis\n\n";
      result += "| Project | Service | Cost | Usage | Period |\n";
      result += "|---------|---------|------|-------|--------|\n";
    
      for (const cost of costs) {
        const projectId = cost.projectId || "All Projects";
        const serviceId = cost.serviceId || "All Services";
        const formattedCost = formatCurrency(cost.cost.amount, cost.cost.currency);
        const usage = `${cost.usage.amount} ${cost.usage.unit}`;
        const period = `${new Date(cost.period.startTime).toLocaleDateString("en-AU")} - ${new Date(cost.period.endTime).toLocaleDateString("en-AU")}`;
    
        result += `| ${projectId} | ${serviceId} | ${formattedCost} | ${usage} | ${period} |\n`;
      }
    
      return result;
    }
  • Helper function to calculate percentage change between current and previous costs, used for trends analysis in the tool.
    export function calculatePercentageChange(
      current: number,
      previous: number,
    ): number {
      if (previous === 0) return current > 0 ? 100 : 0;
      return ((current - previous) / previous) * 100;
    }
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 mentions 'detailed cost analysis with trends and insights' but lacks critical details such as required permissions, rate limits, whether it's read-only or mutative, output format, or any constraints beyond implied date ranges. This is a significant gap for a tool with multiple parameters and no output schema.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose ('Perform detailed cost analysis') and includes key output details ('trends and insights'). There is no wasted verbiage, and it directly communicates the tool's function without redundancy.

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

Completeness2/5

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

Given the complexity (6 parameters, no annotations, no output schema), the description is inadequate. It doesn't explain what 'trends and insights' entail, how results are structured, or any behavioral traits like permissions or limitations. For a tool that likely returns complex data, more context is needed to guide effective use.

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

Parameters3/5

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

Schema description coverage is 100%, providing clear documentation for all 6 parameters. The description adds no additional parameter semantics beyond what's in the schema, such as explaining interactions between parameters or typical use cases. Baseline 3 is appropriate when the schema does the heavy lifting, though the description could have enhanced understanding of parameter relationships.

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 action ('Perform detailed cost analysis') and resource ('Google Cloud billing data'), with additional context about outputs ('trends and insights'). It distinguishes from siblings like 'gcp-billing-cost-recommendations' or 'gcp-billing-detect-anomalies' by focusing on analysis rather than recommendations or anomaly detection, though not explicitly named.

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?

No explicit guidance on when to use this tool versus alternatives is provided. The description implies usage for cost analysis but doesn't mention prerequisites, constraints, or comparisons to siblings like 'gcp-billing-service-breakdown' or 'gcp-billing-list-accounts', leaving the agent to infer based on tool names alone.

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/krzko/google-cloud-mcp'

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