-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathinsightTools.ts
More file actions
217 lines (191 loc) · 6.13 KB
/
Copy pathinsightTools.ts
File metadata and controls
217 lines (191 loc) · 6.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import { dbAll, dbExec, dbRun } from '../db/index.js';
import { PlotlyChartConfig } from '../types/index.js';
import { formatSuccessResponse, formatSuccessResponseHTML } from '../utils/formatUtils.js';
import { aggregateData } from '../utils/helper.js';
/**
* Add a business insight to the memo
* @param insight Business insight text
* @returns Result of the operation
*/
export async function appendInsight(insight: string) {
try {
if (!insight) {
throw new Error("Insight text is required");
}
// Create insights table if it doesn't exist
await dbExec(`
CREATE TABLE IF NOT EXISTS mcp_insights (
id INTEGER PRIMARY KEY AUTOINCREMENT,
insight TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Insert the insight
await dbRun(
"INSERT INTO mcp_insights (insight) VALUES (?)",
[insight]
);
return formatSuccessResponse({ success: true, message: "Insight added" });
} catch (error: any) {
throw new Error(`Error adding insight: ${error.message}`);
}
}
/**
* List all insights in the memo
* @returns Array of insights
*/
export async function listInsights() {
try {
// Check if insights table exists
const tableExists = await dbAll(
"SELECT name FROM sqlite_master WHERE type='table' AND name = 'mcp_insights'"
);
if (tableExists.length === 0) {
// Create table if it doesn't exist
await dbExec(`
CREATE TABLE IF NOT EXISTS mcp_insights (
id INTEGER PRIMARY KEY AUTOINCREMENT,
insight TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
return formatSuccessResponse([]);
}
const insights = await dbAll("SELECT * FROM mcp_insights ORDER BY created_at DESC");
return formatSuccessResponse(insights);
} catch (error: any) {
throw new Error(`Error listing insights: ${error.message}`);
}
}
export async function generatePlotlyChart(config: PlotlyChartConfig): Promise<any> {
const {
data,
chartType,
xColumn,
yColumn,
valueColumn,
labelColumn,
title,
colorColumn,
aggregation = 'none',
width = 800,
height = 600
} = config;
if (!data || data.length === 0) {
throw new Error('No data provided for chart generation');
}
let processedData = [...data];
if (aggregation && aggregation !== 'none' && xColumn) {
const targetColumn = yColumn || valueColumn;
if (targetColumn) {
processedData = aggregateData(data, xColumn, targetColumn, aggregation, colorColumn);
}
}
const layout: any = {
title: title || `${chartType.charAt(0).toUpperCase() + chartType.slice(1)} Chart`,
width,
height
};
let chartData: any[] = [];
try {
switch (chartType) {
case 'bar':
chartData = [{
type: 'bar',
x: processedData.map(row => row[xColumn!]),
y: processedData.map(row => row[yColumn!]),
marker: colorColumn ? { color: processedData.map(row => row[colorColumn]) } : undefined
}];
layout.xaxis = { title: xColumn };
layout.yaxis = { title: yColumn };
break;
case 'line':
chartData = [{
type: 'scatter',
mode: 'lines+markers',
x: processedData.map(row => row[xColumn!]),
y: processedData.map(row => row[yColumn!]),
line: colorColumn ? { color: processedData.map(row => row[colorColumn]) } : undefined
}];
layout.xaxis = { title: xColumn };
layout.yaxis = { title: yColumn };
break;
case 'pie':
chartData = [{
type: 'pie',
labels: processedData.map(row => row[labelColumn!]),
values: processedData.map(row => row[valueColumn!])
}];
break;
case 'scatter':
chartData = [{
type: 'scatter',
mode: 'markers',
x: processedData.map(row => row[xColumn!]),
y: processedData.map(row => row[yColumn!]),
marker: colorColumn ? { color: processedData.map(row => row[colorColumn]), colorscale: 'Viridis' } : undefined
}];
layout.xaxis = { title: xColumn };
layout.yaxis = { title: yColumn };
break;
case 'histogram':
chartData = [{
type: 'histogram',
x: processedData.map(row => row[xColumn!]).filter(Boolean)
}];
layout.xaxis = { title: xColumn };
layout.yaxis = { title: 'Frequency' };
break;
case 'box':
chartData = [{
type: 'box',
y: processedData.map(row => row[xColumn!]).filter(Boolean),
name: xColumn
}];
layout.yaxis = { title: xColumn };
break;
case 'heatmap':
if (!xColumn || !yColumn || !valueColumn) {
throw new Error('Heatmap requires xColumn, yColumn, and valueColumn');
}
const xValues = [...new Set(processedData.map(row => row[xColumn]))];
const yValues = [...new Set(processedData.map(row => row[yColumn]))];
const matrix = yValues.map(y =>
xValues.map(x => {
const match = processedData.find(row => row[xColumn] === x && row[yColumn] === y);
return match ? match[valueColumn] : 0;
})
);
chartData = [{
type: 'heatmap',
x: xValues,
y: yValues,
z: matrix,
colorscale: 'Viridis'
}];
layout.xaxis = { title: xColumn };
layout.yaxis = { title: yColumn };
break;
default:
throw new Error(`Unsupported chart type: ${chartType}`);
}
// Return as full HTML string
return formatSuccessResponseHTML(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="chart" style="width:${width}px;height:${height}px;"></div>
<script>
Plotly.newPlot('chart', ${JSON.stringify(chartData)}, ${JSON.stringify(layout)});
</script>
</body>
</html>
`);
} catch (error) {
throw new Error(`Failed to generate ${chartType} chart: ${error}`);
}
}