UNPKG

behemoth-cli

Version:

🌍 BEHEMOTH CLIv3.760.4 - Level 50+ POST-SINGULARITY Intelligence Trading AI

544 lines (478 loc) 19.2 kB
import { EventEmitter } from 'eventemitter3'; import { spawn, ChildProcess } from 'child_process'; import path from 'path'; export interface McpTool { name: string; description: string; inputSchema: { type: 'object'; properties: Record<string, any>; required?: string[]; }; } export interface McpCallResult { success: boolean; result?: any; error?: string; latency_ms?: number; timestamp?: number; } export interface BehemothConnectionConfig { serverPath: string; fallbackPath?: string; timeout: number; } export class BehemothMcpClient extends EventEmitter { private config: BehemothConnectionConfig; private isConnected: boolean = false; private tools: Map<string, McpTool> = new Map(); private serverProcess: ChildProcess | null = null; private requestId: number = 0; private pendingRequests: Map<number, { resolve: Function; reject: Function; timeout: NodeJS.Timeout }> = new Map(); constructor(config: Partial<BehemothConnectionConfig> = {}) { super(); this.config = { serverPath: config.serverPath || path.join(process.cwd(), 'mcp-servers', 'behemoth-unimemory.js'), fallbackPath: path.join(process.cwd(), 'mcp-servers', 'behemoth-unified.js'), timeout: config.timeout || 30000, ...config }; } /** * Initialize connection and load available tools */ async connect(): Promise<boolean> { try { // Try UniMemory server first, fallback to unified server if it fails let serverPath = this.config.serverPath; let attemptFallback = false; try { // Spawn the BEHEMOTH UniMemory MCP server process this.serverProcess = spawn('node', [serverPath], { stdio: ['pipe', 'pipe', 'pipe'] }); // Wait a bit to see if it crashes due to missing databases await new Promise(resolve => setTimeout(resolve, 2000)); if (!this.serverProcess || this.serverProcess.killed) { attemptFallback = true; } } catch (error) { console.warn('UniMemory server failed, falling back to unified server'); attemptFallback = true; } if (attemptFallback && this.config.fallbackPath) { console.log('🔄 Falling back to unified server...'); serverPath = this.config.fallbackPath; this.serverProcess = spawn('node', [serverPath], { stdio: ['pipe', 'pipe', 'pipe'] }); } if (!this.serverProcess?.stdout || !this.serverProcess?.stdin || !this.serverProcess?.stderr) { throw new Error('Failed to create server process with stdio'); } // Set up JSON-RPC communication let buffer = ''; this.serverProcess.stdout!.on('data', (data) => { buffer += data.toString(); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.trim()) { try { const message = JSON.parse(line); this.handleServerMessage(message); } catch (e) { // Ignore non-JSON lines (logs, etc.) } } } }); this.serverProcess.stderr!.on('data', (data) => { // Log server errors but don't fail connection console.warn('BEHEMOTH server:', data.toString().trim()); }); this.serverProcess!.on('exit', () => { this.isConnected = false; this.serverProcess = null; this.emit('disconnected'); }); // Wait a moment for server to initialize await new Promise(resolve => setTimeout(resolve, 1000)); // Initialize the MCP session const initResult = await this.sendRequest('initialize', { protocolVersion: '2024-11-05', capabilities: { tools: {} }, clientInfo: { name: 'behemoth-cli', version: '1.0.0' } }); if (initResult) { // Get available tools const toolsResult = await this.sendRequest('tools/list', {}); if (toolsResult && toolsResult.tools) { // Store tools this.tools.clear(); for (const tool of toolsResult.tools) { this.tools.set(tool.name, tool); } } this.isConnected = true; this.emit('connected', { toolCount: this.tools.size }); return true; } return false; } catch (error) { this.isConnected = false; this.emit('connection_error', { error: error instanceof Error ? error.message : 'Unknown connection error' }); return false; } } /** * Handle messages from the MCP server */ private handleServerMessage(message: any): void { if (message.id && this.pendingRequests.has(message.id)) { const request = this.pendingRequests.get(message.id); if (request) { clearTimeout(request.timeout); this.pendingRequests.delete(message.id); if (message.error) { request.reject(new Error(message.error.message || 'Server error')); } else { request.resolve(message.result); } } } } /** * Send a JSON-RPC request to the MCP server */ private async sendRequest(method: string, params: any = {}): Promise<any> { return new Promise((resolve, reject) => { if (!this.serverProcess || !this.serverProcess.stdin) { reject(new Error('Server process not available')); return; } const id = ++this.requestId; const request = { jsonrpc: '2.0', id, method, params }; const timeout = setTimeout(() => { this.pendingRequests.delete(id); reject(new Error(`Request timeout: ${method}`)); }, this.config.timeout); this.pendingRequests.set(id, { resolve, reject, timeout }); try { this.serverProcess.stdin!.write(JSON.stringify(request) + '\n'); } catch (error) { this.pendingRequests.delete(id); clearTimeout(timeout); reject(error); } }); } /** * Load available BEHEMOTH tools from MCP server */ private async loadAvailableTools(): Promise<void> { // Define BEHEMOTH tool categories and their tools const behemothTools = [ // Exchange Operations 'mcp__behemoth__bitget_spot_ticker', 'mcp__behemoth__bitget_futures_ticker', 'mcp__behemoth__bitget_place_order', 'mcp__behemoth__bitget_get_positions', 'mcp__behemoth__bitget_wallet_balance', 'mcp__behemoth__bybit_spot_ticker', 'mcp__behemoth__bybit_derivatives_ticker', 'mcp__behemoth__bybit_place_order', 'mcp__behemoth__bybit_get_positions', 'mcp__behemoth__bybit_wallet_balance', 'mcp__behemoth__binance_spot_ticker', 'mcp__behemoth__binance_futures_ticker', 'mcp__behemoth__get_all_futures_prices', 'mcp__behemoth__wallet_overview', // Technical Analysis 'mcp__behemoth__rsi_analysis', 'mcp__behemoth__macd_analysis', 'mcp__behemoth__bollinger_bands', 'mcp__behemoth__moving_averages', 'mcp__behemoth__fibonacci_retracement', 'mcp__behemoth__pivot_points', 'mcp__behemoth__stochastic_oscillator', 'mcp__behemoth__adx_indicator', 'mcp__behemoth__atr_indicator', 'mcp__behemoth__volume_profile', 'mcp__behemoth__ichimoku_cloud', 'mcp__behemoth__support_resistance', 'mcp__behemoth__trend_analysis', 'mcp__behemoth__momentum_indicators', 'mcp__behemoth__volatility_analysis', // Cosmic Intelligence 'mcp__behemoth__planetary_analysis', 'mcp__behemoth__lunar_phase_analysis', 'mcp__behemoth__sacred_geometry', 'mcp__behemoth__cosmic_timing', 'mcp__behemoth__energy_vortex', 'mcp__behemoth__harmonic_resonance', 'mcp__behemoth__fibonacci_spiral', 'mcp__behemoth__golden_ratio', 'mcp__behemoth__cosmic_cycles', 'mcp__behemoth__astro_trading', 'mcp__behemoth__time_fractals', 'mcp__behemoth__cosmic_convergence', 'mcp__behemoth__quantum_flux', 'mcp__behemoth__dimensional_analysis', // Sentiment Analysis 'mcp__behemoth__twitter_sentiment', 'mcp__behemoth__reddit_sentiment', 'mcp__behemoth__news_sentiment', 'mcp__behemoth__fear_greed_index', 'mcp__behemoth__social_volume', 'mcp__behemoth__whale_alerts', 'mcp__behemoth__on_chain_metrics', 'mcp__behemoth__funding_sentiment', 'mcp__behemoth__options_sentiment', 'mcp__behemoth__market_mood', // System & Monitoring 'mcp__behemoth__system_health', 'mcp__behemoth__performance_metrics', 'mcp__behemoth__error_tracking', 'mcp__behemoth__latency_monitor', 'mcp__behemoth__resource_usage', 'mcp__behemoth__alert_manager', // Advanced Analytics 'mcp__behemoth__fr3k_master_analysis', 'mcp__behemoth__cosmic_analyst_signals', 'mcp__behemoth__beast_architect_optimization', 'mcp__behemoth__neural_dev_enhancement', 'mcp__behemoth__persona_switcher', 'mcp__behemoth__fr3k_decision_engine' ]; // Create tool definitions for (const toolName of behemothTools) { const tool: McpTool = { name: toolName, description: this.getToolDescription(toolName), inputSchema: { type: 'object', properties: this.getToolProperties(toolName), required: this.getToolRequired(toolName) } }; this.tools.set(toolName, tool); } } /** * Get tool description based on tool name */ private getToolDescription(toolName: string): string { const descriptions: Record<string, string> = { // Exchange Operations 'mcp__behemoth__bitget_spot_ticker': 'Get real-time spot market ticker data from Bitget exchange', 'mcp__behemoth__bitget_futures_ticker': 'Get real-time futures market ticker data from Bitget exchange', 'mcp__behemoth__bitget_place_order': 'Place trading orders on Bitget futures market', 'mcp__behemoth__bitget_get_positions': 'Get current trading positions on Bitget', 'mcp__behemoth__bitget_wallet_balance': 'Get wallet balance from Bitget account', 'mcp__behemoth__bybit_spot_ticker': 'Get real-time spot market ticker data from Bybit exchange', 'mcp__behemoth__bybit_derivatives_ticker': 'Get real-time derivatives market ticker data from Bybit exchange', 'mcp__behemoth__bybit_place_order': 'Place trading orders on Bybit futures market', 'mcp__behemoth__bybit_get_positions': 'Get current trading positions on Bybit', 'mcp__behemoth__bybit_wallet_balance': 'Get wallet balance from Bybit account', 'mcp__behemoth__binance_spot_ticker': 'Get real-time spot market ticker data from Binance exchange', 'mcp__behemoth__binance_futures_ticker': 'Get real-time futures market ticker data from Binance exchange', 'mcp__behemoth__get_all_futures_prices': 'Get comprehensive futures prices across all supported exchanges', 'mcp__behemoth__wallet_overview': 'Get comprehensive wallet overview across all connected exchanges', // Technical Analysis 'mcp__behemoth__rsi_analysis': 'Calculate Relative Strength Index (RSI) for technical analysis', 'mcp__behemoth__macd_analysis': 'Calculate MACD indicator for trend analysis', 'mcp__behemoth__bollinger_bands': 'Calculate Bollinger Bands for volatility analysis', 'mcp__behemoth__moving_averages': 'Calculate various moving averages (SMA, EMA, WMA)', 'mcp__behemoth__fibonacci_retracement': 'Calculate Fibonacci retracement levels', 'mcp__behemoth__pivot_points': 'Calculate pivot points for support/resistance levels', 'mcp__behemoth__stochastic_oscillator': 'Calculate Stochastic oscillator for momentum analysis', 'mcp__behemoth__adx_indicator': 'Calculate Average Directional Index for trend strength', 'mcp__behemoth__atr_indicator': 'Calculate Average True Range for volatility measurement', 'mcp__behemoth__volume_profile': 'Analyze volume profile and distribution', 'mcp__behemoth__ichimoku_cloud': 'Calculate Ichimoku Cloud indicator suite', 'mcp__behemoth__support_resistance': 'Identify key support and resistance levels', 'mcp__behemoth__trend_analysis': 'Comprehensive trend analysis and direction detection', 'mcp__behemoth__momentum_indicators': 'Calculate various momentum indicators suite', 'mcp__behemoth__volatility_analysis': 'Advanced volatility analysis and metrics', // Cosmic Intelligence 'mcp__behemoth__planetary_analysis': 'Advanced planetary alignment analysis for market timing', 'mcp__behemoth__lunar_phase_analysis': 'Lunar phase analysis for market cycle prediction', 'mcp__behemoth__sacred_geometry': 'Sacred geometry patterns in price action analysis', 'mcp__behemoth__cosmic_timing': 'Cosmic timing analysis for optimal trade entry/exit', 'mcp__behemoth__energy_vortex': 'Energy vortex analysis for market momentum detection', 'mcp__behemoth__harmonic_resonance': 'Harmonic resonance patterns in market data', 'mcp__behemoth__fibonacci_spiral': 'Fibonacci spiral analysis for price projections', 'mcp__behemoth__golden_ratio': 'Golden ratio analysis in market structures', 'mcp__behemoth__cosmic_cycles': 'Cosmic cycle analysis for long-term market prediction', 'mcp__behemoth__astro_trading': 'Astrological trading signals and market correlation', 'mcp__behemoth__time_fractals': 'Time fractal analysis for multi-timeframe patterns', 'mcp__behemoth__cosmic_convergence': 'Cosmic convergence analysis for high-probability setups', 'mcp__behemoth__quantum_flux': 'Quantum flux analysis for market uncertainty quantification', 'mcp__behemoth__dimensional_analysis': 'Multi-dimensional market analysis beyond traditional TA', // System & Monitoring 'mcp__behemoth__system_health': 'Get BEHEMOTH system health status and performance metrics', 'mcp__behemoth__performance_metrics': 'Get detailed performance metrics and statistics', 'mcp__behemoth__error_tracking': 'Track and analyze system errors and issues', 'mcp__behemoth__latency_monitor': 'Monitor API latency and response times', 'mcp__behemoth__resource_usage': 'Monitor system resource usage and optimization', 'mcp__behemoth__alert_manager': 'Manage alerts and notification system', // Advanced Analytics 'mcp__behemoth__fr3k_master_analysis': 'FR3K master analysis combining all BEHEMOTH capabilities', 'mcp__behemoth__cosmic_analyst_signals': 'Cosmic analyst AI signals for trading decisions', 'mcp__behemoth__beast_architect_optimization': 'Beast architect system optimization and tuning', 'mcp__behemoth__neural_dev_enhancement': 'Neural development enhancement for improved accuracy', 'mcp__behemoth__persona_switcher': 'Switch between different AI personas for varied analysis', 'mcp__behemoth__fr3k_decision_engine': 'FR3K decision engine for comprehensive trade analysis' }; return descriptions[toolName] || `BEHEMOTH tool: ${toolName}`; } /** * Get tool properties based on tool name */ private getToolProperties(toolName: string): Record<string, any> { const commonSymbolProp = { symbol: { type: 'string', description: 'Trading pair symbol (e.g., BTCUSDT, ETHUSDT)', default: 'BTCUSDT' } }; const commonPeriodProp = { period: { type: 'number', description: 'Analysis period', default: 14 } }; // Trading order properties const orderProperties = { symbol: { type: 'string', description: 'Trading pair symbol' }, side: { type: 'string', enum: ['buy', 'sell'], description: 'Order side' }, orderType: { type: 'string', enum: ['market', 'limit'], description: 'Order type' }, qty: { type: 'number', description: 'Order quantity' }, price: { type: 'number', description: 'Order price (for limit orders)' } }; // Default to symbol property for most tools if (toolName.includes('place_order')) { return orderProperties; } else if (toolName.includes('analysis') || toolName.includes('indicator')) { return { ...commonSymbolProp, ...commonPeriodProp }; } else { return commonSymbolProp; } } /** * Get required properties for tool */ private getToolRequired(toolName: string): string[] { if (toolName.includes('place_order')) { return ['symbol', 'side', 'orderType', 'qty']; } return []; // Most tools have optional parameters } /** * Call a BEHEMOTH MCP tool */ async callTool(toolName: string, params: Record<string, any> = {}): Promise<McpCallResult> { const startTime = Date.now(); try { if (!this.isConnected) { const connected = await this.connect(); if (!connected) { return { success: false, error: 'Failed to connect to BEHEMOTH MCP server' }; } } // Call tool using JSON-RPC over stdio const result = await this.sendRequest('tools/call', { name: toolName, arguments: params }); const latency = Date.now() - startTime; return { success: true, result: result, latency_ms: latency, timestamp: Date.now() }; } catch (error) { const latency = Date.now() - startTime; return { success: false, error: error instanceof Error ? error.message : `Tool ${toolName} failed`, latency_ms: latency, timestamp: Date.now() }; } } /** * Get list of available tools */ getAvailableTools(): McpTool[] { return Array.from(this.tools.values()); } /** * Get tool by name */ getTool(name: string): McpTool | undefined { return this.tools.get(name); } /** * Check if connected to BEHEMOTH server */ isConnectedToBehemoth(): boolean { return this.isConnected; } /** * Disconnect from server */ async disconnect(): Promise<void> { this.isConnected = false; this.tools.clear(); // Clean up pending requests for (const [id, request] of this.pendingRequests) { clearTimeout(request.timeout); request.reject(new Error('Connection closed')); } this.pendingRequests.clear(); // Terminate server process if (this.serverProcess) { this.serverProcess.kill(); this.serverProcess = null; } this.emit('disconnected'); } /** * Get connection status and stats */ getConnectionInfo(): { connected: boolean; toolCount: number; config: BehemothConnectionConfig; } { return { connected: this.isConnected, toolCount: this.tools.size, config: this.config }; } } // Export singleton instance export const behemothClient = new BehemothMcpClient();