Skip to main content
Glama
krzko

Google Cloud MCP Server

by krzko

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[]; }

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