File size: 10,163 Bytes
da2e594
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env ts-node
/**
 * Test script for validating the get_node_essentials tool
 * 
 * This script:
 * 1. Compares get_node_essentials vs get_node_info response sizes
 * 2. Validates that essential properties are correctly extracted
 * 3. Checks that examples are properly generated
 * 4. Tests the property search functionality
 */

import { N8NDocumentationMCPServer } from '../src/mcp/server';
import { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

// Color codes for terminal output
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m'
};

function log(message: string, color: string = colors.reset) {
  console.log(`${color}${message}${colors.reset}`);
}

function logSection(title: string) {
  console.log('\n' + '='.repeat(60));
  log(title, colors.bright + colors.cyan);
  console.log('='.repeat(60));
}

function formatBytes(bytes: number): string {
  if (bytes < 1024) return bytes + ' B';
  const kb = bytes / 1024;
  if (kb < 1024) return kb.toFixed(1) + ' KB';
  const mb = kb / 1024;
  return mb.toFixed(2) + ' MB';
}

async function testNodeEssentials(server: N8NDocumentationMCPServer, nodeType: string) {
  logSection(`Testing ${nodeType}`);
  
  try {
    // Get full node info
    const startFull = Date.now();
    const fullInfo = await server.executeTool('get_node_info', { nodeType });
    const fullTime = Date.now() - startFull;
    const fullSize = JSON.stringify(fullInfo).length;
    
    // Get essential info
    const startEssential = Date.now();
    const essentialInfo = await server.executeTool('get_node_essentials', { nodeType });
    const essentialTime = Date.now() - startEssential;
    const essentialSize = JSON.stringify(essentialInfo).length;
    
    // Calculate metrics
    const sizeReduction = ((fullSize - essentialSize) / fullSize * 100).toFixed(1);
    const speedImprovement = ((fullTime - essentialTime) / fullTime * 100).toFixed(1);
    
    // Display results
    log(`\nπŸ“Š Size Comparison:`, colors.bright);
    log(`   Full response:      ${formatBytes(fullSize)}`, colors.yellow);
    log(`   Essential response: ${formatBytes(essentialSize)}`, colors.green);
    log(`   Size reduction:     ${sizeReduction}% ✨`, colors.bright + colors.green);
    
    log(`\n⚑ Performance:`, colors.bright);
    log(`   Full response time:      ${fullTime}ms`);
    log(`   Essential response time: ${essentialTime}ms`);
    log(`   Speed improvement:       ${speedImprovement}%`, colors.green);
    
    log(`\nπŸ“‹ Property Count:`, colors.bright);
    const fullPropCount = fullInfo.properties?.length || 0;
    const essentialPropCount = (essentialInfo.requiredProperties?.length || 0) + 
                               (essentialInfo.commonProperties?.length || 0);
    log(`   Full properties:      ${fullPropCount}`);
    log(`   Essential properties: ${essentialPropCount}`);
    log(`   Properties removed:   ${fullPropCount - essentialPropCount} (${((fullPropCount - essentialPropCount) / fullPropCount * 100).toFixed(1)}%)`, colors.green);
    
    log(`\nπŸ”§ Essential Properties:`, colors.bright);
    log(`   Required: ${essentialInfo.requiredProperties?.map((p: any) => p.name).join(', ') || 'None'}`);
    log(`   Common:   ${essentialInfo.commonProperties?.map((p: any) => p.name).join(', ') || 'None'}`);
    
    log(`\nπŸ“š Examples:`, colors.bright);
    const examples = Object.keys(essentialInfo.examples || {});
    log(`   Available examples: ${examples.join(', ') || 'None'}`);
    
    if (essentialInfo.examples?.minimal) {
      log(`   Minimal example properties: ${Object.keys(essentialInfo.examples.minimal).join(', ')}`);
    }
    
    log(`\nπŸ“Š Metadata:`, colors.bright);
    log(`   Total properties available: ${essentialInfo.metadata?.totalProperties || 0}`);
    log(`   Is AI Tool: ${essentialInfo.metadata?.isAITool ? 'Yes' : 'No'}`);
    log(`   Is Trigger: ${essentialInfo.metadata?.isTrigger ? 'Yes' : 'No'}`);
    log(`   Has Credentials: ${essentialInfo.metadata?.hasCredentials ? 'Yes' : 'No'}`);
    
    // Test property search
    const searchTerms = ['auth', 'header', 'body', 'json'];
    log(`\nπŸ” Property Search Test:`, colors.bright);
    
    for (const term of searchTerms) {
      try {
        const searchResult = await server.executeTool('search_node_properties', {
          nodeType,
          query: term,
          maxResults: 5
        });
        log(`   "${term}": Found ${searchResult.totalMatches} properties`);
      } catch (error) {
        log(`   "${term}": Search failed`, colors.red);
      }
    }
    
    return {
      nodeType,
      fullSize,
      essentialSize,
      sizeReduction: parseFloat(sizeReduction),
      fullPropCount,
      essentialPropCount,
      success: true
    };
    
  } catch (error) {
    log(`❌ Error testing ${nodeType}: ${error}`, colors.red);
    return {
      nodeType,
      fullSize: 0,
      essentialSize: 0,
      sizeReduction: 0,
      fullPropCount: 0,
      essentialPropCount: 0,
      success: false,
      error: error instanceof Error ? error.message : String(error)
    };
  }
}

