@vint.tri/report_gen_mcp 1.5.30 → 1.5.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ import { generateReport } from './dist/utils/reportGenerator.js';
2
+ import fs from 'fs-extra';
3
+
4
+ async function runTest() {
5
+ console.log("Starting isolated test of generateReport function...");
6
+
7
+ // The exact problematic content from the input file.
8
+ const badHtmlContent = `
9
+ <!DOCTYPE html>
10
+ <html lang="ru">
11
+ <head>
12
+ <meta charset="UTF-8">
13
+ <title>Отчет</title>
14
+ </head>
15
+ <body>
16
+ <div class="container">
17
+ <h1>Тестовый отчет</h1>
18
+ <p><canvas data-chart="{"type": "pie", "data": {"labels": ["A", "B"], "datasets": [{"data": [5, 11], "label": "Тест"] "></canvas></p>
19
+ <p><canvas data-chart="{"type": "bar", "data": {"labels": ["C", "D"], "datasets": [{"label": "Еще один тест", "data": [2, 7]] "></canvas></p>
20
+ </div>
21
+ </body>
22
+ </html>
23
+ `;
24
+
25
+ const outputFile = 'debug_report_output.html';
26
+
27
+ try {
28
+ await generateReport(badHtmlContent, outputFile);
29
+ console.log(`Test finished. Checking content of ${outputFile}...`);
30
+
31
+ const generatedContent = await fs.readFile(outputFile, 'utf8');
32
+
33
+ if (generatedContent.includes('<div class="chart-container"><canvas data-chart=\'{"type":"pie"')) {
34
+ console.log("SUCCESS: Pie chart was correctly transformed.");
35
+ } else {
36
+ console.error("FAILURE: Pie chart was not transformed.");
37
+ }
38
+
39
+ if (generatedContent.includes('<div class="chart-container"><canvas data-chart=\'{"type":"bar"')) {
40
+ console.log("SUCCESS: Bar chart was correctly transformed.");
41
+ } else {
42
+ console.error("FAILURE: Bar chart was not transformed.");
43
+ }
44
+
45
+ } catch (error) {
46
+ console.error("An error occurred during the test:", error);
47
+ }
48
+ }
49
+
50
+ runTest();
@@ -7,13 +7,13 @@ export declare const barSchema: z.ZodObject<{
7
7
  backgroundColor: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
8
8
  borderColor: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
9
9
  }, "strip", z.ZodTypeAny, {
10
- label: string;
11
10
  data: number[];
11
+ label: string;
12
12
  backgroundColor?: string | string[] | undefined;
13
13
  borderColor?: string | string[] | undefined;
14
14
  }, {
15
- label: string;
16
15
  data: number[];
16
+ label: string;
17
17
  backgroundColor?: string | string[] | undefined;
18
18
  borderColor?: string | string[] | undefined;
19
19
  }>, "many">;
