Skip to main content
Glama
krzko

Google Cloud MCP Server

by krzko

Generate Cost Recommendations

gcp-billing-cost-recommendations

Analyze Google Cloud billing to identify cost optimization opportunities with potential savings, filtering by project, savings amount, and priority level.

Instructions

Generate cost optimisation recommendations with potential savings for Google Cloud billing

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
billingAccountNameYesBilling account name (e.g., 'billingAccounts/123456-789ABC-DEF012')
projectIdNoOptional project ID to filter recommendations
minSavingsAmountNoMinimum savings amount to include in recommendations
priorityNoFilter recommendations by priority levelall

Implementation Reference

  • Tool registration including input schema (Zod), title, description, and inline mock handler function that generates sample cost recommendations, filters them, and returns formatted Markdown response using formatCostRecommendations helper.
      "gcp-billing-cost-recommendations",
      {
        title: "Generate Cost Recommendations",
        description:
          "Generate cost optimisation recommendations with potential savings for Google Cloud billing",
        inputSchema: {
          billingAccountName: z
            .string()
            .describe(
              "Billing account name (e.g., 'billingAccounts/123456-789ABC-DEF012')",
            ),
          projectId: z
            .string()
            .optional()
            .describe("Optional project ID to filter recommendations"),
          minSavingsAmount: z
            .number()
            .min(0)
            .default(10)
            .describe("Minimum savings amount to include in recommendations"),
          priority: z
            .enum(["low", "medium", "high", "all"])
            .default("all")
            .describe("Filter recommendations by priority level"),
        },
      },
      async ({ billingAccountName, projectId, minSavingsAmount, priority }) => {
        try {
          // Use project hierarchy: provided -> state manager -> auth default
          const actualProjectId =
            projectId ||
            stateManager.getCurrentProjectId() ||
            (await getProjectId());
    
          logger.debug(
            `Generating cost recommendations for billing account: ${billingAccountName}, project: ${actualProjectId || "all"}`,
          );
    
          // Mock recommendations for demonstration
          const mockRecommendations: CostRecommendation[] = [
            {
              type: "rightsizing",
              projectId: actualProjectId || "example-project-1",
              serviceId: "compute.googleapis.com",
              resourceName: "instance-group-1",
              description:
                "Compute Engine instances are underutilised and can be right-sized",
              potentialSavings: { amount: 450, currency: "USD", percentage: 30 },
              effort: "medium",
              priority: "high",
              actionRequired:
                "Resize instances from n1-standard-4 to n1-standard-2",
              implementationSteps: [
                "Stop the affected instances during maintenance window",
                "Change machine type from n1-standard-4 to n1-standard-2",
                "Restart instances and monitor performance",
                "Validate application performance meets requirements",
              ],
            },
            {
              type: "idle_resources",
              projectId: actualProjectId || "example-project-2",
              serviceId: "storage.googleapis.com",
              resourceName: "unused-disk-volumes",
              description:
                "Several persistent disks are not attached to any instances",
              potentialSavings: { amount: 125, currency: "USD", percentage: 100 },
              effort: "low",
              priority: "medium",
              actionRequired: "Delete unattached persistent disks",
              implementationSteps: [
                "Verify disks are not needed for backups or future use",
                "Create snapshots if data retention is required",
                "Delete unattached persistent disks",
                "Set up alerts to monitor for future unattached disks",
              ],
            },
          ];
    
          // Filter by minimum savings amount
          const filteredRecommendations = mockRecommendations.filter(
            (rec) => rec.potentialSavings.amount >= minSavingsAmount,
          );
    
          // Filter by priority if specified
          const finalRecommendations =
            priority === "all"
              ? filteredRecommendations
              : filteredRecommendations.filter(
                  (rec) => rec.priority === priority,
                );
    
          let response = `# Cost Optimisation Recommendations\n\n`;
          response += `**Billing Account:** ${billingAccountName}\n`;
          response += `**Minimum Savings:** ${formatCurrency(minSavingsAmount)}\n`;
          response += `**Priority Filter:** ${priority}\n\n`;
    
          response += `⚠️ **Note:** This is a demonstration with mock recommendations. `;
          response += `For actual recommendations, integrate with Google Cloud Recommender API.\n\n`;
    
          response += formatCostRecommendations(finalRecommendations);
    
          if (finalRecommendations.length > 0) {
            const totalSavings = finalRecommendations.reduce(
              (sum, rec) => sum + rec.potentialSavings.amount,
              0,
            );
            response += `\n**Total Potential Savings:** ${formatCurrency(totalSavings)}\n`;
          }
    
          return {
            content: [
              {
                type: "text",
                text: response,
              },
            ],
          };
        } catch (error: any) {
          logger.error(`Error generating cost recommendations: ${error.message}`);
          throw new GcpMcpError(
            `Failed to generate cost recommendations: ${error.message}`,
            error.code || "UNKNOWN",
            error.status || 500,
          );
        }
      },
    );
  • The core handler function for the tool. Uses mock data to create CostRecommendation instances, applies filters based on input parameters, builds a Markdown response, and calls formatCostRecommendations helper.
    async ({ billingAccountName, projectId, minSavingsAmount, priority }) => {
      try {
        // Use project hierarchy: provided -> state manager -> auth default
        const actualProjectId =
          projectId ||
          stateManager.getCurrentProjectId() ||
          (await getProjectId());
    
        logger.debug(
          `Generating cost recommendations for billing account: ${billingAccountName}, project: ${actualProjectId || "all"}`,
        );
    
        // Mock recommendations for demonstration
        const mockRecommendations: CostRecommendation[] = [
          {
            type: "rightsizing",
            projectId: actualProjectId || "example-project-1",
            serviceId: "compute.googleapis.com",
            resourceName: "instance-group-1",
            description:
              "Compute Engine instances are underutilised and can be right-sized",
            potentialSavings: { amount: 450, currency: "USD", percentage: 30 },
            effort: "medium",
            priority: "high",
            actionRequired:
              "Resize instances from n1-standard-4 to n1-standard-2",
            implementationSteps: [
              "Stop the affected instances during maintenance window",
              "Change machine type from n1-standard-4 to n1-standard-2",
              "Restart instances and monitor performance",
              "Validate application performance meets requirements",
            ],
          },
          {
            type: "idle_resources",
            projectId: actualProjectId || "example-project-2",
            serviceId: "storage.googleapis.com",
            resourceName: "unused-disk-volumes",
            description:
              "Several persistent disks are not attached to any instances",
            potentialSavings: { amount: 125, currency: "USD", percentage: 100 },
            effort: "low",
            priority: "medium",
            actionRequired: "Delete unattached persistent disks",
            implementationSteps: [
              "Verify disks are not needed for backups or future use",
              "Create snapshots if data retention is required",
              "Delete unattached persistent disks",
              "Set up alerts to monitor for future unattached disks",
            ],
          },
        ];
    
        // Filter by minimum savings amount
        const filteredRecommendations = mockRecommendations.filter(
          (rec) => rec.potentialSavings.amount >= minSavingsAmount,
        );
    
        // Filter by priority if specified
        const finalRecommendations =
          priority === "all"
            ? filteredRecommendations
            : filteredRecommendations.filter(
                (rec) => rec.priority === priority,
              );
    
        let response = `# Cost Optimisation Recommendations\n\n`;
        response += `**Billing Account:** ${billingAccountName}\n`;
        response += `**Minimum Savings:** ${formatCurrency(minSavingsAmount)}\n`;
        response += `**Priority Filter:** ${priority}\n\n`;
    
        response += `⚠️ **Note:** This is a demonstration with mock recommendations. `;
        response += `For actual recommendations, integrate with Google Cloud Recommender API.\n\n`;
    
        response += formatCostRecommendations(finalRecommendations);
    
        if (finalRecommendations.length > 0) {
          const totalSavings = finalRecommendations.reduce(
            (sum, rec) => sum + rec.potentialSavings.amount,
            0,
          );
          response += `\n**Total Potential Savings:** ${formatCurrency(totalSavings)}\n`;
        }
    
        return {
          content: [
            {
              type: "text",
              text: response,
            },
          ],
        };
      } catch (error: any) {
        logger.error(`Error generating cost recommendations: ${error.message}`);
        throw new GcpMcpError(
          `Failed to generate cost recommendations: ${error.message}`,
          error.code || "UNKNOWN",
          error.status || 500,
        );
      }
    },
  • Zod input schema defining parameters for the tool: required billingAccountName, optional projectId, minSavingsAmount (default 10), priority (enum default 'all').
    inputSchema: {
      billingAccountName: z
        .string()
        .describe(
          "Billing account name (e.g., 'billingAccounts/123456-789ABC-DEF012')",
        ),
      projectId: z
        .string()
        .optional()
        .describe("Optional project ID to filter recommendations"),
      minSavingsAmount: z
        .number()
        .min(0)
        .default(10)
        .describe("Minimum savings amount to include in recommendations"),
      priority: z
        .enum(["low", "medium", "high", "all"])
        .default("all")
        .describe("Filter recommendations by priority level"),
    },
  • Helper function used by the tool handler to format array of CostRecommendation into a detailed Markdown report, sorted by potential savings, with priority/effort icons and implementation steps.
    export function formatCostRecommendations(
      recommendations: CostRecommendation[],
    ): string {
      if (recommendations.length === 0) {
        return "✅ No cost optimisation recommendations available.";
      }
    
      let result = "## 💡 Cost Optimisation Recommendations\n\n";
    
      // Sort by potential savings (highest first)
      const sortedRecs = recommendations.sort(
        (a, b) => b.potentialSavings.amount - a.potentialSavings.amount,
      );
    
      for (const rec of sortedRecs) {
        const priorityIcon = {
          low: "🟢",
          medium: "🟡",
          high: "🔴",
        }[rec.priority];
    
        const effortIcon = {
          low: "⚡",
          medium: "⚙️",
          high: "🔧",
        }[rec.effort];
    
        result += `### ${priorityIcon} ${rec.type.replace("_", " ").toUpperCase()}\n\n`;
        result += `**Project:** ${rec.projectId}\n`;
        if (rec.serviceId) result += `**Service:** ${rec.serviceId}\n`;
        if (rec.resourceName) result += `**Resource:** ${rec.resourceName}\n`;
        result += `**Description:** ${rec.description}\n`;
        result += `**Potential Savings:** ${formatCurrency(rec.potentialSavings.amount)} (${rec.potentialSavings.percentage.toFixed(1)}%)\n`;
        result += `**Effort Required:** ${effortIcon} ${rec.effort.toUpperCase()}\n`;
        result += `**Priority:** ${priorityIcon} ${rec.priority.toUpperCase()}\n`;
        result += `**Action Required:** ${rec.actionRequired}\n`;
    
        if (rec.implementationSteps.length > 0) {
          result += "\n**Implementation Steps:**\n";
          for (let i = 0; i < rec.implementationSteps.length; i++) {
            result += `${i + 1}. ${rec.implementationSteps[i]}\n`;
          }
        }
    
        result += "\n---\n\n";
      }
    
      return result;
    }
  • TypeScript interface defining the structure of cost recommendations used in the tool's mock data and formatting.
    export interface CostRecommendation {
      type:
        | "rightsizing"
        | "idle_resources"
        | "committed_use"
        | "regional_optimisation";
      projectId: string;
      serviceId?: string;
      resourceName?: string;
      description: string;
      potentialSavings: {
        amount: number;
        currency: string;
        percentage: number;
      };
      effort: "low" | "medium" | "high";
      priority: "low" | "medium" | "high";
      actionRequired: string;
      implementationSteps: string[];
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool generates recommendations but does not describe what the recommendations include (e.g., types, formats), how they are prioritized, whether the operation is read-only or has side effects, or any rate limits or authentication requirements. This is a significant gap for a tool that likely involves complex data processing.

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 without unnecessary words. Every part of the sentence ('Generate cost optimisation recommendations with potential savings for Google Cloud billing') contributes directly to understanding the tool's function.

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 of generating cost recommendations and the lack of annotations and output schema, the description is incomplete. It does not cover behavioral aspects (e.g., what the output looks like, whether it's a list or report), and while the schema covers parameters well, the overall context for effective tool use is insufficient.

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?

The schema description coverage is 100%, so the schema already documents all four parameters thoroughly. The description does not add any additional meaning beyond what the schema provides (e.g., it does not explain how parameters interact or affect recommendations). Baseline 3 is appropriate when the schema does the heavy lifting.

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: 'Generate cost optimisation recommendations with potential savings for Google Cloud billing'. It specifies the verb ('Generate'), resource ('cost optimisation recommendations'), and outcome ('potential savings'), but does not explicitly differentiate it from sibling tools like 'gcp-billing-analyse-costs' or 'gcp-billing-detect-anomalies', which might have overlapping cost-related functions.

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 does not mention prerequisites (e.g., billing account access), exclusions, or comparisons to sibling tools such as 'gcp-billing-analyse-costs', leaving the agent to infer usage context from the tool name 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