async function main() {
  logSection('n8n MCP Essentials Tool Test Suite');
  
  try {
    // Initialize server
    log('\nπŸš€ Initializing MCP server...', colors.cyan);
    const server = new N8NDocumentationMCPServer();
    
    // Wait for initialization
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // Test nodes
    const testNodes = [
      'nodes-base.httpRequest',
      'nodes-base.webhook',
      'nodes-base.code',
      'nodes-base.set',
      'nodes-base.if',
      'nodes-base.postgres',
      'nodes-base.openAi',
      'nodes-base.googleSheets',
      'nodes-base.slack',
      'nodes-base.merge'
    ];
    
    const results = [];
    
    for (const nodeType of testNodes) {
      const result = await testNodeEssentials(server, nodeType);
      results.push(result);
    }
    
    // Summary
    logSection('Test Summary');
    
    const successful = results.filter(r => r.success);
    const totalFullSize = successful.reduce((sum, r) => sum + r.fullSize, 0);
    const totalEssentialSize = successful.reduce((sum, r) => sum + r.essentialSize, 0);
    const avgReduction = successful.reduce((sum, r) => sum + r.sizeReduction, 0) / successful.length;
    
    log(`\nβœ… Successful tests: ${successful.length}/${results.length}`, colors.green);
    
    if (successful.length > 0) {
      log(`\nπŸ“Š Overall Statistics:`, colors.bright);
      log(`   Total full size:      ${formatBytes(totalFullSize)}`);
      log(`   Total essential size: ${formatBytes(totalEssentialSize)}`);
      log(`   Average reduction:    ${avgReduction.toFixed(1)}%`, colors.bright + colors.green);
      
      log(`\nπŸ† Best Performers:`, colors.bright);
      const sorted = successful.sort((a, b) => b.sizeReduction - a.sizeReduction);
      sorted.slice(0, 3).forEach((r, i) => {
        log(`   ${i + 1}. ${r.nodeType}: ${r.sizeReduction}% reduction (${formatBytes(r.fullSize)} β†’ ${formatBytes(r.essentialSize)})`);
      });
    }
    
    const failed = results.filter(r => !r.success);
    if (failed.length > 0) {
      log(`\n❌ Failed tests:`, colors.red);
      failed.forEach(r => {
        log(`   - ${r.nodeType}: ${r.error}`, colors.red);
      });
    }
    
    // Save detailed results
    const reportPath = join(process.cwd(), 'test-results-essentials.json');
    writeFileSync(reportPath, JSON.stringify({
      timestamp: new Date().toISOString(),
      summary: {
        totalTests: results.length,
        successful: successful.length,
        failed: failed.length,
        averageReduction: avgReduction,
        totalFullSize,
        totalEssentialSize
      },
      results
    }, null, 2));
    
    log(`\nπŸ“„ Detailed results saved to: ${reportPath}`, colors.cyan);
    
    // Recommendations
    logSection('Recommendations');
    
    if (avgReduction > 90) {
      log('✨ Excellent! The essentials tool is achieving >90% size reduction.', colors.green);
    } else if (avgReduction > 80) {
      log('πŸ‘ Good! The essentials tool is achieving 80-90% size reduction.', colors.yellow);
      log('   Consider reviewing nodes with lower reduction rates.');
    } else {
      log('⚠️  The average size reduction is below 80%.', colors.yellow);
      log('   Review the essential property lists for optimization.');
    }
    
    // Test specific functionality
    logSection('Testing Advanced Features');
    
    // Test error handling
    log('\nπŸ§ͺ Testing error handling...', colors.cyan);
    try {
      await server.executeTool('get_node_essentials', { nodeType: 'non-existent-node' });
      log('   ❌ Error handling failed - should have thrown error', colors.red);
    } catch (error) {
      log('   βœ… Error handling works correctly', colors.green);
    }
    
    // Test alternative node type formats
    log('\nπŸ§ͺ Testing alternative node type formats...', colors.cyan);
    const alternativeFormats = [
      { input: 'httpRequest', expected: 'nodes-base.httpRequest' },
      { input: 'nodes-base.httpRequest', expected: 'nodes-base.httpRequest' },
      { input: 'HTTPREQUEST', expected: 'nodes-base.httpRequest' }
    ];
    
    for (const format of alternativeFormats) {
      try {
        const result = await server.executeTool('get_node_essentials', { nodeType: format.input });
        if (result.nodeType === format.expected) {
          log(`   βœ… "${format.input}" β†’ "${format.expected}"`, colors.green);
        } else {
          log(`   ❌ "${format.input}" β†’ "${result.nodeType}" (expected "${format.expected}")`, colors.red);
        }
      } catch (error) {
        log(`   ❌ "${format.input}" β†’ Error: ${error}`, colors.red);
      }
    }
    
    log('\n✨ Test suite completed!', colors.bright + colors.green);
    
  } catch (error) {
    log(`\n❌ Fatal error: ${error}`, colors.red);
    process.exit(1);
  }
}

// Run the test
main().catch(error => {
  console.error('Unhandled error:', error);
  process.exit(1);
});