outputDir = __DIR__ . '/../Storage/charts/'; // Set the base URL for accessing charts $this->baseUrl = $_ENV['APP_BASE_URL'] ?? getenv('APP_BASE_URL') ?? 'https://ytygroup.app/aineuron'; // Create directory if it doesn't exist if (!is_dir($this->outputDir)) { mkdir($this->outputDir, 0755, true); } } /** * Generate the HTML template for ECharts */ protected function generateHtmlTemplate(string $title, string $chartOptions): string { return << {$title}

{$title}

HTML; } /** * Generate absolute URL for chart access */ protected function getChartUrl(string $filename): string { return rtrim($this->baseUrl, '/') . '/view-chart.php?file=' . urlencode($filename); } #[McpTool( name: 'generate_chart', description: 'Generates an interactive HTML chart using Apache ECharts. Supports bar, line, pie, area, scatter, and radar charts. Saves the chart as an HTML file and returns URLs for viewing and downloading.' )] public function generateChart( #[McpArg(description: 'Chart title')] string $title, #[McpArg(description: 'Chart type: bar, line, pie, area, scatter, radar')] string $chartType, #[McpArg(description: 'JSON array of data series. Format: [{"name": "Series1", "data": [1,2,3]}, ...]')] string $dataSeries, #[McpArg(description: 'JSON array of category labels. Format: ["Jan", "Feb", "Mar"]')] string $categories, #[McpArg(description: 'X-axis label (optional)')] string $xAxisLabel = '', #[McpArg(description: 'Y-axis label (optional)')] string $yAxisLabel = '' ): array { try { // Parse JSON inputs $seriesData = json_decode($dataSeries, true); $categoryLabels = json_decode($categories, true); if (!$seriesData || !$categoryLabels) { throw new \Exception("Invalid JSON format for data series or categories"); } // Build ECharts options based on chart type $chartType = strtolower($chartType); switch ($chartType) { case 'pie': $options = $this->buildPieChartOptions($title, $seriesData, $categoryLabels); break; case 'radar': $options = $this->buildRadarChartOptions($title, $seriesData, $categoryLabels); break; case 'scatter': $options = $this->buildScatterChartOptions($title, $seriesData, $categoryLabels, $xAxisLabel, $yAxisLabel); break; default: // bar, line, area $options = $this->buildStandardChartOptions($title, $chartType, $seriesData, $categoryLabels, $xAxisLabel, $yAxisLabel); break; } // Generate HTML $html = $this->generateHtmlTemplate($title, $options); // Save to file $filename = 'chart_' . time() . '_' . uniqid() . '.html'; $filepath = $this->outputDir . $filename; if (file_put_contents($filepath, $html) === false) { throw new \Exception("Failed to save chart file"); } $fileSize = filesize($filepath); return [ 'success' => true, 'message' => 'Interactive chart generated and saved', 'filename' => $filename, 'filepath' => $filepath, 'view_url' => $this->getChartUrl($filename), 'download_url' => $this->getChartUrl($filename) . '&download=1', 'chart_type' => $chartType, 'size' => $fileSize, 'display_mode' => 'file' // Changed from 'embedded' to 'file' ]; } catch (\Exception $e) { return [ 'success' => false, 'error' => $e->getMessage() ]; } } /** * Build options for standard charts (bar, line, area) */ protected function buildStandardChartOptions( string $title, string $type, array $seriesData, array $categories, string $xAxisLabel, string $yAxisLabel ): string { $series = []; foreach ($seriesData as $s) { $seriesItem = [ 'name' => $s['name'] ?? 'Data', 'type' => $type === 'area' ? 'line' : $type, 'data' => $s['data'] ?? [] ]; // Add area style for area charts if ($type === 'area') { $seriesItem['areaStyle'] = new \stdClass(); } // Smooth line for line/area charts if ($type === 'line' || $type === 'area') { $seriesItem['smooth'] = true; } $series[] = $seriesItem; } $options = [ 'title' => [ 'text' => $title, 'left' => 'center', 'textStyle' => [ 'fontSize' => 24, 'fontWeight' => 'normal' ] ], 'tooltip' => [ 'trigger' => 'axis', 'axisPointer' => [ 'type' => 'shadow' ] ], 'legend' => [ 'data' => array_column($seriesData, 'name'), 'top' => 50 ], 'grid' => [ 'left' => '3%', 'right' => '4%', 'bottom' => '3%', 'containLabel' => true ], 'xAxis' => [ 'type' => 'category', 'data' => $categories, 'name' => $xAxisLabel, 'nameLocation' => 'middle', 'nameGap' => 30 ], 'yAxis' => [ 'type' => 'value', 'name' => $yAxisLabel, 'nameLocation' => 'middle', 'nameGap' => 50 ], 'series' => $series, 'toolbox' => [ 'feature' => [ 'saveAsImage' => ['title' => 'Save as Image'], 'dataView' => ['title' => 'View Data', 'readOnly' => false], 'magicType' => ['type' => ['line', 'bar', 'stack'], 'title' => ['Line', 'Bar', 'Stack']], 'restore' => ['title' => 'Restore'] ] ] ]; return json_encode($options, JSON_PRETTY_PRINT); } /** * Build options for pie charts */ protected function buildPieChartOptions(string $title, array $seriesData, array $categories): string { // For pie charts, we expect single series with values matching categories $data = []; $values = $seriesData[0]['data'] ?? []; foreach ($categories as $index => $category) { $data[] = [ 'name' => $category, 'value' => $values[$index] ?? 0 ]; } $options = [ 'title' => [ 'text' => $title, 'left' => 'center', 'textStyle' => [ 'fontSize' => 24, 'fontWeight' => 'normal' ] ], 'tooltip' => [ 'trigger' => 'item', 'formatter' => '{a}
{b}: {c} ({d}%)' ], 'legend' => [ 'orient' => 'vertical', 'left' => 'left', 'top' => 50 ], 'series' => [ [ 'name' => $seriesData[0]['name'] ?? 'Data', 'type' => 'pie', 'radius' => '60%', 'data' => $data, 'emphasis' => [ 'itemStyle' => [ 'shadowBlur' => 10, 'shadowOffsetX' => 0, 'shadowColor' => 'rgba(0, 0, 0, 0.5)' ] ], 'label' => [ 'formatter' => '{b}: {d}%' ] ] ], 'toolbox' => [ 'feature' => [ 'saveAsImage' => ['title' => 'Save as Image'] ] ] ]; return json_encode($options, JSON_PRETTY_PRINT); } /** * Build options for radar charts */ protected function buildRadarChartOptions(string $title, array $seriesData, array $categories): string { $indicator = []; foreach ($categories as $category) { $indicator[] = ['name' => $category]; } $series = []; foreach ($seriesData as $s) { $series[] = [ 'name' => $s['name'] ?? 'Data', 'type' => 'radar', 'data' => [ [ 'value' => $s['data'] ?? [], 'name' => $s['name'] ?? 'Data' ] ] ]; } $options = [ 'title' => [ 'text' => $title, 'left' => 'center', 'textStyle' => [ 'fontSize' => 24, 'fontWeight' => 'normal' ] ], 'tooltip' => [ 'trigger' => 'item' ], 'legend' => [ 'data' => array_column($seriesData, 'name'), 'top' => 50 ], 'radar' => [ 'indicator' => $indicator ], 'series' => $series ]; return json_encode($options, JSON_PRETTY_PRINT); } /** * Build options for scatter charts */ protected function buildScatterChartOptions( string $title, array $seriesData, array $categories, string $xAxisLabel, string $yAxisLabel ): string { $series = []; foreach ($seriesData as $s) { $series[] = [ 'name' => $s['name'] ?? 'Data', 'type' => 'scatter', 'data' => $s['data'] ?? [], 'symbolSize' => 10 ]; } $options = [ 'title' => [ 'text' => $title, 'left' => 'center', 'textStyle' => [ 'fontSize' => 24, 'fontWeight' => 'normal' ] ], 'tooltip' => [ 'trigger' => 'item', 'formatter' => '{a}
{c}' ], 'legend' => [ 'data' => array_column($seriesData, 'name'), 'top' => 50 ], 'grid' => [ 'left' => '3%', 'right' => '4%', 'bottom' => '3%', 'containLabel' => true ], 'xAxis' => [ 'type' => 'value', 'name' => $xAxisLabel, 'nameLocation' => 'middle', 'nameGap' => 30 ], 'yAxis' => [ 'type' => 'value', 'name' => $yAxisLabel, 'nameLocation' => 'middle', 'nameGap' => 50 ], 'series' => $series, 'toolbox' => [ 'feature' => [ 'saveAsImage' => ['title' => 'Save as Image'], 'dataZoom' => ['title' => ['Zoom', 'Reset Zoom']] ] ] ]; return json_encode($options, JSON_PRETTY_PRINT); } #[McpTool( name: 'generate_simple_chart', description: 'Generates a simple interactive HTML chart for quick visualization using Apache ECharts. Easier to use than generate_chart with fewer parameters. Perfect for basic data visualization needs.' )] public function generateSimpleChart( #[McpArg(description: 'Chart title')] string $title, #[McpArg(description: 'Chart type: bar, line, pie, area')] string $type, #[McpArg(description: 'JSON object with labels and values. Format: {"labels": ["A","B"], "values": [10,20]}')] string $data ): array { try { $chartData = json_decode($data, true); if (!isset($chartData['labels']) || !isset($chartData['values'])) { throw new \Exception("Data must contain 'labels' and 'values' arrays"); } // Convert to format expected by generateChart $dataSeries = json_encode([ ['name' => 'Data', 'data' => $chartData['values']] ]); $categories = json_encode($chartData['labels']); return $this->generateChart( $title, $type, $dataSeries, $categories ); } catch (\Exception $e) { return [ 'success' => false, 'error' => $e->getMessage() ]; } } #[McpTool( name: 'generate_comparison_chart', description: 'Generates a side-by-side comparison chart with multiple metrics. Perfect for comparing performance, sales, or any multi-dimensional data.' )] public function generateComparisonChart( #[McpArg(description: 'Chart title')] string $title, #[McpArg(description: 'JSON array of items to compare. Format: [{"name": "Product A", "metrics": [100, 200, 150]}, ...]')] string $items, #[McpArg(description: 'JSON array of metric names. Format: ["Sales", "Profit", "Growth"]')] string $metricNames ): array { try { $itemsData = json_decode($items, true); $metrics = json_decode($metricNames, true); if (!$itemsData || !$metrics) { throw new \Exception("Invalid JSON format"); } // Transform data for ECharts $series = []; $categories = array_column($itemsData, 'name'); // Transpose data: each metric becomes a series foreach ($metrics as $index => $metricName) { $metricValues = []; foreach ($itemsData as $item) { $metricValues[] = $item['metrics'][$index] ?? 0; } $series[] = [ 'name' => $metricName, 'data' => $metricValues ]; } return $this->generateChart( $title, 'bar', json_encode($series), json_encode($categories), 'Items', 'Value' ); } catch (\Exception $e) { return [ 'success' => false, 'error' => $e->getMessage() ]; } } #[McpTool( name: 'generate_trend_chart', description: 'Generates a time-series trend chart perfect for showing data over time. Automatically formats dates and shows trends clearly.' )] public function generateTrendChart( #[McpArg(description: 'Chart title')] string $title, #[McpArg(description: 'JSON array of date strings. Format: ["2024-01", "2024-02", ...]')] string $dates, #[McpArg(description: 'JSON array of data series. Format: [{"name": "Metric1", "data": [100, 120, ...]}, ...]')] string $dataSeries ): array { try { $dateLabels = json_decode($dates, true); $series = json_decode($dataSeries, true); if (!$dateLabels || !$series) { throw new \Exception("Invalid JSON format"); } return $this->generateChart( $title, 'line', json_encode($series), json_encode($dateLabels), 'Time Period', 'Value' ); } catch (\Exception $e) { return [ 'success' => false, 'error' => $e->getMessage() ]; } } }