UNPKG

flow-nexus

Version:

🚀 AI-Powered Swarm Intelligence Platform - Gamified MCP Development with 70+ Tools

1,525 lines (1,497 loc) • 229 kB
#!/usr/bin/env node // Windows keep-alive: Must be at the very top for npx compatibility if (process.platform === 'win32' && process.env.MCP_MODE === 'stdio') { // Keep process alive on Windows when running via npx const keepAlive = setInterval(() => {}, 1000000); // Clean up on exit process.on('SIGINT', () => { clearInterval(keepAlive); process.exit(0); }); process.on('SIGTERM', () => { clearInterval(keepAlive); process.exit(0); }); } import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { createRequire } from 'module'; import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; import fs from 'fs/promises'; import { SUPABASE_URL, SUPABASE_ANON_KEY } from './config/supabase-config.js'; import { db } from './services/supabase.js'; import supabaseClient from './services/supabase-client.js'; // E2B now handled via Edge Function // import { E2BService } from './services/e2b-service.js'; import { registration } from './services/registration.js'; import { security } from './middleware/security.js'; // import { e2b } from './services/e2b-service.js'; import { exec } from 'child_process'; import { promisify } from 'util'; import distributedNeuralTools from './tools/distributed-neural-tools.js'; import neuralTools from './tools/neural-mcp-tools.js'; import { registerPaymentTools } from './tools/payment-mcp-tools-secure.js'; const execAsync = promisify(exec); const require = createRequire(import.meta.url); const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); // Mode configurations with expanded tool sets const MODES = { complete: { name: 'Flow Nexus Complete', description: 'Full suite with all tools and resources including payments', tools: ['swarm', 'neural', 'github', 'daa', 'workflow', 'sandbox', 'app-store', 'auth', 'user-management', 'realtime', 'storage', 'application', 'system', 'payment'], resources: ['docs', 'templates', 'examples', 'configs'] }, store: { name: 'App Store Only', description: 'App store management and publishing tools', tools: ['app-store', 'application', 'storage', 'auth', 'user-management'], resources: ['templates', 'examples'] }, swarm: { name: 'Swarm Coordination', description: 'Multi-agent swarm orchestration', tools: ['swarm', 'neural', 'daa', 'auth', 'realtime'], resources: ['docs', 'configs'] }, dev: { name: 'Development Tools', description: 'Code execution and development utilities', tools: ['sandbox', 'workflow', 'github', 'auth', 'storage', 'system'], resources: ['examples', 'docs'] }, gamer: { name: 'Gamification Features', description: 'Challenges, achievements, and leaderboards', tools: ['app-store', 'auth', 'user-management'], resources: ['templates'], filter: ['challenge', 'achievement', 'leaderboard', 'ruv', 'gamification'] }, enterprise: { name: 'Enterprise Suite', description: 'Complete enterprise toolkit with all features', tools: ['swarm', 'neural', 'github', 'daa', 'workflow', 'sandbox', 'app-store', 'auth', 'user-management', 'realtime', 'storage', 'application', 'system', 'payment'], resources: ['docs', 'templates', 'examples', 'configs', 'analytics'] }, workflow: { name: 'Advanced Workflow System', description: 'Event-driven workflow orchestration with message queues and agents', tools: ['workflow', 'swarm', 'daa', 'auth', 'realtime'], resources: ['docs', 'templates', 'examples'], features: ['pgmq', 'vector', 'audit', 'agents'] }, 'neural-network': { name: 'Flow Nexus Neural', description: 'DIY neural network training with ruv-fann and templates', tools: ['neural', 'app-store', 'auth', 'storage', 'payment'], resources: ['templates', 'docs', 'examples'], features: ['ruv-fann', 'wasm', 'divergent', 'templates', 'validation'] } }; // Tool definitions by category const TOOL_CATEGORIES = { payment: [ { name: 'check_balance', description: 'Check current credit balance and auto-refill status', inputSchema: { type: 'object', properties: {}, } }, { name: 'create_payment_link', description: 'Create a secure payment link for purchasing credits', inputSchema: { type: 'object', properties: { amount: { type: 'number', description: 'Amount in USD (minimum $10)', minimum: 10, maximum: 10000, }, }, required: ['amount'], } }, { name: 'configure_auto_refill', description: 'Configure automatic credit refill settings', inputSchema: { type: 'object', properties: { enabled: { type: 'boolean', description: 'Enable or disable auto-refill', }, threshold: { type: 'number', description: 'Credit threshold to trigger refill', minimum: 10, }, amount: { type: 'number', description: 'Amount in USD to refill', minimum: 10, }, }, required: ['enabled'], } }, { name: 'get_payment_history', description: 'Get recent payment and transaction history', inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Number of transactions to return', minimum: 1, maximum: 100, default: 10, }, }, } }, ], auth: [ { name: 'auth_status', description: 'Check authentication status and permissions', inputSchema: { type: 'object', properties: { detailed: { type: 'boolean', description: 'Include detailed auth info' } } } }, { name: 'auth_init', description: 'Initialize secure authentication', inputSchema: { type: 'object', properties: { mode: { type: 'string', enum: ['user', 'service'], description: 'Authentication mode' } }, required: ['mode'] } } ], swarm: [ { name: 'swarm_init', description: 'Initialize multi-agent swarm with specified topology', inputSchema: { type: 'object', properties: { topology: { type: 'string', enum: ['hierarchical', 'mesh', 'ring', 'star'], description: 'Swarm topology: hierarchical (tree), mesh (peer-to-peer), ring (circular), star (centralized)' }, maxAgents: { type: 'number', minimum: 1, maximum: 100, default: 8, description: 'Maximum number of agents in swarm' }, strategy: { type: 'string', enum: ['balanced', 'specialized', 'adaptive'], default: 'balanced', description: 'Agent distribution strategy' } }, required: ['topology'] } }, { name: 'agent_spawn', description: 'Create specialized AI agent in swarm', inputSchema: { type: 'object', properties: { type: { type: 'string', enum: ['researcher', 'coder', 'analyst', 'optimizer', 'coordinator'], description: 'Agent specialization type' }, capabilities: { type: 'array', items: { type: 'string' }, description: 'Specific capabilities for the agent' }, name: { type: 'string', description: 'Custom agent identifier' } }, required: ['type'] } }, { name: 'task_orchestrate', description: 'Orchestrate complex task across swarm agents', inputSchema: { type: 'object', properties: { task: { type: 'string', description: 'Task description or instructions' }, priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'], default: 'medium', description: 'Task priority level' }, strategy: { type: 'string', enum: ['parallel', 'sequential', 'adaptive'], default: 'adaptive', description: 'Task execution strategy' }, maxAgents: { type: 'number', minimum: 1, maximum: 10, description: 'Maximum agents to use for task' } }, required: ['task'] } }, { name: 'swarm_list', description: 'List active swarms', inputSchema: { type: 'object', properties: { status: { type: 'string', enum: ['active', 'destroyed', 'all'], default: 'active', description: 'Filter by swarm status' } } } }, { name: 'swarm_status', description: 'Get swarm status and details', inputSchema: { type: 'object', properties: { swarm_id: { type: 'string', description: 'Swarm ID (optional, uses active swarm if not provided)' } } } }, { name: 'swarm_scale', description: 'Scale swarm up or down', inputSchema: { type: 'object', properties: { swarm_id: { type: 'string', description: 'Swarm ID (optional, uses active swarm if not provided)' }, target_agents: { type: 'number', minimum: 1, maximum: 100, description: 'Target number of agents' } }, required: ['target_agents'] } }, { name: 'swarm_destroy', description: 'Destroy swarm and clean up resources', inputSchema: { type: 'object', properties: { swarm_id: { type: 'string', description: 'Swarm ID (optional, uses active swarm if not provided)' } } } }, { name: 'swarm_create_from_template', description: 'Create swarm from app store template', inputSchema: { type: 'object', properties: { template_id: { type: 'string', description: 'Template ID from app store' }, template_name: { type: 'string', description: 'Template name (alternative to ID)' }, overrides: { type: 'object', properties: { maxAgents: { type: 'number', minimum: 1, maximum: 100 }, strategy: { type: 'string', enum: ['balanced', 'specialized', 'adaptive'] } }, description: 'Optional configuration overrides' } } } }, { name: 'swarm_templates_list', description: 'List available swarm templates', inputSchema: { type: 'object', properties: { category: { type: 'string', enum: ['quickstart', 'specialized', 'enterprise', 'custom', 'all'], default: 'all', description: 'Template category to filter by' }, includeStore: { type: 'boolean', default: true, description: 'Include templates from app store' } } } } ], 'app-store': [ { name: 'template_list', description: 'List available deployment templates', inputSchema: { type: 'object', properties: { category: { type: 'string', description: 'Filter by template category' }, template_type: { type: 'string', description: 'Filter by template type' }, featured: { type: 'boolean', description: 'Show only featured templates' }, limit: { type: 'number', minimum: 1, maximum: 100, default: 20, description: 'Maximum templates to return' } } } }, { name: 'template_get', description: 'Get specific template details', inputSchema: { type: 'object', properties: { template_id: { type: 'string', description: 'Template ID' }, template_name: { type: 'string', description: 'Template name (alternative to ID)' } } } }, { name: 'template_deploy', description: 'Deploy a template with variables', inputSchema: { type: 'object', properties: { template_id: { type: 'string', description: 'Template ID' }, template_name: { type: 'string', description: 'Template name (alternative to ID)' }, deployment_name: { type: 'string', description: 'Name for this deployment' }, variables: { type: 'object', description: 'Template variables (anthropic_api_key, prompt, etc.)' }, env_vars: { type: 'object', description: 'Additional environment variables' } } } }, { name: 'app_store_list_templates', description: 'List available application templates', inputSchema: { type: 'object', properties: { category: { type: 'string', description: 'Filter by template category' }, limit: { type: 'number', minimum: 1, maximum: 100, default: 20, description: 'Maximum templates to return' }, tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' } } } }, { name: 'app_store_publish_app', description: 'Publish new application to store', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Application name' }, description: { type: 'string', description: 'App description' }, category: { type: 'string', description: 'App category' }, source_code: { type: 'string', description: 'Application source code' }, version: { type: 'string', default: '1.0.0', description: 'Application version number' }, tags: { type: 'array', items: { type: 'string' }, description: 'Tags for categorizing the application' }, metadata: { type: 'object', description: 'Additional app metadata' } }, required: ['name', 'description', 'category', 'source_code'] } }, { name: 'challenges_list', description: 'List available challenges', inputSchema: { type: 'object', properties: { difficulty: { type: 'string', enum: ['beginner', 'intermediate', 'advanced', 'expert'], description: 'Filter by difficulty level' }, category: { type: 'string', description: 'Filter by category' }, status: { type: 'string', enum: ['active', 'completed', 'locked'], default: 'active', description: 'Challenge status filter' }, limit: { type: 'number', default: 20, minimum: 1, maximum: 100, description: 'Maximum number of challenges to return' } } } }, { name: 'challenge_get', description: 'Get specific challenge details', inputSchema: { type: 'object', properties: { challenge_id: { type: 'string', description: 'Challenge identifier' } }, required: ['challenge_id'] } }, { name: 'challenge_submit', description: 'Submit solution for a challenge', inputSchema: { type: 'object', properties: { challenge_id: { type: 'string', description: 'Challenge identifier' }, user_id: { type: 'string', description: 'User identifier' }, solution_code: { type: 'string', description: 'Solution code' }, language: { type: 'string', description: 'Programming language used' }, execution_time: { type: 'number', description: 'Time taken in milliseconds' } }, required: ['challenge_id', 'user_id', 'solution_code'] } }, { name: 'app_store_complete_challenge', description: 'Mark challenge as completed for user', inputSchema: { type: 'object', properties: { challenge_id: { type: 'string', description: 'Challenge identifier' }, user_id: { type: 'string', description: 'User identifier' }, submission_data: { type: 'object', description: 'Challenge completion data' } }, required: ['challenge_id', 'user_id'] } }, { name: 'leaderboard_get', description: 'Get leaderboard rankings', inputSchema: { type: 'object', properties: { type: { type: 'string', enum: ['global', 'weekly', 'monthly', 'challenge'], default: 'global', description: 'Leaderboard type' }, challenge_id: { type: 'string', description: 'Challenge ID for challenge-specific leaderboard' }, limit: { type: 'number', default: 10, minimum: 1, maximum: 100, description: 'Maximum number of leaderboard entries to return' } } } }, { name: 'achievements_list', description: 'List user achievements and badges', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User identifier' }, category: { type: 'string', description: 'Achievement category filter' } }, required: ['user_id'] } }, { name: 'app_store_earn_ruv', description: 'Award rUv credits to user', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User identifier' }, amount: { type: 'number', minimum: 1, description: 'rUv credits to award' }, reason: { type: 'string', description: 'Reason for earning credits' }, source: { type: 'string', description: 'Credit source (challenge, app_usage, etc.)' } }, required: ['user_id', 'amount', 'reason'] } }, { name: 'ruv_balance', description: 'Get user rUv credit balance', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User identifier' } }, required: ['user_id'] } }, { name: 'ruv_history', description: 'Get rUv transaction history', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User identifier' }, limit: { type: 'number', default: 20, minimum: 1, maximum: 100, description: 'Maximum number of transactions to return' } }, required: ['user_id'] } } ], sandbox: [ { name: 'sandbox_create', description: 'Create new code execution sandbox with optional environment variables', inputSchema: { type: 'object', properties: { template: { type: 'string', enum: ['node', 'python', 'react', 'nextjs', 'vanilla', 'base', 'claude-code'], description: 'Sandbox template type' }, name: { type: 'string', description: 'Sandbox identifier' }, env_vars: { type: 'object', description: 'Environment variables to set in sandbox (e.g., API keys)', additionalProperties: { type: 'string' } }, api_key: { type: 'string', description: 'Custom E2B API key (uses default if not provided)' }, anthropic_key: { type: 'string', description: 'Anthropic API key for Claude Code usage' }, timeout: { type: 'number', description: 'Sandbox timeout in seconds', default: 3600 }, metadata: { type: 'object', description: 'Additional metadata for the sandbox' }, install_packages: { type: 'array', items: { type: 'string' }, description: 'NPM/pip packages to install on creation' }, startup_script: { type: 'string', description: 'Script to run after sandbox creation' } }, required: ['template'] } }, { name: 'sandbox_execute', description: 'Execute code in sandbox environment with optional environment variables', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox identifier' }, code: { type: 'string', description: 'Code to execute' }, language: { type: 'string', description: 'Programming language', default: 'javascript' }, env_vars: { type: 'object', description: 'Environment variables for this execution', additionalProperties: { type: 'string' } }, working_dir: { type: 'string', description: 'Working directory for execution' }, timeout: { type: 'number', description: 'Execution timeout in seconds', default: 60 }, capture_output: { type: 'boolean', description: 'Whether to capture stdout/stderr', default: true } }, required: ['sandbox_id', 'code'] } }, { name: 'sandbox_list', description: 'List all sandboxes', inputSchema: { type: 'object', properties: { status: { type: 'string', enum: ['running', 'stopped', 'all'], default: 'all' } } } }, { name: 'sandbox_stop', description: 'Stop a running sandbox', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox identifier' } }, required: ['sandbox_id'] } }, { name: 'sandbox_configure', description: 'Configure environment variables and settings for existing sandbox', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox identifier' }, env_vars: { type: 'object', description: 'Environment variables to set/update', additionalProperties: { type: 'string' } }, anthropic_key: { type: 'string', description: 'Anthropic API key for Claude Code usage' }, install_packages: { type: 'array', items: { type: 'string' }, description: 'Additional packages to install' }, run_commands: { type: 'array', items: { type: 'string' }, description: 'Commands to run for configuration' } }, required: ['sandbox_id'] } }, { name: 'sandbox_delete', description: 'Delete a sandbox', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox identifier' } }, required: ['sandbox_id'] } }, { name: 'sandbox_status', description: 'Get sandbox status', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox identifier' } }, required: ['sandbox_id'] } }, { name: 'sandbox_upload', description: 'Upload file to sandbox', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox identifier' }, file_path: { type: 'string', description: 'Path in sandbox' }, content: { type: 'string', description: 'File content' } }, required: ['sandbox_id', 'file_path', 'content'] } }, { name: 'sandbox_logs', description: 'Get sandbox logs', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox identifier' }, lines: { type: 'number', default: 100, minimum: 1, maximum: 1000 } }, required: ['sandbox_id'] } } ], neural: [ // Add neural training tools ...neuralTools, // Add distributed neural tools ...distributedNeuralTools ], github: [ { name: 'github_repo_analyze', description: 'Analyze GitHub repository', inputSchema: { type: 'object', properties: { repo: { type: 'string', description: 'Repository name (owner/repo)' }, analysis_type: { type: 'string', enum: ['code_quality', 'performance', 'security'], description: 'Type of analysis to perform' } }, required: ['repo'] } } ], daa: [ { name: 'daa_agent_create', description: 'Create decentralized autonomous agent', inputSchema: { type: 'object', properties: { agent_type: { type: 'string', description: 'DAA agent type' }, capabilities: { type: 'array', items: { type: 'string' } }, resources: { type: 'object', description: 'Agent resources' } }, required: ['agent_type'] } } ], workflow: [ { name: 'workflow_create', description: 'Create advanced workflow with event-driven processing', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Workflow name' }, description: { type: 'string', description: 'Workflow description' }, steps: { type: 'array', description: 'Workflow steps with agent assignments' }, triggers: { type: 'array', description: 'Event triggers' }, priority: { type: 'integer', description: 'Priority (0-10)', minimum: 0, maximum: 10 }, metadata: { type: 'object', description: 'Additional metadata' } }, required: ['name', 'steps'] } }, { name: 'workflow_execute', description: 'Execute workflow with message queue processing', inputSchema: { type: 'object', properties: { workflow_id: { type: 'string', description: 'Workflow ID to execute' }, input_data: { type: 'object', description: 'Input data for execution' }, async: { type: 'boolean', description: 'Execute asynchronously via queue' } }, required: ['workflow_id'] } }, { name: 'workflow_status', description: 'Get workflow execution status and metrics', inputSchema: { type: 'object', properties: { workflow_id: { type: 'string', description: 'Workflow ID' }, execution_id: { type: 'string', description: 'Specific execution ID' }, include_metrics: { type: 'boolean', description: 'Include performance metrics' } } } }, { name: 'workflow_list', description: 'List workflows with filtering', inputSchema: { type: 'object', properties: { limit: { type: 'integer', description: 'Max results', default: 10 }, offset: { type: 'integer', description: 'Skip results', default: 0 }, status: { type: 'string', description: 'Filter by status' } } } }, { name: 'workflow_agent_assign', description: 'Assign optimal agent to workflow task', inputSchema: { type: 'object', properties: { task_id: { type: 'string', description: 'Task ID' }, agent_type: { type: 'string', description: 'Preferred agent type' }, use_vector_similarity: { type: 'boolean', description: 'Use vector matching' } }, required: ['task_id'] } }, { name: 'workflow_queue_status', description: 'Check message queue status', inputSchema: { type: 'object', properties: { queue_name: { type: 'string', description: 'Queue name (optional)' }, include_messages: { type: 'boolean', description: 'Include pending messages' } } } }, { name: 'workflow_audit_trail', description: 'Get workflow audit trail', inputSchema: { type: 'object', properties: { workflow_id: { type: 'string', description: 'Workflow ID' }, limit: { type: 'integer', description: 'Max events', default: 50 }, start_time: { type: 'string', description: 'Start timestamp' } } } } ], 'user-management': [ { name: 'user_register', description: 'Register new user account', inputSchema: { type: 'object', properties: { email: { type: 'string', description: 'User email' }, password: { type: 'string', description: 'User password' }, username: { type: 'string', description: 'Username' }, full_name: { type: 'string', description: 'Full name' } }, required: ['email', 'password'] } }, { name: 'user_login', description: 'Login user and create session', inputSchema: { type: 'object', properties: { email: { type: 'string', description: 'User email' }, password: { type: 'string', description: 'User password' } }, required: ['email', 'password'] } }, { name: 'user_logout', description: 'Logout user and clear session', inputSchema: { type: 'object', properties: {} } }, { name: 'user_verify_email', description: 'Verify email with token', inputSchema: { type: 'object', properties: { token: { type: 'string', description: 'Verification token' } }, required: ['token'] } }, { name: 'user_reset_password', description: 'Request password reset', inputSchema: { type: 'object', properties: { email: { type: 'string', description: 'User email' } }, required: ['email'] } }, { name: 'user_update_password', description: 'Update password with reset token', inputSchema: { type: 'object', properties: { token: { type: 'string', description: 'Reset token' }, new_password: { type: 'string', description: 'New password' } }, required: ['token', 'new_password'] } }, { name: 'user_upgrade', description: 'Upgrade user tier', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User ID' }, tier: { type: 'string', enum: ['pro', 'enterprise'], description: 'New tier' } }, required: ['user_id', 'tier'] } }, { name: 'user_stats', description: 'Get user statistics', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User ID' } }, required: ['user_id'] } }, { name: 'user_profile', description: 'Get user profile', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User ID' } }, required: ['user_id'] } }, { name: 'user_update_profile', description: 'Update user profile', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User ID' }, updates: { type: 'object', description: 'Profile updates' } }, required: ['user_id', 'updates'] } } ], 'realtime': [ { name: 'execution_stream_subscribe', description: 'Subscribe to real-time execution stream updates', inputSchema: { type: 'object', properties: { sandbox_id: { type: 'string', description: 'Sandbox ID to monitor' }, deployment_id: { type: 'string', description: 'Deployment ID to monitor' }, stream_type: { type: 'string', enum: ['claude-code', 'claude-flow-swarm', 'claude-flow-hive-mind', 'github-integration'], description: 'Type of execution stream to monitor' } } } }, { name: 'execution_stream_status', description: 'Get current status of execution stream', inputSchema: { type: 'object', properties: { stream_id: { type: 'string', description: 'Execution stream ID' }, sandbox_id: { type: 'string', description: 'Sandbox ID (alternative)' } } } }, { name: 'execution_files_list', description: 'List files created during execution', inputSchema: { type: 'object', properties: { stream_id: { type: 'string', description: 'Execution stream ID' }, sandbox_id: { type: 'string', description: 'Sandbox ID (alternative)' }, file_type: { type: 'string', description: 'Filter by file type' }, created_by: { type: 'string', enum: ['claude-code', 'claude-flow', 'git-clone', 'user'], description: 'Filter by creator' } } } }, { name: 'execution_file_get', description: 'Get specific file content from execution', inputSchema: { type: 'object', properties: { file_id: { type: 'string', description: 'File ID' }, stream_id: { type: 'string', description: 'Execution stream ID (alternative)' }, file_path: { type: 'string', description: 'File path (alternative)' } } } }, { name: 'realtime_subscribe', description: 'Subscribe to real-time database changes', inputSchema: { type: 'object', properties: { table: { type: 'string', description: 'Table to subscribe to' }, event: { type: 'string', enum: ['INSERT', 'UPDATE', 'DELETE', '*'], default: '*', description: 'Event type to listen for' }, filter: { type: 'string', description: 'Optional filter condition' } }, required: ['table'] } }, { name: 'realtime_unsubscribe', description: 'Unsubscribe from real-time changes', inputSchema: { type: 'object', properties: { subscription_id: { type: 'string', description: 'Subscription ID to cancel' } }, required: ['subscription_id'] } }, { name: 'realtime_list', description: 'List active subscriptions', inputSchema: { type: 'object', properties: {} } } ], 'storage': [ { name: 'storage_upload', description: 'Upload file to storage', inputSchema: { type: 'object', properties: { bucket: { type: 'string', description: 'Storage bucket name' }, path: { type: 'string', description: 'File path in bucket' }, content: { type: 'string', description: 'File content (base64 for binary)' }, content_type: { type: 'string', description: 'MIME type' } }, required: ['bucket', 'path', 'content'] } }, { name: 'storage_delete', description: 'Delete file from storage', inputSchema: { type: 'object', properties: { bucket: { type: 'string', description: 'Storage bucket name' }, path: { type: 'string', description: 'File path in bucket' } }, required: ['bucket', 'path'] } }, { name: 'storage_list', description: 'List files in storage bucket', inputSchema: { type: 'object', properties: { bucket: { type: 'string', description: 'Storage bucket name' }, path: { type: 'string', description: 'Path prefix', default: '' }, limit: { type: 'number', default: 100, minimum: 1, maximum: 1000, description: 'Maximum number of files to return' } }, required: ['bucket'] } }, { name: 'storage_get_url', description: 'Get public URL for file', inputSchema: { type: 'object', properties: { bucket: { type: 'string', description: 'Storage bucket name' }, path: { type: 'string', description: 'File path in bucket' }, expires_in: { type: 'number', description: 'URL expiry in seconds', default: 3600 } }, required: ['bucket', 'path'] } } ], 'application': [ { name: 'app_get', description: 'Get specific application details', inputSchema: { type: 'object', properties: { app_id: { type: 'string', description: 'Application ID' } }, required: ['app_id'] } }, { name: 'app_update', description: 'Update application information', inputSchema: { type: 'object', properties: { app_id: { type: 'string', description: 'Application ID' }, updates: { type: 'object', description: 'Updates to apply' } }, required: ['app_id', 'updates'] } }, { name: 'app_search', description: 'Search applications with filters', inputSchema: { type: 'object', properties: { search: { type: 'string', description: 'Search query' }, category: { type: 'string', description: 'Category filter' }, featured: { type: 'boolean', description: 'Featured apps only' }, limit: { type: 'number', default: 20, minimum: 1, maximum: 100 } } } }, { name: 'app_analytics', description: 'Get application analytics', inputSchema: { type: 'object', properties: { app_id: { type: 'string', description: 'Application ID' }, timeframe: { type: 'string', enum: ['24h', '7d', '30d', '90d'], default: '30d', description: 'Analytics timeframe' } }, required: ['app_id'] } }, { name: 'app_installed', description: 'Get user installed applications', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User ID' } }, required: ['user_id'] } } ], 'system': [ { name: 'system_health', description: 'Check system health status', inputSchema: { type: 'object', properties: {} } }, { name: 'audit_log', description: 'Get audit log entries', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'Filter by user ID' }, limit: { type: 'number', default: 100, minimum: 1, maximum: 1000 } } } }, { name: 'market_data', description: 'Get market statistics and trends', inputSchema: { type: 'object', properties: {} } }, { name: 'seraphina_chat', description: 'Seek audience with Queen Seraphina for guidance and wisdom', inputSchema: { type: 'object', properties: { message: { type: 'string', description: 'Your message or question for Queen Seraphina' }, enable_tools: { type: 'boolean', description: 'Enable Seraphina to use tools (create swarms, deploy code)', default: false }, conversation_history: { type: 'array', description: 'Previous conversation messages for context', items: { type: 'object', properties: { role: { type: 'string', enum: ['user', 'assistant'] }, content: { type: 'string' } } } } }, required: ['message'] } } ], 'templates': [ { name: 'template_list', description: 'List available deployment templates', inputSchema: { type: 'object', properties: { category: { type: 'string', description: 'Filter by template category' }, template_type: { type: 'string', description: 'Filter by template type' }, featured: { type: 'boolean', description: 'Show only featured templates' }, limit: { type: 'number', default: 20, minimum: 1, maximum: 100 } } } }, { name: 'template_get', description: 'Get specific template details', inputSchema: { type: 'object', properties: { template_id: { type: 'string', description: 'Template ID' }, template_name: { type: 'string', description: 'Template name (alternative to ID)' } } } }, { name: 'template_deploy', description: 'Deploy a template with variables', inputSchema: { type: 'object', properties: { template_id: { type: 'string', description: 'Template ID' }, template_name: { type: 'string', description: 'Template name (alternative to ID)' }, variables: { type: 'object', description: 'Template variables (anthropic_api_key required for Claude Code)', additionalProperties: true }, deployment_name: { type: 'string', description: 'Custom deployment name' }, user_id: { type: 'string', description: 'User ID for deployment tracking' } }, required: ['variables'] } }, { name: 'template_deployments', description: 'List user template deployments', inputSchema: { type: 'object', properties: { user_id: { type: 'string', description: 'User ID' }, status: { type: 'string', enum: ['deploying', 'completed', 'failed', 'all'], default: 'all', description: 'Filter by deployment status' }, limit: { type: 'number', default: 20, minimum: 1, maximum: 100 } }, required: ['user_id'] } }, { name: 'template_create', description: 'Create a new deployment template', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Template name (unique identifier)' }, display_name: { type: 'string', description: 'Display name for users' }, description: { type: 'string', description: 'Template description' }, category: { type: 'string', description: 'Template category' }, template_type: { type: 'string', default: 'sandbox', description: 'Template type' }, config: { type: 'object', description: 'Template configuration' }, variables: { type: 'object', description: 'Variable definitions' }, required_variables: { type: 'array', items: { type: 'string' }, description: 'Required variable names' }, claude_command_template: { type: 'string', description: 'Claude Code command template' }, claude_args: { type: 'object', description: 'Claude Code arguments' }, sandbox_template: { type: 'string', default: 'claude-code', description: 'Sandbox template' }, install_packages: { type: 'array', items: { type: 'string' }, description: 'Packages to install' }, startup_script: { type: 'string', description: 'Startup script' }, tags: { type: 'array', items: { type: 'string' }, description: 'Template tags' }, is_public: { type: 'boolean', default: true, description: 'Make template public' } }, required: ['name', 'display_name', 'description'] } } ] }; // Flow Nexus Server with real Supabase integration class FlowNexusServer { constructor(mode = 'complete', flags = {}) { this.mode = mode; this.flags = flags; this.config = MODES[mode] || MODES.complete; // Initialize real services for production use this.supabaseClient = supabaseClient; // E2B service is now handled via Edge Function // this.e2bService = new E2BService(); // Apply flag overrides if (flags.tools) { this.config.tools = flags.tools.split(','); } if (flags.noAuth) { this.config.tools = this.config.tools.filter(t => t !== 'auth' && t !== 'user-management'); } if (flags.realtime) { if (!this.config.tools.includes('realtime')) { this.config.tools.push('realtime'); } } this.server = new Server( { name: this.config.name, version: '2.0.0' }, { capabilities: { resources: {}, tools: {} } } ); // Track active sessions and subscriptions this.sessions = new Map(); this.swarms = new Map(); this.sandboxes = new Map(); this.subscriptions = new Map(); this.currentUser = null; // Initialize available templates with safe defaults this.availableTemplates = ['base']; // 'base' template usually works for everyone this.loadAvailableTemplates(); // Load from database asynchronously this.setupHandlers(); } async loadAvailableTemplates() { try { // Define standard E2B templates only const standardTemplates = { 'base': 1, 'python': 2, 'claude-code': 3, 'react': 4, 'nextjs': 5, 'vanilla': 6, 'node': 7, 'nodejs': 7 }; // Query database for templates that have been successfully used const { data: sandboxes } = await db.client .from('sandboxes') .select('template') .not('template', 'is', null) .limit(100); if (sandboxes && sandboxes.length > 0) { // Get unique templates from database const uniqueTemplates = [...new Set(sandboxes.map(s => s.template))]; // Filter to only include standard templates // This excludes custom E2B template IDs like 'wfnm99zasqzu8af66lt2' const validTemplates = uniqueTemplates.filter(t => { return standardTemplates.hasOwnProperty(t); }); // Sort by priority const sortedTemplates = validTemplates.sort((a, b) => { return (standardTemplates[a] || 99) - (standardTemplates[b] || 99); }); // Ensure we always have at least 'base' template if (!sortedTemplates.includes('base')) { sortedTemplates.unshift('base'); } this.availableTemplates = sortedTemplates; console.log('E2B Templates loaded (standard only):', this.availableTemplates); } else { // If no sandboxes found, use all standard templates this.availableTemplates = Object.keys(standardTemplates).sort((a, b) => { return standardTemplates[a] - standardTemplates[b]; }); console.log('Using default standard templates:', this.availableTemplates); } } catch (error) { console.error('Failed to load templates:', error); // Keep default standard templates on error this.availableTemplates = ['base', 'python', 'claude-code', 'react', 'nextjs']; } } async getValidTemplate(requestedTemplate) { try { console.log(`[getValidTemplate] Looking up template: ${requestedTemplate}`); // First, check if it's a direct E2B template ID (format: alphanumeric) if (requestedTemplate && /^[a-z0-9]{20}$/.test(requestedTemplate)) { console.log(`[getValidTemplate] Direct E2B ID detected: ${requestedTemplate}`); return requestedTemplate; // Return E2B template ID directly } // Query the database for app store templates const { data: templates, error } = await db.client .from('app_store_templates') .select('name, config') .eq('name', requestedTemplate); console.log(`[getValidTemplate] Database query result:`, { templates, error }); if (!error && templates && templates.length > 0) { const template = templates[0]; // Return the E2B template ID from the config if (template.config?.e2b_template_id) { console.log(`[getValidTemplate] Found E2B ID in database: ${template.config.e2b_template_id}`); return template.config.e2b_template_id; } } // Query sandbox_templates table as fallback const { data: sandboxTemplates } = await db.client .from('sandbox_templates') .select('template_id, config') .or(`template_id.eq.${requestedTemplate},name.eq.${requestedTemplate}`); if (sandboxTemplates && sandboxTemplates.length > 0) { const template = sandboxTemplates[0]; // Return the template_id or e2b_template_id from config if (template.config?.e2b_template_id) { return template.config.e2b_template_id; } if (template.template_id && /^[a-z0-9]{20}$/.test(template.template_id)) { return template.template_id; } } // Fallback to basic template mappings for common types const basicMapping = { 'base': 'base', 'node': 'nodejs', 'nodejs': 'nodejs', 'javascript': 'nodejs', 'js': 'nodejs', 'typescript': 'nodejs', 'ts': 'n