fr3kc0d3
Version: 
Personal AI Infrastructure (PAI) - Complete implementation of Daniel Miessler's PAI vision with 4-layer context enforcement, FOBs system, flow orchestration, and Kai digital assistant
391 lines (352 loc) ⢠13.4 kB
JavaScript
/**
 * fr3kc0de Reflect MCP Server
 * Performance analysis and trading strategy reflection system
 */
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import fs from 'fs/promises';
import path from 'path';
class Fr3kc0deReflectServer {
  constructor() {
    this.server = new Server(
      {
        name: 'fr3kc0de-reflect',
        version: '1.0.0',
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );
    this.reflectionsFile = path.join(process.cwd(), 'fr3kc0de-reflections.json');
    this.setupToolHandlers();
  }
  setupToolHandlers() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'mcp__fr3kc0de_reflect__analyze_performance',
          description: 'Analyze trading performance and generate insights',
          inputSchema: {
            type: 'object',
            properties: {
              trades: {
                type: 'array',
                description: 'Array of trade data for analysis',
              },
              timeframe: {
                type: 'string',
                description: 'Time period for analysis (day, week, month)',
                default: 'week',
              },
            },
            required: ['trades'],
          },
        },
        {
          name: 'mcp__fr3kc0de_reflect__strategy_review',
          description: 'Review and analyze trading strategy effectiveness',
          inputSchema: {
            type: 'object',
            properties: {
              strategy_name: {
                type: 'string',
                description: 'Name of the trading strategy to review',
              },
              performance_data: {
                type: 'object',
                description: 'Performance metrics and trade outcomes',
              },
              market_conditions: {
                type: 'string',
                description: 'Market conditions during strategy execution',
              },
            },
            required: ['strategy_name'],
          },
        },
        {
          name: 'mcp__fr3kc0de_reflect__cosmic_accuracy_review',
          description: 'Analyze accuracy of cosmic intelligence predictions',
          inputSchema: {
            type: 'object',
            properties: {
              predictions: {
                type: 'array',
                description: 'Array of cosmic predictions to analyze',
              },
              actual_outcomes: {
                type: 'array',
                description: 'Actual market outcomes for comparison',
              },
            },
            required: ['predictions', 'actual_outcomes'],
          },
        },
        {
          name: 'mcp__fr3kc0de_reflect__generate_improvement_plan',
          description: 'Generate actionable improvement plan based on performance analysis',
          inputSchema: {
            type: 'object',
            properties: {
              analysis_results: {
                type: 'object',
                description: 'Results from performance analysis',
              },
              focus_areas: {
                type: 'array',
                items: { type: 'string' },
                description: 'Specific areas to focus improvement on',
              },
            },
            required: ['analysis_results'],
          },
        },
      ],
    }));
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;
      try {
        switch (name) {
          case 'mcp__fr3kc0de_reflect__analyze_performance':
            return await this.analyzePerformance(args.trades, args.timeframe);
          case 'mcp__fr3kc0de_reflect__strategy_review':
            return await this.strategyReview(args.strategy_name, args.performance_data, args.market_conditions);
          case 'mcp__fr3kc0de_reflect__cosmic_accuracy_review':
            return await this.cosmicAccuracyReview(args.predictions, args.actual_outcomes);
          case 'mcp__fr3kc0de_reflect__generate_improvement_plan':
            return await this.generateImprovementPlan(args.analysis_results, args.focus_areas);
          default:
            throw new Error(`Unknown tool: ${name}`);
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Error: ${error.message}`,
            },
          ],
        };
      }
    });
  }
  async loadReflections() {
    try {
      const data = await fs.readFile(this.reflectionsFile, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      return { reflections: [], created_at: new Date().toISOString() };
    }
  }
  async saveReflections(reflections) {
    await fs.writeFile(this.reflectionsFile, JSON.stringify(reflections, null, 2));
  }
  async analyzePerformance(trades, timeframe = 'week') {
    if (!trades || trades.length === 0) {
      return {
        content: [
          {
            type: 'text',
            text: 'ā ļø No trade data provided for performance analysis.',
          },
        ],
      };
    }
    // Calculate basic performance metrics
    const totalTrades = trades.length;
    const winningTrades = trades.filter(t => t.pnl > 0).length;
    const losingTrades = trades.filter(t => t.pnl < 0).length;
    const winRate = (winningTrades / totalTrades * 100).toFixed(2);
    
    const totalPnL = trades.reduce((sum, t) => sum + (t.pnl || 0), 0);
    const avgWin = trades.filter(t => t.pnl > 0).reduce((sum, t, _, arr) => sum + t.pnl / arr.length, 0);
    const avgLoss = trades.filter(t => t.pnl < 0).reduce((sum, t, _, arr) => sum + Math.abs(t.pnl) / arr.length, 0);
    const profitFactor = avgWin / (avgLoss || 1);
    const analysis = {
      period: timeframe,
      total_trades: totalTrades,
      winning_trades: winningTrades,
      losing_trades: losingTrades,
      win_rate: winRate,
      total_pnl: totalPnL.toFixed(2),
      profit_factor: profitFactor.toFixed(2),
      avg_win: avgWin.toFixed(2),
      avg_loss: avgLoss.toFixed(2),
      analyzed_at: new Date().toISOString()
    };
    // Store reflection
    const reflections = await this.loadReflections();
    reflections.reflections.push({
      type: 'performance_analysis',
      data: analysis,
      timestamp: new Date().toISOString()
    });
    await this.saveReflections(reflections);
    return {
      content: [
        {
          type: 'text',
          text: `š **fr3kc0de Performance Analysis** (${timeframe})\n\n` +
                `šÆ **Win Rate**: ${winRate}% (${winningTrades}/${totalTrades} trades)\n` +
                `š° **Total P&L**: $${totalPnL.toFixed(2)}\n` +
                `š **Profit Factor**: ${profitFactor.toFixed(2)}\n` +
                `š¢ **Average Win**: $${avgWin.toFixed(2)}\n` +
                `š“ **Average Loss**: $${avgLoss.toFixed(2)}\n\n` +
                `**Key Insights:**\n` +
                `${winRate > 50 ? 'ā
' : 'ā ļø'} Win rate is ${winRate > 50 ? 'above' : 'below'} 50%\n` +
                `${profitFactor > 1 ? 'ā
' : 'ā ļø'} Profit factor is ${profitFactor > 1 ? 'positive' : 'negative'}\n` +
                `${totalPnL > 0 ? 'ā
' : 'ā ļø'} Overall ${totalPnL > 0 ? 'profitable' : 'unprofitable'} period`,
        },
      ],
    };
  }
  async strategyReview(strategyName, performanceData = {}, marketConditions = '') {
    const review = {
      strategy: strategyName,
      market_conditions: marketConditions,
      performance: performanceData,
      reviewed_at: new Date().toISOString()
    };
    // Generate strategy insights
    let insights = `š **Strategy Review: ${strategyName}**\n\n`;
    
    if (marketConditions) {
      insights += `š **Market Conditions**: ${marketConditions}\n\n`;
    }
    insights += `š **Performance Summary**:\n`;
    if (performanceData.winRate) {
      insights += `⢠Win Rate: ${performanceData.winRate}%\n`;
    }
    if (performanceData.totalReturn) {
      insights += `⢠Total Return: ${performanceData.totalReturn}%\n`;
    }
    if (performanceData.maxDrawdown) {
      insights += `⢠Max Drawdown: ${performanceData.maxDrawdown}%\n`;
    }
    insights += `\nšÆ **Strategy Effectiveness**:\n`;
    insights += `⢠Strategy shows ${performanceData.winRate > 50 ? 'positive' : 'challenging'} win rate\n`;
    insights += `⢠${performanceData.totalReturn > 0 ? 'Profitable' : 'Needs optimization'} in current market conditions\n`;
    insights += `⢠Drawdown ${performanceData.maxDrawdown < 10 ? 'well controlled' : 'requires attention'}\n`;
    // Store reflection
    const reflections = await this.loadReflections();
    reflections.reflections.push({
      type: 'strategy_review',
      data: review,
      timestamp: new Date().toISOString()
    });
    await this.saveReflections(reflections);
    return {
      content: [
        {
          type: 'text',
          text: insights,
        },
      ],
    };
  }
  async cosmicAccuracyReview(predictions, actualOutcomes) {
    if (!predictions || !actualOutcomes || predictions.length !== actualOutcomes.length) {
      return {
        content: [
          {
            type: 'text',
            text: 'ā ļø Invalid prediction data provided for cosmic accuracy review.',
          },
        ],
      };
    }
    let correctPredictions = 0;
    const totalPredictions = predictions.length;
    for (let i = 0; i < predictions.length; i++) {
      const prediction = predictions[i];
      const outcome = actualOutcomes[i];
      
      // Simple accuracy check - can be enhanced based on prediction format
      if (prediction.direction === outcome.direction) {
        correctPredictions++;
      }
    }
    const accuracy = (correctPredictions / totalPredictions * 100).toFixed(2);
    const cosmicReview = {
      total_predictions: totalPredictions,
      correct_predictions: correctPredictions,
      accuracy_percentage: accuracy,
      reviewed_at: new Date().toISOString()
    };
    // Store reflection
    const reflections = await this.loadReflections();
    reflections.reflections.push({
      type: 'cosmic_accuracy_review',
      data: cosmicReview,
      timestamp: new Date().toISOString()
    });
    await this.saveReflections(reflections);
    return {
      content: [
        {
          type: 'text',
          text: `š **Cosmic Intelligence Accuracy Review**\n\n` +
                `šÆ **Prediction Accuracy**: ${accuracy}% (${correctPredictions}/${totalPredictions})\n` +
                `${accuracy > 60 ? 'āØ' : 'ā ļø'} Cosmic intelligence is ${accuracy > 60 ? 'highly effective' : 'needs calibration'}\n\n` +
                `**Recommendations:**\n` +
                `${accuracy > 70 ? '⢠Continue leveraging cosmic signals\n⢠Increase position sizing confidence' : 
                  '⢠Review planetary alignment calculations\n⢠Adjust quantum entanglement sensitivity'}\n` +
                `⢠Monitor performance across different market conditions\n` +
                `⢠Document cosmic patterns with highest accuracy`,
        },
      ],
    };
  }
  async generateImprovementPlan(analysisResults, focusAreas = []) {
    const plan = {
      analysis_date: new Date().toISOString(),
      focus_areas: focusAreas,
      analysis_results: analysisResults,
    };
    let improvementPlan = `š **fr3kc0de Improvement Plan**\n\n`;
    
    if (focusAreas.length > 0) {
      improvementPlan += `šÆ **Focus Areas**:\n`;
      focusAreas.forEach(area => {
        improvementPlan += `⢠${area}\n`;
      });
      improvementPlan += `\n`;
    }
    improvementPlan += `š§ **Recommended Actions**:\n`;
    improvementPlan += `1. **Risk Management**: Review position sizing and stop loss placement\n`;
    improvementPlan += `2. **Strategy Optimization**: Backtest strategies across different market conditions\n`;
    improvementPlan += `3. **Cosmic Calibration**: Fine-tune cosmic intelligence sensitivity\n`;
    improvementPlan += `4. **Performance Tracking**: Implement more granular performance metrics\n`;
    improvementPlan += `5. **Multi-Agent Coordination**: Optimize agent consensus thresholds\n\n`;
    improvementPlan += `š **Success Metrics**:\n`;
    improvementPlan += `⢠Increase win rate to >60%\n`;
    improvementPlan += `⢠Improve profit factor to >1.5\n`;
    improvementPlan += `⢠Reduce maximum drawdown to <15%\n`;
    improvementPlan += `⢠Achieve >70% cosmic prediction accuracy\n`;
    // Store reflection
    const reflections = await this.loadReflections();
    reflections.reflections.push({
      type: 'improvement_plan',
      data: plan,
      timestamp: new Date().toISOString()
    });
    await this.saveReflections(reflections);
    return {
      content: [
        {
          type: 'text',
          text: improvementPlan,
        },
      ],
    };
  }
  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
  }
}
const server = new Fr3kc0deReflectServer();
server.run().catch(console.error);