Skip to main content
Glama
code-alchemist01

MCP Cloud Services Server

analyze_costs

Analyze cloud costs across AWS, Azure, or GCP to identify spending patterns and optimize resource usage based on date ranges and granularity.

Instructions

Analyze cloud costs for AWS, Azure, or GCP

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
providerYesCloud provider
startDateYesStart date (YYYY-MM-DD)
endDateYesEnd date (YYYY-MM-DD)
granularityNoCost granularitymonthly

Implementation Reference

  • Primary handler for cost analysis tools, including the switch case for 'analyze_costs' that delegates to provider-specific functions.
    export async function handleCostAnalysisTool(name: string, args: unknown): Promise<unknown> {
      const params = args as Record<string, unknown>;
      const provider = params.provider as CloudProvider;
    
      switch (name) {
        case 'analyze_costs': {
          const startDate = params.startDate as string;
          const endDate = params.endDate as string;
          const granularity = (params.granularity as string) || 'monthly';
    
          if (provider === 'aws') {
            return await analyzeAWSCosts(startDate, endDate, granularity);
          } else if (provider === 'azure') {
            // Azure cost analysis would go here
            return { message: 'Azure cost analysis not yet fully implemented' };
          } else if (provider === 'gcp') {
            // GCP cost analysis would go here
            return { message: 'GCP cost analysis not yet fully implemented' };
          }
          throw new Error(`Unsupported provider: ${provider}`);
        }
    
        case 'get_cost_by_service': {
          const startDate = params.startDate as string;
          const endDate = params.endDate as string;
    
          if (provider === 'aws') {
            return await getAWSCostByService(startDate, endDate);
          }
          return { message: `Cost by service not yet implemented for ${provider}` };
        }
    
        case 'estimate_monthly_cost': {
          // Simplified estimation
          return {
            provider,
            estimatedMonthlyCost: 'N/A - Requires actual usage data',
            message: 'Monthly cost estimation requires detailed usage metrics',
          };
        }
    
        default:
          throw new Error(`Unknown cost analysis tool: ${name}`);
      }
    }
  • Core helper function implementing AWS cost analysis using AWS Cost Explorer client, processing costs by service and time period.
    async function analyzeAWSCosts(startDate: string, endDate: string, granularity: string): Promise<string> {
      try {
        const credentials = await credentialManager.getCredentials('aws');
        if (!credentials) {
          throw new Error('AWS credentials not found');
        }
    
        const client = new CostExplorerClient({
          region: 'us-east-1', // Cost Explorer is global
          credentials: credentials.accessKeyId && credentials.secretAccessKey
            ? {
                accessKeyId: credentials.accessKeyId,
                secretAccessKey: credentials.secretAccessKey,
              }
            : undefined,
        });
    
        const command = new GetCostAndUsageCommand({
          TimePeriod: {
            Start: startDate,
            End: endDate,
          },
          Granularity: granularity === 'daily' ? 'DAILY' : 'MONTHLY',
          Metrics: ['BlendedCost', 'UnblendedCost'],
          GroupBy: [{ Type: 'DIMENSION', Key: 'SERVICE' }],
        });
    
        const response = await client.send(command);
    
        const costAnalysis: CostAnalysis = {
          provider: 'aws',
          period: {
            start: new Date(startDate),
            end: new Date(endDate),
          },
          totalCost: 0,
          currency: 'USD',
          breakdown: [],
          trends: [],
        };
    
        if (response.ResultsByTime && response.ResultsByTime.length > 0) {
          for (const result of response.ResultsByTime) {
            const timePeriod = result.TimePeriod;
            if (timePeriod && result.Groups) {
              for (const group of result.Groups) {
                const cost = parseFloat(group.Metrics?.BlendedCost?.Amount || '0');
                costAnalysis.totalCost += cost;
    
                const serviceName = group.Keys?.[0] || 'Unknown';
                costAnalysis.breakdown.push({
                  service: serviceName,
                  cost,
                  percentage: 0, // Will calculate after
                });
    
                if (timePeriod.Start) {
                  costAnalysis.trends?.push({
                    date: new Date(timePeriod.Start),
                    cost,
                    service: serviceName,
                  });
                }
              }
            }
          }
    
          // Calculate percentages
          if (costAnalysis.totalCost > 0) {
            for (const item of costAnalysis.breakdown) {
              item.percentage = (item.cost / costAnalysis.totalCost) * 100;
            }
          }
        }
    
        return Formatters.formatCostAnalysis(costAnalysis);
      } catch (error) {
        throw new Error(`Failed to analyze AWS costs: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • Tool definition including name, description, and input schema for 'analyze_costs'.
    {
      name: 'analyze_costs',
      description: 'Analyze cloud costs for AWS, Azure, or GCP',
      inputSchema: {
        type: 'object',
        properties: {
          provider: {
            type: 'string',
            enum: ['aws', 'azure', 'gcp'],
            description: 'Cloud provider',
          },
          startDate: {
            type: 'string',
            description: 'Start date (YYYY-MM-DD)',
          },
          endDate: {
            type: 'string',
            description: 'End date (YYYY-MM-DD)',
          },
          granularity: {
            type: 'string',
            enum: ['daily', 'monthly'],
            description: 'Cost granularity',
            default: 'monthly',
          },
        },
        required: ['provider', 'startDate', 'endDate'],
      },
    },
  • src/server.ts:19-27 (registration)
    Registers costAnalysisTools (including analyze_costs) into the global allTools array used for listing available MCP tools.
    const allTools = [
      ...awsTools,
      ...azureTools,
      ...gcpTools,
      ...resourceManagementTools,
      ...costAnalysisTools,
      ...monitoringTools,
      ...securityTools,
    ];
  • src/server.ts:72-73 (registration)
    Dispatch logic in MCP server that routes calls to 'analyze_costs' (and other cost tools) to the appropriate handler.
    } else if (costAnalysisTools.some((t) => t.name === name)) {
      result = await handleCostAnalysisTool(name, args || {});
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It only states what the tool does (analyze costs) without mentioning permissions needed, rate limits, data freshness, output format, or whether it performs calculations versus fetching raw data. This is inadequate for a tool with potential complexity.

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 extremely concise - a single sentence with no wasted words. It's front-loaded with the core purpose and efficiently lists the three supported providers. Every word earns its place in this minimal but complete statement of 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?

For a cost analysis tool with no annotations and no output schema, the description is insufficient. It doesn't explain what 'analyze' means operationally, what kind of analysis is performed, what format results are returned in, or any behavioral characteristics. The agent lacks critical context for proper tool selection and invocation.

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%, so the schema fully documents all parameters. The description adds no additional parameter semantics beyond implying provider selection and cost analysis, which is already covered by the schema. Baseline 3 is appropriate when 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 as analyzing cloud costs for three major providers (AWS, Azure, GCP), which is specific and actionable. However, it doesn't explicitly differentiate from sibling tools like 'get_cost_by_service' or 'estimate_monthly_cost', leaving some ambiguity about scope and methodology.

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 guidance is provided on when to use this tool versus alternatives like 'get_cost_by_service' or 'estimate_monthly_cost'. The description mentions providers but doesn't specify prerequisites, appropriate contexts, or exclusions, leaving the agent to infer usage scenarios.

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/code-alchemist01/Cloud-mcp_server'

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