Performance Optimization

Optimize your MCP Jest test suite for speed, efficiency, and scalability.

Performance Best Practices

Parallel Test Execution

Run tests in parallel to reduce overall execution time:

{
  "name": "Optimized Test Suite",
  "config": {
    "parallel": true,
    "maxWorkers": 4,              // Use 4 CPU cores
    "workerIdleTimeout": 5000,    // Kill idle workers after 5s
    "workerMemoryLimit": "500MB", // Limit worker memory usage
    "isolateWorkers": false       // Reuse workers for speed
  },
  "server": { ... },
  "tests": [ ... ]
}

Choose optimal worker count:

# Auto-detect CPU cores
mcp-jest tests/*.json --parallel

# Specify worker count
mcp-jest tests/*.json --parallel --max-workers 2

# Use percentage of CPU cores
mcp-jest tests/*.json --parallel --max-workers 50%

Server Connection Pooling

{
  "config": {
    "serverPool": {
      "enabled": true,
      "minServers": 2,       // Minimum server instances
      "maxServers": 8,       // Maximum server instances
      "idleTimeout": 30000,  // Kill idle servers after 30s
      "reuseConnections": true
    }
  },
  "server": {
    "command": "node",
    "args": ["server.js"],
    "env": {
      "PORT": "${DYNAMIC_PORT}", // Use dynamic ports
      "NODE_ENV": "test"
    }
  }
}

Test Organization for Speed

Group Related Tests

// Fast tests (run first)
{
  "name": "Unit Tests - Fast",
  "timeout": 5000,
  "tests": [
    {
      "name": "Test capabilities",
      "type": "capabilities"
    },
    {
      "name": "List tools",
      "type": "tools"
    }
  ]
}

// Slow tests (run separately or with higher timeout)
{
  "name": "Integration Tests - Slow", 
  "timeout": 30000,
  "tests": [
    {
      "name": "Complex data processing",
      "type": "tool",
      "tool": "process-large-dataset"
    }
  ]
}

Smart Test Selection

# Run only fast tests during development
mcp-jest tests/unit/*.json --grep "fast|quick|capabilities"

# Run slow tests only on CI
mcp-jest tests/integration/*.json --grep "slow|integration" --timeout 60000

# Skip expensive tests locally
mcp-jest tests/*.json --grep "expensive" --grep-invert

Caching Strategies

Snapshot Caching

{
  "snapshots": {
    "caching": {
      "enabled": true,
      "strategy": "content-hash",  // Cache based on content hash
      "maxAge": 3600000,          // 1 hour cache
      "maxSize": "100MB"          // Maximum cache size
    },
    "compression": {
      "enabled": true,
      "algorithm": "gzip",
      "level": 6
    }
  }
}

Server Startup Caching

{
  "server": {
    "command": "node",
    "args": ["server.js"],
    "caching": {
      "enabled": true,
      "key": "server-v1.2.3",     // Cache key based on version
      "warmup": [                 // Pre-warm server with these calls
        { "type": "capabilities" },
        { "type": "tools" }
      ],
      "healthCheck": {
        "type": "tool",
        "tool": "health"
      }
    }
  }
}

Memory Optimization

Efficient Data Handling

{
  "config": {
    "memory": {
      "maxHeapSize": "512MB",        // Limit Node.js heap size
      "gc": {
        "aggressive": true,          // Force garbage collection
        "interval": 10              // GC every 10 tests
      },
      "streaming": {
        "enabled": true,            // Stream large responses
        "threshold": "1MB"          // Stream responses > 1MB
      }
    }
  },
  "tests": [
    {
      "name": "Large data test",
      "type": "tool",
      "tool": "get-large-dataset",
      "config": {
        "streaming": true,          // Enable streaming for this test
        "memoryLimit": "50MB"       // Limit memory for this test
      }
    }
  ]
}

Response Size Limits

{
  "config": {
    "limits": {
      "maxResponseSize": "10MB",    // Fail if response > 10MB
      "maxSnapshotSize": "1MB",     // Don't snapshot responses > 1MB
      "truncateOutput": true,       // Truncate large outputs
      "truncateSize": "100KB"       // Truncate at 100KB
    }
  },
  "snapshots": {
    "exclude": ["largeData", "binaryContent"],
    "filters": [
      {
        "path": "**.data.content",
        "action": "truncate",
        "maxLength": 1000
      }
    ]
  }
}

Network Optimization

Connection Reuse

{
  "server": {
    "command": "node",
    "args": ["server.js"],
    "connection": {
      "keepAlive": true,          // Reuse connections
      "maxConnections": 10,       // Connection pool size
      "timeout": 5000,           // Connection timeout
      "retryDelay": 100,         // Retry delay
      "maxRetries": 3            // Max connection retries
    }
  }
}

Request Batching

{
  "config": {
    "batching": {
      "enabled": true,
      "maxBatchSize": 10,         // Max requests per batch
      "timeout": 100              // Batch timeout in ms
    }
  },
  "tests": [
    {
      "name": "Batch tool calls",
      "type": "batch",
      "batch": [
        {
          "type": "tool",
          "tool": "get-user",
          "arguments": { "id": "1" }
        },
        {
          "type": "tool", 
          "tool": "get-user",
          "arguments": { "id": "2" }
        }
      ]
    }
  ]
}

Performance Monitoring

Built-in Metrics

{
  "config": {
    "metrics": {
      "enabled": true,
      "outputFile": "performance-metrics.json",
      "thresholds": {
        "testDuration": 5000,      // Warn if test > 5s
        "serverStartup": 10000,    // Warn if startup > 10s
        "memoryUsage": "200MB"     // Warn if memory > 200MB
      },
      "alerts": {
        "slowTests": true,         // Alert on slow tests
        "memoryLeaks": true,       // Alert on memory leaks
        "serverErrors": true       // Alert on server errors
      }
    }
  }
}

Performance Reporting

# Enable performance reporting
mcp-jest tests/*.json --performance --performance-output perf-report.json

# Set performance thresholds
mcp-jest tests/*.json --max-duration 30000 --memory-limit 500MB

# Generate performance comparison
mcp-jest tests/*.json --compare-performance baseline-perf.json

Profiling and Debugging

CPU Profiling

# Profile CPU usage
mcp-jest tests/*.json --profile-cpu --profile-output cpu-profile.cpuprofile

# Profile memory usage
mcp-jest tests/*.json --profile-memory --profile-output memory-profile.heapsnapshot

# Enable detailed timing
mcp-jest tests/*.json --detailed-timing --timing-output timing-report.json

Performance Debugging

// Enable debug logging for performance issues
{
  "config": {
    "debug": {
      "performance": true,        // Log performance metrics
      "memory": true,            // Log memory usage
      "timing": true,            // Log detailed timing
      "server": true             // Log server communication
    },
    "logging": {
      "level": "debug",
      "outputFile": "debug.log",
      "maxSize": "50MB",
      "compress": true
    }
  }
}

Performance Testing

Load Testing

{
  "name": "Load Test Suite",
  "config": {
    "parallel": true,
    "maxWorkers": 10,
    "stress": {
      "enabled": true,
      "concurrent": 50,           // 50 concurrent requests
      "duration": 60000,          // Run for 60 seconds
      "rampUp": 5000             // Ramp up over 5 seconds
    }
  },
  "tests": [
    {
      "name": "High load tool test",
      "type": "tool",
      "tool": "process-request",
      "arguments": { "data": "test" },
      "repeat": 1000,             // Repeat 1000 times
      "expect": {
        "responseTime": { "max": 1000 },
        "memoryUsage": { "max": "100MB" }
      }
    }
  ]
}

Benchmark Tests

{
  "name": "Benchmark Suite",
  "tests": [
    {
      "name": "Baseline performance",
      "type": "benchmark",
      "benchmark": {
        "iterations": 100,
        "warmup": 10,
        "timeout": 60000
      },
      "setup": {
        "type": "tool",
        "tool": "setup-benchmark-data"
      },
      "test": {
        "type": "tool", 
        "tool": "benchmark-operation",
        "arguments": { "size": 1000 }
      },
      "teardown": {
        "type": "tool",
        "tool": "cleanup-benchmark-data"
      },
      "expect": {
        "averageTime": { "max": 500 },    // Average < 500ms
        "p95Time": { "max": 1000 },       // 95th percentile < 1s
        "p99Time": { "max": 2000 }        // 99th percentile < 2s
      }
    }
  ]
}

Optimization Checklist

✅ Performance Optimizations

  • • Enable parallel execution for independent tests
  • • Use server connection pooling
  • • Implement smart caching strategies
  • • Limit response sizes and memory usage
  • • Group tests by execution time
  • • Use streaming for large data
  • • Monitor and profile performance regularly

❌ Performance Anti-patterns

  • • Running all tests sequentially
  • • Not setting appropriate timeouts
  • • Ignoring memory leaks
  • • Creating new server instances for each test
  • • Not cleaning up resources
  • • Testing with unrealistic data sizes

⚡ Performance Mastery

With these optimization techniques, your MCP Jest test suite will run faster and scale better as your project grows.