Files
mcp-tool/simple-integration.js
nasir@endelospay.com 811b9bee91 fix add tool
2025-07-19 03:08:10 +05:00

198 lines
6.1 KiB
JavaScript

#!/usr/bin/env node
/**
* Simple Integration: Add new tools to endpoints.js safely
*/
import fs from 'fs';
import path from 'path';
class SimpleIntegration {
constructor() {
this.auditResults = null;
this.newToolsByAuthType = {};
}
/**
* Load audit results
*/
loadAuditResults() {
try {
console.log('📖 Loading audit results...');
const resultsPath = path.join(process.cwd(), 'comprehensive-audit-results.json');
const resultsContent = fs.readFileSync(resultsPath, 'utf8');
this.auditResults = JSON.parse(resultsContent);
console.log(`✅ Loaded audit results: ${this.auditResults.newTools.length} new tools`);
// Group new tools by auth type
this.auditResults.newTools.forEach(tool => {
if (!this.newToolsByAuthType[tool.authType]) {
this.newToolsByAuthType[tool.authType] = [];
}
this.newToolsByAuthType[tool.authType].push(tool);
});
return true;
} catch (error) {
console.error('❌ Error loading audit results:', error.message);
return false;
}
}
/**
* Convert tool to properly formatted endpoint string
*/
toolToEndpointString(tool) {
const paramEntries = Object.entries(tool.parameters);
let paramString = '{}';
if (paramEntries.length > 0) {
const paramLines = paramEntries.map(([name, param]) => {
return ` ${name}: {
type: "${param.type}",
required: ${param.required},
description: "${param.description}",
}`;
});
paramString = `{
${paramLines.join(',\n')}
}`;
}
return ` {
path: "${tool.path}",
method: "${tool.method}",
controller: "${tool.controller}",
category: ${tool.category},
description: "${tool.description}",
parameters: ${paramString},
}`;
}
/**
* Add new endpoints to specific auth type section
*/
addEndpointsToSection(content, sectionName, newTools) {
if (newTools.length === 0) return content;
console.log(`📋 Adding ${newTools.length} endpoints to ${sectionName}`);
// Generate endpoint strings
const endpointStrings = newTools.map(tool => this.toolToEndpointString(tool));
// Find the section
const sectionRegex = new RegExp(`(export const ${sectionName}\\s*=\\s*\\[)([\\s\\S]*?)(\\];)`, 'g');
const match = sectionRegex.exec(content);
if (match) {
const beforeSection = match[1];
const sectionContent = match[2];
const afterSection = match[3];
// Add new endpoints at the end of the section
const newSection = `
// ===== NEW ENDPOINTS FROM API-DOCS.JSON COMPREHENSIVE AUDIT =====
${endpointStrings.join(',\n')}`;
const updatedSection = sectionContent.trimEnd() + ',' + newSection + '\n';
const replacement = beforeSection + updatedSection + afterSection;
return content.replace(match[0], replacement);
} else {
console.log(` ⚠️ Could not find ${sectionName} section`);
return content;
}
}
/**
* Create backup of current endpoints.js
*/
createBackup() {
try {
const endpointsPath = path.join(process.cwd(), 'src/config/endpoints.js');
const backupPath = `src/config/endpoints_backup_simple_${Date.now()}.js`;
fs.copyFileSync(endpointsPath, backupPath);
console.log(`💾 Created backup: ${backupPath}`);
return backupPath;
} catch (error) {
console.error('❌ Error creating backup:', error.message);
return null;
}
}
/**
* Run simple integration
*/
async runIntegration() {
console.log('🚀 SIMPLE INTEGRATION: ADDING NEW TOOLS\n');
// Load audit results
if (!this.loadAuditResults()) return false;
// Create backup
const backupPath = this.createBackup();
if (!backupPath) return false;
try {
// Load current endpoints.js
const endpointsPath = path.join(process.cwd(), 'src/config/endpoints.js');
let content = fs.readFileSync(endpointsPath, 'utf8');
// Add new endpoints for each auth type
Object.entries(this.newToolsByAuthType).forEach(([authType, tools]) => {
const sectionName = `${authType.toUpperCase()}_ENDPOINTS`;
content = this.addEndpointsToSection(content, sectionName, tools);
console.log(` ✅ Added ${tools.length} endpoints to ${sectionName}`);
});
// Write updated content
fs.writeFileSync(endpointsPath, content);
console.log('✅ Updated endpoints.js successfully');
// Generate summary
const totalNewTools = Object.values(this.newToolsByAuthType).reduce((sum, tools) => sum + tools.length, 0);
console.log('\n📊 INTEGRATION SUMMARY:');
console.log(`✅ Added ${totalNewTools} new endpoints`);
console.log(`💾 Backup created: ${backupPath}`);
// Show distribution by auth type
console.log('\n📋 New Tools by Authentication Type:');
Object.entries(this.newToolsByAuthType).forEach(([authType, tools]) => {
console.log(` ${authType.toUpperCase()}: ${tools.length} tools`);
});
return true;
} catch (error) {
console.error('❌ Error during integration:', error.message);
// Restore backup on error
try {
const endpointsPath = path.join(process.cwd(), 'src/config/endpoints.js');
fs.copyFileSync(backupPath, endpointsPath);
console.log('🔄 Restored backup due to error');
} catch (restoreError) {
console.error('❌ Failed to restore backup:', restoreError.message);
}
return false;
}
}
}
// Run Simple Integration
const integration = new SimpleIntegration();
integration.runIntegration().then(success => {
if (success) {
console.log('\n🎉 Simple integration completed successfully!');
console.log('\n📋 Next steps:');
console.log('1. Run test-basic.js to verify functionality');
console.log('2. Update MCP-TOOLS-REFERENCE.md documentation');
console.log('3. Test new endpoints with real API calls');
} else {
console.log('\n❌ Simple integration failed');
}
});