UNPKG

universal-documents-converter

Version:

Universal MCP Server for Multi-Rendering PDF Quality Assurance System with AI-powered optimization

296 lines (246 loc) โ€ข 9.31 kB
#!/usr/bin/env node /** * Universal Documents Converter MCP Server Setup Script * Configures the multi-rendering PDF quality assurance system */ import { promises as fs } from 'fs'; import { spawn } from 'child_process'; import path from 'path'; import { fileURLToPath } from 'url'; import readline from 'readline'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); class UniversalDocumentsSetup { constructor() { this.rl = readline.createInterface({ input: process.stdin, output: process.stdout }); } async setup() { console.log('๐Ÿš€ Universal Documents Converter MCP Server Setup'); console.log('=' * 60); try { // Step 1: Create directory structure await this.createDirectoryStructure(); // Step 2: Install Python dependencies await this.installPythonDependencies(); // Step 3: Install Playwright browsers await this.installPlaywrightBrowsers(); // Step 4: Configure OpenRouter API keys await this.configureOpenRouterKeys(); // Step 5: Create MCP server configuration await this.createMcpConfiguration(); // Step 6: Run validation tests await this.runValidationTests(); // Step 7: Display completion message await this.displayCompletionMessage(); } catch (error) { console.error('โŒ Setup failed:', error.message); process.exit(1); } finally { this.rl.close(); } } async createDirectoryStructure() { console.log('\n๐Ÿ“ Creating directory structure...'); const directories = [ 'src', 'config', 'tools', 'quality_reports', 'pdf_variants', 'pdf_analysis_images', 'backups' ]; for (const dir of directories) { const dirPath = path.join(__dirname, dir); try { await fs.mkdir(dirPath, { recursive: true }); console.log(` โœ… Created: ${dir}/`); } catch (error) { if (error.code !== 'EEXIST') { throw error; } console.log(` โœ… Exists: ${dir}/`); } } } async installPythonDependencies() { console.log('\n๐Ÿ Installing Python dependencies...'); try { await this.runCommand('python', ['-m', 'pip', 'install', '-r', 'requirements.txt']); console.log(' โœ… Python dependencies installed successfully'); } catch (error) { console.log(' โš ๏ธ Python dependency installation failed, trying alternative...'); try { await this.runCommand('python3', ['-m', 'pip', 'install', '-r', 'requirements.txt']); console.log(' โœ… Python dependencies installed successfully (python3)'); } catch (error2) { throw new Error('Failed to install Python dependencies. Please install manually.'); } } } async installPlaywrightBrowsers() { console.log('\n๐ŸŒ Installing Playwright browsers...'); try { await this.runCommand('python', ['-m', 'playwright', 'install']); console.log(' โœ… Playwright browsers installed successfully'); } catch (error) { console.log(' โš ๏ธ Playwright browser installation failed, trying alternative...'); try { await this.runCommand('python3', ['-m', 'playwright', 'install']); console.log(' โœ… Playwright browsers installed successfully (python3)'); } catch (error2) { console.log(' โš ๏ธ Playwright browser installation failed. You may need to install manually.'); } } } async configureOpenRouterKeys() { console.log('\n๐Ÿ”‘ Configuring OpenRouter API keys...'); const configPath = path.join(__dirname, 'config', 'openrouter_keys.json'); try { // Check if config already exists await fs.access(configPath); console.log(' โœ… OpenRouter configuration already exists'); const updateConfig = await this.askQuestion('Do you want to update the OpenRouter configuration? (y/N): '); if (updateConfig.toLowerCase() !== 'y') { return; } } catch (error) { // Config doesn't exist, create it } console.log('\n ๐Ÿ“ Please provide your OpenRouter API keys:'); console.log(' You can get API keys from: https://openrouter.ai/keys'); console.log(' Enter one key per line, press Enter twice when done:'); const apiKeys = []; let keyInput = ''; let emptyLines = 0; while (emptyLines < 2) { keyInput = await this.askQuestion(` API Key ${apiKeys.length + 1}: `); if (keyInput.trim() === '') { emptyLines++; } else { apiKeys.push(keyInput.trim()); emptyLines = 0; } } if (apiKeys.length === 0) { console.log(' โš ๏ธ No API keys provided. Creating template configuration...'); const templateConfig = { api_keys: [ "sk-or-v1-your-api-key-here" ], model: "deepseek/deepseek-r1-0528:free", updated_at: new Date().toISOString(), note: "Replace with your actual OpenRouter API keys" }; await fs.writeFile(configPath, JSON.stringify(templateConfig, null, 2)); console.log(' โœ… Template configuration created. Please update with your API keys.'); } else { const config = { api_keys: apiKeys, model: "deepseek/deepseek-r1-0528:free", updated_at: new Date().toISOString() }; await fs.writeFile(configPath, JSON.stringify(config, null, 2)); console.log(` โœ… Configuration saved with ${apiKeys.length} API keys`); } } async createMcpConfiguration() { console.log('\nโš™๏ธ Creating MCP server configuration...'); const configPath = path.join(__dirname, 'config', 'mcp_server_config.json'); const config = { workspace_path: "auto-detect", enable_learning: true, default_document_type: "general", quality_threshold: 85.0, max_variants: 7, ai_timeout: 45, backup_enabled: true, created_at: new Date().toISOString() }; await fs.writeFile(configPath, JSON.stringify(config, null, 2)); console.log(' โœ… MCP server configuration created'); } async runValidationTests() { console.log('\n๐Ÿงช Running validation tests...'); try { const testScript = path.join(__dirname, 'src', 'test_multi_rendering_system.py'); // Check if test script exists try { await fs.access(testScript); } catch (error) { console.log(' โš ๏ธ Test script not found. Skipping validation tests.'); return; } await this.runCommand('python', [testScript, '--test-type', 'quick']); console.log(' โœ… Validation tests passed'); } catch (error) { console.log(' โš ๏ธ Validation tests failed. System may still work, but please check manually.'); } } async displayCompletionMessage() { console.log('\n๐ŸŽ‰ Setup completed successfully!'); console.log('=' * 60); console.log('\n๐Ÿ“‹ Next Steps:'); console.log('1. Add this server to your VS Code Insiders MCP configuration:'); console.log(' {'); console.log(' "mcpServers": {'); console.log(' "universal-documents-converter": {'); console.log(` "command": "node",`); console.log(` "args": ["${path.join(__dirname, 'server.js')}"],`); console.log(' "env": {}'); console.log(' }'); console.log(' }'); console.log(' }'); console.log('\n2. Restart VS Code Insiders'); console.log('3. Test the system with: "convert my document.md to PDF"'); console.log('\n๐Ÿ”ง Available Commands:'); console.log(' npm start - Start the MCP server'); console.log(' npm test - Run comprehensive tests'); console.log(' npm run demo - Run demonstration'); console.log(' npm run validate - Quick validation'); console.log('\n๐Ÿ“š Documentation: README.md'); console.log('๐Ÿ†˜ Support: https://github.com/universal-documents-converter/mcp-server'); } async askQuestion(question) { return new Promise((resolve) => { this.rl.question(question, (answer) => { resolve(answer); }); }); } async runCommand(command, args = [], options = {}) { return new Promise((resolve, reject) => { const process = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], ...options }); let stdout = ''; let stderr = ''; process.stdout.on('data', (data) => { stdout += data.toString(); }); process.stderr.on('data', (data) => { stderr += data.toString(); }); process.on('close', (code) => { if (code === 0) { resolve({ stdout, stderr }); } else { reject(new Error(`Command failed with code ${code}: ${stderr}`)); } }); process.on('error', (error) => { reject(new Error(`Failed to start command: ${error.message}`)); }); }); } } // Run setup if called directly if (import.meta.url === `file://${process.argv[1]}`) { const setup = new UniversalDocumentsSetup(); setup.setup().catch(console.error); } export default UniversalDocumentsSetup;