UNPKG

php-universal-mcp-server

Version:

Servidor MCP universal para desenvolvimento PHP e criação de sites em qualquer provedor de hospedagem

210 lines (183 loc) 6.5 kB
#!/usr/bin/env node /** * Ponto de entrada CLI para o PHP Universal MCP Server * Compatível com o mcp-installer */ const { MCPServer, startServer } = require('./index'); let createMCPServer; // Tenta importar o SDK MCP, com fallback para mock se falhar try { ({ createMCPServer } = require('@modelcontextprotocol/sdk')); } catch (error) { console.warn('Aviso: SDK MCP não encontrado, usando mock interno.'); ({ createMCPServer } = require('./sdk-mock')); } const path = require('path'); const fs = require('fs'); // Processa argumentos da linha de comando const parseArgs = () => { const args = process.argv.slice(2); const options = { mode: 'auto', apiKey: process.env.API_KEY || '', fallbackEnabled: true, providerType: 'auto', configPath: null, httpServer: false, port: parseInt(process.env.MCP_PORT) || 7432, host: process.env.MCP_HOST || '127.0.0.1' }; // Processa flags for (let i = 0; i < args.length; i++) { if (args[i] === '--mode' && i + 1 < args.length) { options.mode = args[i + 1]; i++; } else if (args[i] === '--provider' && i + 1 < args.length) { options.providerType = args[i + 1]; i++; } else if (args[i] === '--config' && i + 1 < args.length) { options.configPath = args[i + 1]; i++; } else if (args[i] === '--api-key' && i + 1 < args.length) { options.apiKey = args[i + 1]; i++; } else if (args[i] === '--no-fallback') { options.fallbackEnabled = false; } else if (args[i] === '--http-server') { options.httpServer = true; } else if (args[i] === '--port' && i + 1 < args.length) { options.port = parseInt(args[i + 1], 10); i++; } else if (args[i] === '--host' && i + 1 < args.length) { options.host = args[i + 1]; i++; } else if (args[i] === '--help') { printHelp(); process.exit(0); } } return options; }; // Imprime ajuda const printHelp = () => { console.log(` PHP Universal MCP Server - Servidor MCP universal para desenvolvimento PHP Uso: php-universal-mcp-server [options] Opções: --mode <mode> Modo de operação: 'auto', 'online', ou 'offline' (padrão: auto) --provider <n> Tipo de provider: 'cpanel', 'plesk', 'aws', 'azure', 'gcp', 'mock', 'auto' (padrão: auto) --config <path> Caminho para arquivo de configuração JSON --api-key <key> Chave de API para o provider (sobrescreve a variável de ambiente API_KEY) --no-fallback Desabilita o fallback para modo offline em caso de falha --http-server Inicia o servidor HTTP para integração MCP (padrão: false) --port <port> Porta para o servidor HTTP (padrão: 7432) --host <host> Host para o servidor HTTP (padrão: 127.0.0.1) --help Mostra esta ajuda e sai Exemplos: php-universal-mcp-server --mode offline php-universal-mcp-server --provider azure --api-key sua-chave-api php-universal-mcp-server --config ./config.json php-universal-mcp-server --http-server --port 8080 Env Vars: API_KEY Chave de API genérica MCP_PORT Porta para o servidor HTTP MCP_HOST Host para o servidor HTTP AWS_ACCESS_KEY_ID Chave de acesso AWS AZURE_SUBSCRIPTION_ID ID de assinatura Azure GOOGLE_CLOUD_PROJECT ID do projeto GCP `); }; // Carrega configuração de arquivo se fornecido const loadConfig = (configPath) => { if (!configPath) return {}; try { const configFile = path.resolve(process.cwd(), configPath); const configContent = fs.readFileSync(configFile, 'utf8'); return JSON.parse(configContent); } catch (error) { console.error(`Erro ao carregar arquivo de configuração: ${error.message}`); return {}; } }; // Função principal const main = async () => { try { const options = parseArgs(); const fileConfig = options.configPath ? loadConfig(options.configPath) : {}; // Mescla configurações const config = { ...fileConfig, mode: options.mode, apiKey: options.apiKey, fallbackEnabled: options.fallbackEnabled, providerType: options.providerType }; // Se solicitado servidor HTTP, inicia-o if (options.httpServer) { console.log(`Iniciando servidor HTTP MCP em ${options.host}:${options.port}...`); startServer({ port: options.port, host: options.host, mcpConfig: config }); return; } // Cria instância do servidor MCP const mcpServerInstance = new MCPServer(config); // Inicializa o servidor mcpServerInstance.start(); console.log(`PHP Universal MCP Server iniciado em modo ${config.mode} usando provider ${mcpServerInstance.provider ? mcpServerInstance.provider.getName() : 'desconhecido'}`); // Cria e inicia o wrapper MCP const mcpServer = createMCPServer({ execute: async (input) => { return mcpServerInstance.processCommand({ type: 'execute', payload: JSON.parse(input) }); }, stream: async (input) => { const cmd = mcpServerInstance.processCommand({ type: 'stream', payload: JSON.parse(input) }); return { sessionId: cmd.sessionId, addListener: (type, listener) => { if (!cmd.stream || !cmd.stream.emitter) return; cmd.stream.emitter.on(type, listener); }, removeListener: (type, listener) => { if (!cmd.stream || !cmd.stream.emitter) return; cmd.stream.emitter.removeListener(type, listener); } }; }, cancel: async (sessionId) => { return mcpServerInstance.processCommand({ type: 'cancel', payload: { sessionId } }); } }); // Inicia servidor MCP await mcpServer.listen(); console.log('PHP Universal MCP Server está pronto para receber comandos.'); // Gerencia saída graciosa const cleanup = () => { console.log('Encerrando PHP Universal MCP Server...'); mcpServerInstance.stop(); mcpServer.close(); process.exit(0); }; process.on('SIGINT', cleanup); process.on('SIGTERM', cleanup); } catch (error) { console.error('Erro ao iniciar PHP Universal MCP Server:', error); process.exit(1); } }; // Executa função principal main().catch(err => { console.error('Erro fatal:', err); process.exit(1); });