Skip to main content
Glama
jghidalgo

Lambda Performance MCP Server

by jghidalgo

analyze_memory_utilization

Analyze AWS Lambda function memory usage to identify optimization opportunities and provide right-sizing recommendations for improved performance.

Instructions

Analyze memory utilization and provide right-sizing recommendations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
functionNameYesName of the Lambda function
timeRangeNoTime range for memory analysis (default: 24h)

Implementation Reference

  • Core handler implementing the memory utilization analysis, fetching config, logs, calculating stats, and generating recommendations.
    async analyzeMemoryUtilization(functionName, timeRange) {
      const timeRangeMs = this.parseTimeRange(timeRange);
      const endTime = new Date();
      const startTime = new Date(endTime.getTime() - timeRangeMs);
    
      // Get function configuration
      const config = await this.getFunctionConfig(functionName);
      const allocatedMemory = config.MemorySize;
    
      // Get memory usage from logs
      const memoryUsage = await this.getMemoryUsageFromLogs(functionName, startTime, endTime);
      
      const avgUsed = memoryUsage.reduce((sum, usage) => sum + usage, 0) / memoryUsage.length || 0;
      const peakUsed = Math.max(...memoryUsage, 0);
      const minUsed = Math.min(...memoryUsage, allocatedMemory);
      const utilizationPercent = Math.round((avgUsed / allocatedMemory) * 100);
    
      // Generate recommendation
      const recommendation = this.generateMemoryRecommendation(
        allocatedMemory, 
        avgUsed, 
        peakUsed, 
        utilizationPercent
      );
    
      return {
        allocated: allocatedMemory,
        avgUsed: Math.round(avgUsed),
        peakUsed: Math.round(peakUsed),
        minUsed: Math.round(minUsed),
        utilizationPercent,
        recommended: recommendation.memory,
        reasoning: recommendation.reasoning,
        performanceImpact: recommendation.performanceImpact,
        costImpact: recommendation.costImpact,
        patterns: this.analyzeMemoryPatterns(memoryUsage)
      };
    }
  • MCP server handler wrapper that invokes the analyzer and formats the response for the MCP protocol.
    async analyzeMemoryUtilization(args) {
      const { functionName, timeRange = '24h' } = args;
      
      const memoryAnalysis = await this.lambdaAnalyzer.analyzeMemoryUtilization(
        functionName, 
        timeRange
      );
    
      return {
        content: [
          {
            type: 'text',
            text: `# Memory Utilization Analysis: ${functionName}\n\n` +
                  `## Current Configuration\n` +
                  `- **Allocated Memory**: ${memoryAnalysis.allocated}MB\n` +
                  `- **Average Used**: ${memoryAnalysis.avgUsed}MB (${memoryAnalysis.utilizationPercent}%)\n` +
                  `- **Peak Usage**: ${memoryAnalysis.peakUsed}MB\n` +
                  `- **Minimum Usage**: ${memoryAnalysis.minUsed}MB\n\n` +
                  `## Right-sizing Recommendation\n` +
                  `- **Recommended Memory**: ${memoryAnalysis.recommended}MB\n` +
                  `- **Reasoning**: ${memoryAnalysis.reasoning}\n` +
                  `- **Expected Performance Impact**: ${memoryAnalysis.performanceImpact}\n` +
                  `- **Cost Impact**: ${memoryAnalysis.costImpact}\n\n` +
                  `## Memory Usage Patterns\n` +
                  `${memoryAnalysis.patterns.map(pattern => `- ${pattern}`).join('\n')}`
          }
        ]
      };
    }
  • index.js:148-164 (registration)
    Tool registration in the MCP server's listTools response, including name, description, and input schema.
    name: 'analyze_memory_utilization',
    description: 'Analyze memory utilization and provide right-sizing recommendations',
    inputSchema: {
      type: 'object',
      properties: {
        functionName: {
          type: 'string',
          description: 'Name of the Lambda function'
        },
        timeRange: {
          type: 'string',
          enum: ['1h', '6h', '24h', '7d'],
          description: 'Time range for memory analysis (default: 24h)'
        }
      },
      required: ['functionName']
    }
  • Helper method that generates memory right-sizing recommendations based on utilization stats.
    generateMemoryRecommendation(allocated, avgUsed, peakUsed, utilizationPercent) {
      let recommendedMemory = allocated;
      let reasoning = '';
      let performanceImpact = 'No change expected';
      let costImpact = 'No change';
    
      if (utilizationPercent < 50) {
        // Over-provisioned
        recommendedMemory = Math.max(128, Math.ceil(peakUsed * 1.2 / 64) * 64);
        reasoning = 'Memory is over-provisioned. Reducing memory will lower costs.';
        costImpact = `Reduce costs by ~${Math.round((1 - recommendedMemory/allocated) * 100)}%`;
        performanceImpact = 'Minimal performance impact expected';
      } else if (utilizationPercent > 85) {
        // Under-provisioned
        recommendedMemory = Math.ceil(peakUsed * 1.3 / 64) * 64;
        reasoning = 'Memory utilization is high. Increasing memory may improve performance.';
        costImpact = `Increase costs by ~${Math.round((recommendedMemory/allocated - 1) * 100)}%`;
        performanceImpact = 'Improved performance and reduced duration expected';
      } else {
        reasoning = 'Memory allocation appears optimal for current usage patterns.';
      }
    
      return {
        memory: recommendedMemory,
        reasoning,
        performanceImpact,
        costImpact
      };
  • Helper to fetch memory usage data from CloudWatch logs (placeholder implementation).
    async getMemoryUsageFromLogs(functionName, startTime, endTime) {
      // Placeholder implementation - would parse CloudWatch logs for memory usage
      return Array.from({ length: 100 }, () => Math.floor(Math.random() * 200) + 100);
    }
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 analyzes and provides recommendations, implying a read-only, non-destructive operation, but doesn't detail aspects like rate limits, authentication needs, error handling, or what the recommendations entail. For a tool with zero annotation coverage, this is insufficient.

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 directly states the tool's purpose without unnecessary words. It is front-loaded and appropriately sized, making it easy for an agent to parse quickly.

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 tool's complexity (analyzing memory utilization with recommendations), lack of annotations, and no output schema, the description is incomplete. It doesn't explain the format or nature of the recommendations, potential side effects, or how it integrates with sibling tools. This leaves significant gaps for an agent to understand the tool's full context.

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 input schema has 100% description coverage, fully documenting both parameters. The description adds no additional parameter semantics beyond what the schema provides, such as explaining how 'functionName' relates to memory analysis or the implications of 'timeRange' choices. With high schema coverage, the baseline score of 3 is appropriate.

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: 'Analyze memory utilization and provide right-sizing recommendations.' It specifies the action ('analyze') and resource ('memory utilization') with an additional outcome ('right-sizing recommendations'). However, it doesn't explicitly differentiate from siblings like 'analyze_lambda_performance' or 'get_optimization_recommendations,' which might overlap in scope.

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 when to choose it over siblings such as 'analyze_lambda_performance' or 'get_optimization_recommendations,' nor does it specify prerequisites or exclusions. This leaves the agent without context for 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/jghidalgo/lambda-performance-mcp-nodejs'

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