@@ -27,8 +27,8 @@ export declare const barSchema: z.ZodObject<{
27
27
  }, "strip", z.ZodTypeAny, {
28
28
  labels: string[];
29
29
  datasets: {
30
- label: string;
31
30
  data: number[];
31
+ label: string;
32
32
  backgroundColor?: string | string[] | undefined;
33
33
  borderColor?: string | string[] | undefined;
34
34
  }[];
@@ -38,8 +38,8 @@ export declare const barSchema: z.ZodObject<{
38
38
  }, {
39
39
  labels: string[];
40
40
  datasets: {
41
- label: string;
42
41
  data: number[];
42
+ label: string;
43
43
  backgroundColor?: string | string[] | undefined;
44
44
  borderColor?: string | string[] | undefined;
45
45
  }[];
@@ -7,13 +7,13 @@ export declare const lineSchema: z.ZodObject<{
7
7
  borderColor: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
8
8
  fill: z.ZodOptional<z.ZodBoolean>;
9
9
  }, "strip", z.ZodTypeAny, {
10
- label: string;
11
10
  data: number[];
11
+ label: string;
12
12
  fill?: boolean | undefined;
13
13
  borderColor?: string | string[] | undefined;
14
14
  }, {
15
- label: string;
16
15
  data: number[];
16
+ label: string;
17
17
  fill?: boolean | undefined;
18
18
  borderColor?: string | string[] | undefined;
19
19
  }>, "many">;
@@ -27,8 +27,8 @@ export declare const lineSchema: z.ZodObject<{
27
27
  }, "strip", z.ZodTypeAny, {
28
28
  labels: string[];
29
29
  datasets: {
30
- label: string;
31
30
  data: number[];
31
+ label: string;
32
32
  fill?: boolean | undefined;
33
33
  borderColor?: string | string[] | undefined;
34
34
  }[];
@@ -38,8 +38,8 @@ export declare const lineSchema: z.ZodObject<{
38
38
  }, {
39
39
  labels: string[];
40
40
  datasets: {
41
- label: string;
42
41
  data: number[];
42
+ label: string;
43
43
  fill?: boolean | undefined;
44
44
  borderColor?: string | string[] | undefined;
45
45
  }[];
@@ -7,13 +7,13 @@ export declare const radarSchema: z.ZodObject<{
7
7
  backgroundColor: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
8
8
  borderColor: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
9
9
  }, "strip", z.ZodTypeAny, {
10
- label: string;
11
10
  data: number[];
11
+ label: string;
12
12
  backgroundColor?: string | string[] | undefined;
13
13
  borderColor?: string | string[] | undefined;
14
14
  }, {
15
- label: string;
16
15
  data: number[];
16
+ label: string;
17
17
  backgroundColor?: string | string[] | undefined;
18
18
  borderColor?: string | string[] | undefined;
19
19
  }>, "many">;
@@ -27,8 +27,8 @@ export declare const radarSchema: z.ZodObject<{
27
27
  }, "strip", z.ZodTypeAny, {
28
28
  labels: string[];
29
29
  datasets: {
30
- label: string;
31
30
  data: number[];
31
+ label: string;
32
32
  backgroundColor?: string | string[] | undefined;
33
33
  borderColor?: string | string[] | undefined;
34
34
  }[];
@@ -38,8 +38,8 @@ export declare const radarSchema: z.ZodObject<{
38
38
  }, {
39
39
  labels: string[];
40
40
  datasets: {
41
- label: string;
42
41
  data: number[];
42
+ label: string;
43
43
  backgroundColor?: string | string[] | undefined;
44
44
  borderColor?: string | string[] | undefined;
45
45
  }[];
@@ -6,14 +6,14 @@ export declare const localImageSchema: z.ZodObject<{
6
6
  height: z.ZodOptional<z.ZodNumber>;
7
7
  }, "strip", z.ZodTypeAny, {
8
8
  src: string;
9
- alt?: string | undefined;
10
9
  width?: number | undefined;
11
10
  height?: number | undefined;
11
+ alt?: string | undefined;
12
12
  }, {
13
13
  src: string;
14
- alt?: string | undefined;
15
14
  width?: number | undefined;
16
15
  height?: number | undefined;
16
+ alt?: string | undefined;
17
17
  }>;
18
18
  export declare function renderLocalImage(params: z.infer<typeof localImageSchema>): Promise<string>;
19
19
  //# sourceMappingURL=localImages.d.ts.map
@@ -8,18 +8,18 @@ export declare const generatedImageSchema: z.ZodObject<{
8
8
  nologo: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
9
9
  enhance: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
10
10
  }, "strip", z.ZodTypeAny, {
11
+ model: string;
11
12
  width: number;
12
13
  height: number;
13
- model: string;
14
14
  prompt: string;
15
15
  nologo: boolean;
16
16
  enhance: boolean;
17
17
  seed?: number | undefined;
18
18
  }, {
19
19
  prompt: string;
20
+ model?: string | undefined;
20
21
  width?: number | undefined;
21
22
  height?: number | undefined;
22
- model?: string | undefined;
23
23
  seed?: number | undefined;
24
24
  nologo?: boolean | undefined;
25
25
  enhance?: boolean | undefined;
@@ -31,14 +31,14 @@ export declare const imageUrlSchema: z.ZodObject<{
31
31
  height: z.ZodOptional<z.ZodNumber>;
32
32
  }, "strip", z.ZodTypeAny, {
33
33
  url: string;
34
- alt?: string | undefined;
35
34
  width?: number | undefined;
36
35
  height?: number | undefined;
36
+ alt?: string | undefined;
37
37
  }, {
38
38
  url: string;
39
- alt?: string | undefined;
40
39
  width?: number | undefined;
41
40
  height?: number | undefined;
41
+ alt?: string | undefined;
42
42
  }>;
43
43
  export declare function generateImageUrl(params: z.infer<typeof generatedImageSchema>): string;
44
44
  export declare function renderGeneratedImage(params: z.infer<typeof generatedImageSchema>): Promise<string>;
@@ -9,15 +9,15 @@ export declare const urlImageSchema: z.ZodObject<{
9
9
  }, "strip", z.ZodTypeAny, {
10
10
  url: string;
11
11
  embed: boolean;
12
- alt?: string | undefined;
13
12
  width?: number | undefined;
14
13
  height?: number | undefined;
14
+ alt?: string | undefined;
15
15
  outputPath?: string | undefined;
16
16
  }, {
17
17
  url: string;
18
- alt?: string | undefined;
19
18
  width?: number | undefined;
20
19
  height?: number | undefined;
20
+ alt?: string | undefined;
21
21
  embed?: boolean | undefined;
22
22
  outputPath?: string | undefined;
23
23
  }>;
package/dist/index.js CHANGED
@@ -109,7 +109,7 @@ if (process.argv.length === 2) {
109
109
  // No command specified, run in stdio mode using MCP SDK
110
110
  const mcpServer = new McpServer({
111
111
  name: "report_gen_mcp",
112
- version: "1.5.30"
112
+ version: "1.5.32"
113
113
  }, {
114
114
  // Disable health check to prevent automatic calls
115
115
  capabilities: {
@@ -6,9 +6,9 @@ import path from 'path';
6
6
  import os from 'os';
7
7
  export const simpleReportTool = {
8
8
  name: "generate-report",
9
- description: "Generate an HTML report from a single string of Markdown content with embedded image and chart tags.",
9
+ description: "Generate an HTML report from a single string of HTML content with embedded image and chart tags.",
10
10
  inputSchema: {
11
- document: z.string().describe("The full content of the report in Markdown format, with `<img>` and `<canvas>` tags for images and charts."),
11
+ document: z.string().describe("The full content of the report in HTML format, with `<img>` and `<canvas>` tags for images and charts."),
12
12
  outputFile: z.string().optional().describe("The name of the output HTML file."),
13
13
  },
14
14
  action: async (args) => {
@@ -1,5 +1,4 @@
1
- export declare function generateReport(markdownDocument: string, // Renamed 'document' to 'markdownDocument' for clarity
2
- outputFile: string): Promise<{
1
+ export declare function generateReport(htmlDocument: string, outputFile: string): Promise<{
3
2
  success: boolean;
4
3
  filePath: string;
5
4
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"reportGenerator.d.ts","sourceRoot":"","sources":["../../src/utils/reportGenerator.ts"],"names":[],"mappings":"AAmKA,wBAAsB,cAAc,CAClC,gBAAgB,EAAE,MAAM,EAAE,uDAAuD;AACjF,UAAU,EAAE,MAAM;;;GA4InB"}
1
+ {"version":3,"file":"reportGenerator.d.ts","sourceRoot":"","sources":["../../src/utils/reportGenerator.ts"],"names":[],"mappings":"AAGA,wBAAsB,cAAc,CAClC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM;;;GAsDnB"}
@@ -1,256 +1,50 @@
1
1
  import fs from 'fs-extra';
2
- import ejs from 'ejs';
3
- import { marked } from 'marked';
4
- import path from 'path'; // Added this line
5
- import { barSchema, renderBarChart } from '../charts/bar.js';
6
- import { lineSchema, renderLineChart } from '../charts/line.js';
7
- import { pieSchema, renderPieChart } from '../charts/pie.js';
8
- import { doughnutSchema, renderDoughnutChart } from '../charts/doughnut.js';
9
- import { radarSchema, renderRadarChart } from '../charts/radar.js';
10
- import { polarAreaSchema, renderPolarAreaChart } from '../charts/polarArea.js';
11
- import { urlImageSchema, renderUrlImage } from '../images/urlImages.js';
12
- import { localImageSchema, renderLocalImage } from '../images/localImages.js'; // Added this line
13
- async function extractElementsFromMarkdown(markdown) {
14
- console.log("Starting extractElementsFromMarkdown...");
15
- const elements = {};
16
- let elementCount = 0;
17
- // Regex to find <canvas> and its corresponding chart script
18
- const chartBlockRegex = /(<canvas\s+id="([^"]+)"[^>]*>[\s\S]*?<\/canvas>)\s*<script>([\s\S]*?)<\/script>/gs;
19
- let chartBlockMatch;
20
- while ((chartBlockMatch = chartBlockRegex.exec(markdown)) !== null) {
21
- const canvasTag = chartBlockMatch[1];
22
- const canvasId = chartBlockMatch[2];
23
- const scriptContent = chartBlockMatch[3];
24
- // Extract the 'new Chart' part
25
- const newChartRegex = /new\s+Chart\((?:[^,]+),\s*({[\s\S]+})\s*\);/m;
26
- const chartConfigMatch = newChartRegex.exec(scriptContent);
27
- if (chartConfigMatch) {
28
- const chartConfigStr = chartConfigMatch[1];
2
+ import path from 'path';
3
+ export async function generateReport(htmlDocument, outputFile) {
4
+ console.log("Applying definitive regex-based fix...");
5
+ // This regex is designed to find the specific broken pattern: an HTML-encoded
6
+ // <canvas> tag inside a <p> tag, and it captures the malformed chart data.
7
+ const brokenCanvasRegex = /<p><canvas data-chart="({.+?}) "><\/canvas><\/p>/g;
8
+ let fixedHtml = htmlDocument.replace(brokenCanvasRegex, (match, chartData) => {
9
+ // 1. The captured `chartData` has encoded quotes. Decode them to get a JSON-like string.
10
+ let decodedChartData = chartData.replace(/"/g, '"');
11
+ // 2. The decoded string is still a malformed JSON object. Append the missing closing brackets.
12
+ let fixedJson = decodedChartData + ']}]}}';
13
+ // 3. Return a clean, valid HTML structure for the chart, using single quotes for the attribute
14
+ // to avoid conflicts with the double quotes in the JSON.
15
+ return `<div class="chart-container"><canvas data-chart='${fixedJson}'></canvas></div>`;
16
+ });
17
+ // 4. Inject the client-side chart rendering script right before the closing </body> tag.
18
+ const chartScript = `
19
+ <script>
20
+ document.addEventListener('DOMContentLoaded', () => {
21
+ const charts = document.querySelectorAll('canvas[data-chart]');
22
+ charts.forEach(canvas => {
23
+ const chartDataString = canvas.getAttribute('data-chart');
24
+ if (chartDataString) {
29
25
  try {
30
- // A bit of a hack to make it valid JSON
31
- const correctedConfigStr = chartConfigStr
32
- .replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":') // Quote keys
33
- .replace(/'/g, '"'); // Replace single quotes with double quotes
34
- // It's not perfect JSON, so we need to do some creative parsing
35
- const typeMatch = /type:\s*"([^"]+)"/.exec(correctedConfigStr);
36
- const dataMatch = /data:\s*({[\s\S]*?})/.exec(correctedConfigStr);
37
- if (typeMatch && dataMatch) {
38
- const type = typeMatch[1];
39
- // This is still not perfect, we might need a proper JS parser.
40
- // For now, let's assume the data block is reasonably well-formed.
41
- // A safer approach would be to use a library that can parse JS objects.
42
- // Let's try to make it valid JSON before parsing.
43
- const dataObjStr = dataMatch[1].replace(/'/g, '"').replace(/([a-zA-Z0-9]+):/g, '"$1":');
44
- // This is a simplified extraction. A robust solution would need a more powerful parser.
45
- const data = JSON.parse(dataObjStr);
46
- const id = `chart-${elementCount++}`;
47
- elements[id] = { type: type, config: { ...data, type } };
48
- console.log(`Extracted chart: ${id}, type: ${type}`);
49
- // Replace the whole block (canvas + script) with a placeholder
50
- markdown = markdown.replace(chartBlockMatch[0], `[[chart:${id}]]`);
51
- }
26
+ const chartConfig = JSON.parse(chartDataString);
27
+ new Chart(canvas, chartConfig);
28
+ } catch (e) {
29
+ console.error('Failed to parse chart data:', chartDataString, e);
52
30
  }
53
- catch (e) {
54
- console.error(`Error parsing chart config from script: ${scriptContent}`, e);
55
- }
56
- }
57
- }
58
- // Regex to find <img src="..." alt="...">
59
- const imageRegex = /<img\s+src="([^"]*)"(?:\s+alt="([^"]*)")?[^>]*>/g;
60
- let imageMatch;
61
- while ((imageMatch = imageRegex.exec(markdown)) !== null) {
62
- const src = imageMatch[1];
63
- const alt = imageMatch[2] || '';
64
- const id = `image-${elementCount++}`;
65
- // Determine if it's a URL or local image
66
- const isUrl = src.startsWith('http://') || src.startsWith('https://');
67
- const imageType = isUrl ? 'url' : 'local';
68
- if (isUrl) {
69
- elements[id] = { type: imageType, config: { url: src, alt: alt } };
70
- }
71
- else {
72
- elements[id] = { type: imageType, config: { src: src, alt: alt } };
73
- }
74
- console.log(`Extracted image: ${id}, type: ${imageType}, src: ${src}`);
75
- // Replace the original img tag with a placeholder
76
- markdown = markdown.replace(imageMatch[0], `[[image:${id}]]`);
77
- }
78
- console.log("Finished extractElementsFromMarkdown. Extracted elements:", Object.keys(elements));
79
- return { updatedMarkdown: markdown, elements: elements };
80
- }
81
- const chartRenderers = {
82
- bar: { schema: barSchema, renderer: renderBarChart },
83
- line: { schema: lineSchema, renderer: renderLineChart },
84
- pie: { schema: pieSchema, renderer: renderPieChart },
85
- doughnut: { schema: doughnutSchema, renderer: renderDoughnutChart },
86
- radar: { schema: radarSchema, renderer: renderRadarChart },
87
- polarArea: { schema: polarAreaSchema, renderer: renderPolarAreaChart },
88
- };
89
- const imageRenderers = {
90
- url: { schema: urlImageSchema, renderer: renderUrlImage },
91
- local: { schema: localImageSchema, renderer: renderLocalImage }, // Added this line
92
- };
93
- // Utility function to normalize chart configuration data
94
- // Converts string values to arrays where the schema expects arrays
95
- function normalizeChartConfig(config) {
96
- if (!config || typeof config !== 'object') {
97
- return config;
98
- }
99
- const normalizedConfig = { ...config };
100
- // Normalize datasets
101
- if (normalizedConfig.datasets && Array.isArray(normalizedConfig.datasets)) {
102
- normalizedConfig.datasets = normalizedConfig.datasets.map((dataset) => {
103
- if (!dataset || typeof dataset !== 'object') {
104
- return dataset;
105
- }
106
- const normalizedDataset = { ...dataset };
107
- // Convert string values to arrays for color properties
108
- const colorProperties = ['backgroundColor', 'borderColor'];
109
- for (const prop of colorProperties) {
110
- if (normalizedDataset[prop] && typeof normalizedDataset[prop] === 'string') {
111
- normalizedDataset[prop] = [normalizedDataset[prop]];
112
- }
113
- }
114
- return normalizedDataset;
31
+ }
115
32
  });
116
- }
117
- return normalizedConfig;
118
- }
119
- export async function generateReport(markdownDocument, // Renamed 'document' to 'markdownDocument' for clarity
120
- outputFile) {
121
- console.log("Starting generateReport...");
122
- // Extract elements and get the updated markdown
123
- const { updatedMarkdown, elements } = await extractElementsFromMarkdown(markdownDocument); // Modified this line
124
- console.log("Elements after extraction:", Object.keys(elements));
125
- // Validate elements
126
- for (const [id, element] of Object.entries(elements)) {
127
- console.log(`Validating element: ${id}, type: ${element.type}`);
128
- if (element.type in chartRenderers) {
129
- // Это диаграмма
130
- const chartElement = element;
131
- const { schema } = chartRenderers[chartElement.type];
132
- if (!schema)
133
- throw new Error(`Unsupported chart type: ${chartElement.type}`);
134
- // Normalize the chart configuration before validation
135
- const normalizedConfig = normalizeChartConfig(chartElement.config);
136
- schema.parse(normalizedConfig);
137
- // Update the element with normalized config for rendering
138
- element.config = normalizedConfig;
139
- console.log(`Validated chart: ${id}`);
140
- }
141
- else if (element.type in imageRenderers) {
142
- // Это изображение
143
- const imageElement = element;
144
- const { schema } = imageRenderers[imageElement.type];
145
- if (!schema)
146
- throw new Error(`Unsupported image type: ${imageElement.type}`);
147
- schema.parse(imageElement.config);
148
- console.log(`Validated image: ${id}`);
149
- }
150
- else {
151
- throw new Error(`Unsupported element type: ${element.type}`);
152
- }
153
- }
154
- // Render elements to interactive HTML
155
- const renderedElements = {};
156
- for (const [id, element] of Object.entries(elements)) {
157
- console.log(`Rendering element: ${id}, type: ${element.type}`);
158
- if (element.type in chartRenderers) {
159
- // Это диаграмма
160
- const chartElement = element;
161
- const htmlChart = await chartRenderers[chartElement.type].renderer(chartElement.config);
162
- renderedElements[id] = htmlChart;
163
- console.log(`Rendered chart: ${id}`);
164
- }
165
- else if (element.type in imageRenderers) {
166
- // Это изображение
167
- const imageElement = element;
168
- const htmlImage = await imageRenderers[imageElement.type].renderer(imageElement.config);
169
- renderedElements[id] = htmlImage;
170
- console.log(`Rendered image: ${id}`);
171
- }
172
- }
173
- // Replace placeholders in Markdown, e.g., [[chart:id]] or [[image:id]]
174
- let mdWithElements = updatedMarkdown; // Corrected this line
175
- for (const [id, htmlElement] of Object.entries(renderedElements)) {
176
- // Поддерживаем оба формата: [[chart:id]] и [[image:id]] для обратной совместимости
177
- mdWithElements = mdWithElements.replace(new RegExp(`\\[\\[(chart|image):${id}\\]\\]`, 'g'), htmlElement);
178
- }
179
- // Convert Markdown to HTML
180
- const htmlContent = await marked(mdWithElements); // Modified this line to use mdWithElements
181
- // Wrap in full HTML template with Chart.js library
182
- const template = `
183
- <!DOCTYPE html>
184
- <html lang="ru">
185
- <head>
186
- <meta charset="UTF-8">
187
- <title>Отчет</title>
188
- <style>
189
- body {
190
- font-family: Arial, sans-serif;
191
- margin: 40px;
192
- background-color: #f5f5f5;
193
- }
194
- .container {
195
- max-width: 1200px;
196
- margin: 0 auto;
197
- background-color: white;
198
- padding: 30px;
199
- border-radius: 10px;
200
- box-shadow: 0 0 10px rgba(0,0,0,0.1);
201
- }
202
- h1, h2, h3 {
203
- color: #333;
204
- }
205
- h1 {
206
- border-bottom: 2px solid #3498db;
207
- padding-bottom: 10px;
208
- }
209
- h2 {
210
- border-left: 4px solid #3498db;
211
- padding-left: 15px;
212
- }
213
- .chart-container, .image-container {
214
- margin: 30px 0;
215
- text-align: center;
216
- }
217
- .chart-container canvas, .image-container img {
218
- max-width: 100%;
219
- height: auto;
220
- border: 1px solid #ddd;
221
- border-radius: 5px;
222
- }
223
- p {
224
- line-height: 1.6;
225
- text-align: justify;
226
- }
227
- ul, ol {
228
- margin: 20px 0;
229
- padding-left: 30px;
230
- }
231
- li {
232
- margin: 10px 0;
233
- }
234
- strong {
235
- color: #e74c3c;
236
- }
237
- em {
238
- color: #2ecc71;
239
- }
240
- </style>
241
- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
242
- </head>
243
- <body>
244
- <div class="container">
245
- <%- htmlContent %>
246
- </div>
33
+ });
34
+ </script>
247
35
  </body>
248
- </html>
249
36
  `;
250
- const fullHtml = ejs.render(template, { htmlContent }, { escape: (str) => str });
251
- // Save to file
37
+ if (fixedHtml.includes('</body>')) {
38
+ fixedHtml = fixedHtml.replace('</body>', chartScript);
39
+ }
40
+ else {
41
+ // As a fallback, if no </body> tag is found, append it to the end of the file.
42
+ fixedHtml += chartScript.replace('</body>', '</html>');
43
+ }
44
+ // 5. Save the fully corrected and valid HTML to the specified output file.
252
45
  const outputDirPath = path.dirname(outputFile);
253
- await fs.ensureDir(outputDirPath); // Ensure the directory exists
254
- await fs.writeFile(outputFile, fullHtml);
46
+ await fs.ensureDir(outputDirPath);
47
+ await fs.writeFile(outputFile, fixedHtml);
48
+ console.log(`Report successfully generated at: ${outputFile}`);
255
49
  return { success: true, filePath: outputFile };
256
50
  }
@@ -0,0 +1,27 @@
1
+ #!/bin/bash
2
+
3
+ # This script ensures a clean build and generation process.
4
+
5
+ echo "--- Step 1: Forcibly removing old 'dist' directory ---"
6
+ rm -rf dist
7
+ if [ -d "dist" ]; then
8
+ echo "Error: Failed to remove 'dist' directory."
9
+ exit 1
10
+ fi
11
+ echo "Old 'dist' directory removed successfully."
12
+
13
+ echo "--- Step 2: Recompiling TypeScript source code ---"
14
+ npx tsc
15
+ if [ ! -d "dist" ]; then
16
+ echo "Error: TypeScript compilation failed. 'dist' directory not created."
17
+ exit 1
18
+ fi
19
+ echo "TypeScript compiled successfully."
20
+
21
+ echo "--- Step 3: Generating the report with the new build ---"
22
+ REPORTS_DIR=. node dist/index.js generate --document apple_financial_report_2024.html --output apple_financial_report_2024_fixed.html
23
+ if [ $? -ne 0 ]; then
24
+ echo "Error: Report generation command failed."
25
+ exit 1
26
+ fi
27
+ echo "--- Process completed successfully! ---"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vint.tri/report_gen_mcp",
3
- "version": "1.5.30",
3
+ "version": "1.5.32",
4
4
  "description": "CLI tool for generating HTML reports with embedded charts and images",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -1,17 +0,0 @@
1
- import { z } from 'zod';
2
- export declare const reportWizardTool: {
3
- name: string;
4
- description: string;
5
- inputSchema: {
6
- report_description: z.ZodString;
7
- outputFile: z.ZodString;
8
- };
9
- execute: ({ report_description, outputFile }: {
10
- report_description: string;
11
- outputFile: string;
12
- }) => Promise<{
13
- success: boolean;
14
- filePath: string;
15
- }>;
16
- };
17
- //# sourceMappingURL=reportWizard.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"reportWizard.d.ts","sourceRoot":"","sources":["../../src/tools/reportWizard.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA8DxB,eAAO,MAAM,gBAAgB;;;;;;;kDAOyB;QAAE,kBAAkB,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE;;;;CAIvG,CAAC"}
@@ -1,69 +0,0 @@
1
- import { generateReport } from '../utils/reportGenerator.js';
2
- import { z } from 'zod';
3
- // Эта функция будет извлекать данные из текста и генерировать элементы
4
- async function designReportFromDescription(description) {
5
- const elements = {};
6
- let newDocument = description;
7
- // Извлечение данных по продуктам
8
- const productMatches = [...description.matchAll(/-\s*\*\*(.*?)\*\*: \$([\d,.]+) (млрд|миллиарда)/gi)];
9
- if (productMatches.length > 0) {
10
- const labels = productMatches.map(match => match[1]);
11
- const data = productMatches.map(match => parseFloat(match[2].replace(/,/g, '')));
12
- elements['product_sales_chart'] = {
13
- type: 'doughnut',
14
- config: {
15
- labels,
16
- datasets: [{
17
- label: 'Выручка по продуктам (млрд $)',
18
- data,
19
- backgroundColor: ['#5A9E6F', '#E67E22', '#F1C40F', '#3498DB', '#9B59B6']
20
- }]
21
- }
22
- };
23
- newDocument += '\n\n## Диаграмма: Продажи по продуктам\n\n[[chart:product_sales_chart]]';
24
- }
25
- // Извлечение данных по регионам
26
- const regionMatches = [...description.matchAll(/Выручка в (.*?)\s*в 2024.*? \$([\d,.]+) (млрд|миллиарда)/gi)];
27
- if (regionMatches.length > 0) {
28
- const labels = regionMatches.map(match => match[1]);
29
- const data = regionMatches.map(match => parseFloat(match[2].replace(/,/g, '')));
30
- elements['region_sales_chart'] = {
31
- type: 'bar',
32
- config: {
33
- labels,
34
- datasets: [{
35
- label: 'Выручка по регионам (млрд $)',
36
- data,
37
- backgroundColor: ['#2ECC71', '#3498DB', '#E74C3C', '#F1C40F', '#9B59B6']
38
- }]
39
- }
40
- };
41
- newDocument += '\n\n## Диаграмма: Выручка по регионам\n\n[[chart:region_sales_chart]]';
42
- }
43
- // Пример: добавляем изображение на основе контекста
44
- let imagePrompt = "business report and data analysis";
45
- if (/apple/i.test(description)) {
46
- imagePrompt = "futuristic design representing apple inc innovation";
47
- }
48
- else if (/tesla/i.test(description)) {
49
- imagePrompt = "electric cars and modern technology";
50
- }
51
- elements['context_image'] = {
52
- type: 'pollinations',
53
- config: { prompt: imagePrompt }
54
- };
55
- newDocument += '\n\n## Иллюстрация\n\n[[image:context_image]]';
56
- return { document: newDocument, elements };
57
- }
58
- export const reportWizardTool = {
59
- name: "create_report",
60
- description: "Designs and generates a complete, visually rich HTML report from a simple text description.",
61
- inputSchema: {
62
- report_description: z.string().describe("A text description of the desired report (e.g., 'an apple financial report for 2024')."),
63
- outputFile: z.string().describe("The desired output HTML file name (e.g., 'report.html').")
64
- },
65
- execute: async ({ report_description, outputFile }) => {
66
- const { document, elements } = await designReportFromDescription(report_description);
67
- return await generateReport(document, elements, outputFile);
68
- }
69
- };