@outsidedata/dolex 1.0.1 → 3.0.0

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.
Files changed (175) hide show
  1. package/README.md +6 -7
  2. package/dist/src/analysis/rules.d.ts.map +1 -1
  3. package/dist/src/analysis/rules.js +29 -36
  4. package/dist/src/analysis/rules.js.map +1 -1
  5. package/dist/src/analysis/types.d.ts +1 -2
  6. package/dist/src/analysis/types.d.ts.map +1 -1
  7. package/dist/src/connectors/csv.d.ts.map +1 -1
  8. package/dist/src/connectors/csv.js +131 -0
  9. package/dist/src/connectors/csv.js.map +1 -1
  10. package/dist/src/connectors/manager.d.ts +16 -12
  11. package/dist/src/connectors/manager.d.ts.map +1 -1
  12. package/dist/src/connectors/manager.js +49 -43
  13. package/dist/src/connectors/manager.js.map +1 -1
  14. package/dist/src/connectors/types.d.ts +4 -0
  15. package/dist/src/connectors/types.d.ts.map +1 -1
  16. package/dist/src/index.d.ts +2 -4
  17. package/dist/src/index.d.ts.map +1 -1
  18. package/dist/src/index.js +1 -2
  19. package/dist/src/index.js.map +1 -1
  20. package/dist/src/mcp/app-shell.js +1 -2
  21. package/dist/src/mcp/app-shell.js.map +1 -1
  22. package/dist/src/mcp/index.d.ts +8 -7
  23. package/dist/src/mcp/index.d.ts.map +1 -1
  24. package/dist/src/mcp/index.js +50 -72
  25. package/dist/src/mcp/index.js.map +1 -1
  26. package/dist/src/mcp/prompts.js +1 -1
  27. package/dist/src/mcp/tools/drop-columns.d.ts +12 -0
  28. package/dist/src/mcp/tools/drop-columns.d.ts.map +1 -0
  29. package/dist/src/mcp/tools/drop-columns.js +122 -0
  30. package/dist/src/mcp/tools/drop-columns.js.map +1 -0
  31. package/dist/src/mcp/tools/export-html.d.ts +1 -1
  32. package/dist/src/mcp/tools/export-html.js +2 -2
  33. package/dist/src/mcp/tools/export-html.js.map +1 -1
  34. package/dist/src/mcp/tools/list-transforms.d.ts +11 -0
  35. package/dist/src/mcp/tools/list-transforms.d.ts.map +1 -0
  36. package/dist/src/mcp/tools/list-transforms.js +49 -0
  37. package/dist/src/mcp/tools/list-transforms.js.map +1 -0
  38. package/dist/src/mcp/tools/operation-log.d.ts +2 -13
  39. package/dist/src/mcp/tools/operation-log.d.ts.map +1 -1
  40. package/dist/src/mcp/tools/operation-log.js +1 -35
  41. package/dist/src/mcp/tools/operation-log.js.map +1 -1
  42. package/dist/src/mcp/tools/promote-columns.d.ts +11 -0
  43. package/dist/src/mcp/tools/promote-columns.d.ts.map +1 -0
  44. package/dist/src/mcp/tools/promote-columns.js +73 -0
  45. package/dist/src/mcp/tools/promote-columns.js.map +1 -0
  46. package/dist/src/mcp/tools/query-source.d.ts +4 -318
  47. package/dist/src/mcp/tools/query-source.d.ts.map +1 -1
  48. package/dist/src/mcp/tools/query-source.js +7 -13
  49. package/dist/src/mcp/tools/query-source.js.map +1 -1
  50. package/dist/src/mcp/tools/refine.d.ts +4 -4
  51. package/dist/src/mcp/tools/refine.js +2 -2
  52. package/dist/src/mcp/tools/refine.js.map +1 -1
  53. package/dist/src/mcp/tools/screenshot.js +1 -1
  54. package/dist/src/mcp/tools/screenshot.js.map +1 -1
  55. package/dist/src/mcp/tools/shared.d.ts +1 -23
  56. package/dist/src/mcp/tools/shared.d.ts.map +1 -1
  57. package/dist/src/mcp/tools/shared.js +2 -84
  58. package/dist/src/mcp/tools/shared.js.map +1 -1
  59. package/dist/src/mcp/tools/sql-schemas.d.ts +20 -0
  60. package/dist/src/mcp/tools/sql-schemas.d.ts.map +1 -0
  61. package/dist/src/mcp/tools/sql-schemas.js +18 -0
  62. package/dist/src/mcp/tools/sql-schemas.js.map +1 -0
  63. package/dist/src/mcp/tools/transform-data.d.ts +12 -0
  64. package/dist/src/mcp/tools/transform-data.d.ts.map +1 -0
  65. package/dist/src/mcp/tools/transform-data.js +73 -0
  66. package/dist/src/mcp/tools/transform-data.js.map +1 -0
  67. package/dist/src/mcp/tools/transform-schemas.d.ts +234 -0
  68. package/dist/src/mcp/tools/transform-schemas.d.ts.map +1 -0
  69. package/dist/src/mcp/tools/transform-schemas.js +35 -0
  70. package/dist/src/mcp/tools/transform-schemas.js.map +1 -0
  71. package/dist/src/mcp/tools/visualize.d.ts +12 -6
  72. package/dist/src/mcp/tools/visualize.d.ts.map +1 -1
  73. package/dist/src/mcp/tools/visualize.js +42 -11
  74. package/dist/src/mcp/tools/visualize.js.map +1 -1
  75. package/dist/src/renderers/html/index.d.ts +0 -2
  76. package/dist/src/renderers/html/index.d.ts.map +1 -1
  77. package/dist/src/renderers/html/index.js +0 -1
  78. package/dist/src/renderers/html/index.js.map +1 -1
  79. package/dist/src/transforms/column-functions.d.ts +19 -0
  80. package/dist/src/transforms/column-functions.d.ts.map +1 -0
  81. package/dist/src/transforms/column-functions.js +269 -0
  82. package/dist/src/transforms/column-functions.js.map +1 -0
  83. package/dist/src/transforms/column-manager.d.ts +35 -0
  84. package/dist/src/transforms/column-manager.d.ts.map +1 -0
  85. package/dist/src/transforms/column-manager.js +151 -0
  86. package/dist/src/transforms/column-manager.js.map +1 -0
  87. package/dist/src/transforms/dependency.d.ts +21 -0
  88. package/dist/src/transforms/dependency.d.ts.map +1 -0
  89. package/dist/src/transforms/dependency.js +129 -0
  90. package/dist/src/transforms/dependency.js.map +1 -0
  91. package/dist/src/transforms/evaluator.d.ts +38 -0
  92. package/dist/src/transforms/evaluator.d.ts.map +1 -0
  93. package/dist/src/transforms/evaluator.js +377 -0
  94. package/dist/src/transforms/evaluator.js.map +1 -0
  95. package/dist/src/transforms/index.d.ts +19 -0
  96. package/dist/src/transforms/index.d.ts.map +1 -0
  97. package/dist/src/transforms/index.js +21 -0
  98. package/dist/src/transforms/index.js.map +1 -0
  99. package/dist/src/transforms/manifest.d.ts +19 -0
  100. package/dist/src/transforms/manifest.d.ts.map +1 -0
  101. package/dist/src/transforms/manifest.js +136 -0
  102. package/dist/src/transforms/manifest.js.map +1 -0
  103. package/dist/src/transforms/metadata.d.ts +31 -0
  104. package/dist/src/transforms/metadata.d.ts.map +1 -0
  105. package/dist/src/transforms/metadata.js +116 -0
  106. package/dist/src/transforms/metadata.js.map +1 -0
  107. package/dist/src/transforms/parser.d.ts +22 -0
  108. package/dist/src/transforms/parser.d.ts.map +1 -0
  109. package/dist/src/transforms/parser.js +165 -0
  110. package/dist/src/transforms/parser.js.map +1 -0
  111. package/dist/src/transforms/pipeline.d.ts +40 -0
  112. package/dist/src/transforms/pipeline.d.ts.map +1 -0
  113. package/dist/src/transforms/pipeline.js +208 -0
  114. package/dist/src/transforms/pipeline.js.map +1 -0
  115. package/dist/src/transforms/row-functions.d.ts +11 -0
  116. package/dist/src/transforms/row-functions.d.ts.map +1 -0
  117. package/dist/src/transforms/row-functions.js +241 -0
  118. package/dist/src/transforms/row-functions.js.map +1 -0
  119. package/dist/src/transforms/tokenizer.d.ts +12 -0
  120. package/dist/src/transforms/tokenizer.d.ts.map +1 -0
  121. package/dist/src/transforms/tokenizer.js +135 -0
  122. package/dist/src/transforms/tokenizer.js.map +1 -0
  123. package/dist/src/transforms/types.d.ts +139 -0
  124. package/dist/src/transforms/types.d.ts.map +1 -0
  125. package/dist/src/transforms/types.js +19 -0
  126. package/dist/src/transforms/types.js.map +1 -0
  127. package/dist/src/types.d.ts +7 -164
  128. package/dist/src/types.d.ts.map +1 -1
  129. package/dist/src/types.js +0 -12
  130. package/dist/src/types.js.map +1 -1
  131. package/package.json +2 -2
  132. package/src/analysis/rules.ts +30 -37
  133. package/src/analysis/types.ts +1 -3
  134. package/src/connectors/csv.ts +147 -0
  135. package/src/connectors/manager.ts +69 -55
  136. package/src/connectors/types.ts +4 -0
  137. package/src/index.ts +3 -20
  138. package/src/mcp/app-shell.ts +1 -2
  139. package/src/mcp/index.ts +68 -82
  140. package/src/mcp/prompts.ts +1 -1
  141. package/src/mcp/tools/drop-columns.ts +144 -0
  142. package/src/mcp/tools/export-html.ts +2 -2
  143. package/src/mcp/tools/list-transforms.ts +63 -0
  144. package/src/mcp/tools/operation-log.ts +2 -50
  145. package/src/mcp/tools/promote-columns.ts +89 -0
  146. package/src/mcp/tools/query-source.ts +10 -17
  147. package/src/mcp/tools/refine.ts +2 -2
  148. package/src/mcp/tools/screenshot.ts +1 -1
  149. package/src/mcp/tools/shared.ts +2 -108
  150. package/src/mcp/tools/sql-schemas.ts +22 -0
  151. package/src/mcp/tools/transform-data.ts +87 -0
  152. package/src/mcp/tools/transform-schemas.ts +45 -0
  153. package/src/mcp/tools/visualize.ts +46 -10
  154. package/src/renderers/html/index.ts +0 -2
  155. package/src/transforms/column-functions.ts +310 -0
  156. package/src/transforms/column-manager.ts +194 -0
  157. package/src/transforms/dependency.ts +141 -0
  158. package/src/transforms/evaluator.ts +418 -0
  159. package/src/transforms/index.ts +71 -0
  160. package/src/transforms/manifest.ts +162 -0
  161. package/src/transforms/metadata.ts +147 -0
  162. package/src/transforms/parser.ts +205 -0
  163. package/src/transforms/pipeline.ts +301 -0
  164. package/src/transforms/row-functions.ts +228 -0
  165. package/src/transforms/tokenizer.ts +154 -0
  166. package/src/transforms/types.ts +142 -0
  167. package/src/types.ts +8 -212
  168. package/src/connectors/dsl-compiler.ts +0 -361
  169. package/src/connectors/dsl-validator.ts +0 -495
  170. package/src/connectors/js-aggregation.ts +0 -404
  171. package/src/mcp/tools/dashboard-refine.ts +0 -456
  172. package/src/mcp/tools/dashboard.ts +0 -62
  173. package/src/mcp/tools/dsl-schemas.ts +0 -262
  174. package/src/mcp/tools/visualize-from-source.ts +0 -92
  175. package/src/renderers/html/builders/dashboard.ts +0 -449
@@ -6,24 +6,43 @@
6
6
  * - In-memory registry with optional JSON file persistence
7
7
  * - Connector lookup by type
8
8
  * - Connection caching (lazy connect on first query)
9
- * - Cross-source query routing by name
9
+ * - SQL query execution with safety checks
10
10
  */
11
11
 
12
12
  import * as fs from 'fs';
13
13
  import * as crypto from 'crypto';
14
- import type { DataSourceType, DataSourceConfig, DataSchema, DslQuery } from '../types.js';
14
+ import type { DataSourceType, DataSourceConfig, DataSchema } from '../types.js';
15
15
  import type {
16
16
  ConnectedSource,
17
17
  SourceRegistryEntry,
18
18
  QueryExecutionResult,
19
19
  } from './types.js';
20
- import { compileDsl, hasJsAggregates, hasWindowFunctions } from './dsl-compiler.js';
21
- import { validateDsl, validateDslWithJoins } from './dsl-validator.js';
22
20
  import { csvConnector } from './csv.js';
23
- import type { DslQueryResult } from './js-aggregation.js';
24
- import { executeJsAggregation, executeJsAggregationWithWindows } from './js-aggregation.js';
25
21
 
26
- export type { DslQueryResult } from './js-aggregation.js';
22
+ const MAX_RESULT_ROWS = 10000;
23
+
24
+ // ─── SQL Query Result ─────────────────────────────────────────────────────
25
+
26
+ export interface SqlQueryResult {
27
+ ok: boolean;
28
+ rows?: Record<string, any>[];
29
+ columns?: string[];
30
+ totalRows?: number;
31
+ truncated?: boolean;
32
+ error?: string;
33
+ }
34
+
35
+ // ─── SQL Safety ───────────────────────────────────────────────────────────
36
+
37
+ function isReadOnlySelect(sql: string): boolean {
38
+ const trimmed = sql.trim().replace(/^\/\*.*?\*\//gs, '').trim();
39
+ return /^(SELECT|WITH)\b/i.test(trimmed);
40
+ }
41
+
42
+ function wrapWithLimit(sql: string, maxRows: number): string {
43
+ const trimmed = sql.trim().replace(/;\s*$/, '');
44
+ return `SELECT * FROM (${trimmed}) AS _q LIMIT ${maxRows}`;
45
+ }
27
46
 
28
47
  // ─── Helpers ─────────────────────────────────────────────────────────────────
29
48
 
@@ -220,7 +239,6 @@ export class SourceManager {
220
239
 
221
240
  /**
222
241
  * Lazily connect and return the source, or an error result.
223
- * Consolidates the repeated connect-or-fail pattern used by getSchema/query/queryDsl.
224
242
  */
225
243
  private async resolveSource(
226
244
  idOrName: string
@@ -264,77 +282,73 @@ export class SourceManager {
264
282
  }
265
283
 
266
284
  /**
267
- * Execute a DSL query against a specific source table.
268
- * Validates against schema, compiles to SQL (or JS aggregation fallback),
269
- * executes, and returns rows.
285
+ * Execute a SQL query against a source with safety checks.
286
+ * Only SELECT/WITH queries are allowed. Results are auto-capped at maxRows.
287
+ * Error messages are enriched with available table/column names.
270
288
  */
271
- async queryDsl(
289
+ async querySql(
272
290
  idOrName: string,
273
- table: string,
274
- dslQuery: DslQuery
275
- ): Promise<DslQueryResult> {
291
+ sql: string,
292
+ maxRows: number = MAX_RESULT_ROWS
293
+ ): Promise<SqlQueryResult> {
294
+ if (!isReadOnlySelect(sql)) {
295
+ return { ok: false, error: 'Only SELECT queries are allowed.' };
296
+ }
297
+
276
298
  const resolved = await this.resolveSource(idOrName);
277
299
  if (!resolved.ok) return resolved;
278
300
 
279
- try {
280
- const validationError = await this.validateDslQuery(idOrName, table, dslQuery);
281
- if (validationError) return { ok: false, error: validationError };
282
-
283
- const needsJsAgg = hasJsAggregates(dslQuery);
284
- const needsWindows = hasWindowFunctions(dslQuery);
285
-
286
- if (needsJsAgg && needsWindows) {
287
- return executeJsAggregationWithWindows(resolved.source, table, dslQuery, 'sqlite');
288
- }
289
- if (needsJsAgg) {
290
- return executeJsAggregation(resolved.source, table, dslQuery, 'sqlite');
291
- }
301
+ const cappedSql = wrapWithLimit(sql, Math.min(maxRows, MAX_RESULT_ROWS));
292
302
 
293
- // Pure SQL path — compileDsl handles CTE wrapping for window functions
294
- const sql = compileDsl(table, dslQuery, 'sqlite');
295
- const result = await resolved.source.executeQuery(sql);
303
+ try {
304
+ const result = await resolved.source.executeQuery(cappedSql);
296
305
  const errorMsg = hasErrorRow(result);
297
- if (errorMsg) return { ok: false, error: errorMsg };
306
+ if (errorMsg) {
307
+ const enriched = await this.enrichSqlError(idOrName, errorMsg);
308
+ return { ok: false, error: enriched };
309
+ }
298
310
 
299
311
  return {
300
312
  ok: true,
301
313
  rows: result.rows,
302
314
  columns: result.columns,
303
315
  totalRows: result.rows.length,
304
- truncated: false,
316
+ truncated: result.rows.length >= Math.min(maxRows, MAX_RESULT_ROWS),
305
317
  };
306
318
  } catch (err: any) {
307
- return { ok: false, error: `DSL query failed: ${err.message}` };
319
+ const enriched = await this.enrichSqlError(idOrName, err.message);
320
+ return { ok: false, error: `SQL query failed: ${enriched}` };
308
321
  }
309
322
  }
310
323
 
311
324
  /**
312
- * Validate a DSL query against the source schema. Returns an error message
313
- * if validation fails, or null if the query is valid.
325
+ * Enrich SQLite error messages with available table/column info.
314
326
  */
315
- private async validateDslQuery(
316
- idOrName: string,
317
- table: string,
318
- dslQuery: DslQuery
319
- ): Promise<string | null> {
320
- const schemaResult = await this.getSchema(idOrName);
321
- if (!schemaResult.ok || !schemaResult.schema) return null;
327
+ private async enrichSqlError(idOrName: string, errorMsg: string): Promise<string> {
328
+ try {
329
+ const schemaResult = await this.getSchema(idOrName);
330
+ if (!schemaResult.ok || !schemaResult.schema) return errorMsg;
322
331
 
323
- const schema = schemaResult.schema;
332
+ const schema = schemaResult.schema;
324
333
 
325
- if (dslQuery.join && dslQuery.join.length > 0) {
326
- const validation = validateDslWithJoins(schema, table, dslQuery);
327
- return validation.ok ? null : validation.error ?? 'Validation failed';
328
- }
334
+ if (/no such column/i.test(errorMsg)) {
335
+ const allCols = schema.tables.flatMap(t => t.columns.map(c => c.name));
336
+ const unique = [...new Set(allCols)];
337
+ return `${errorMsg}. Available columns: ${unique.join(', ')}`;
338
+ }
329
339
 
330
- const tableSchema = schema.tables.find(t => t.name === table);
331
- if (!tableSchema) {
332
- const available = schema.tables.map(t => t.name).join(', ');
333
- return `Table "${table}" not found. Available: ${available}`;
334
- }
340
+ if (/no such table/i.test(errorMsg)) {
341
+ const tables = schema.tables.map(t => t.name);
342
+ return `${errorMsg}. Available tables: ${tables.join(', ')}`;
343
+ }
335
344
 
336
- const validation = validateDsl(tableSchema, dslQuery);
337
- return validation.ok ? null : validation.error ?? 'Validation failed';
345
+ if (/no such function/i.test(errorMsg)) {
346
+ return `${errorMsg}. Available aggregate functions: SUM, AVG, MIN, MAX, COUNT, MEDIAN, STDDEV, P25, P75, P10, P90. Window functions: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, etc.`;
347
+ }
348
+ } catch {
349
+ // Schema lookup failed — return original error
350
+ }
351
+ return errorMsg;
338
352
  }
339
353
 
340
354
  // ─── Cross-Source ──────────────────────────────────────────────────────────
@@ -29,6 +29,10 @@ export interface ConnectedSource {
29
29
  executeQuery(sql: string): Promise<QueryExecutionResult>;
30
30
  /** Get sample rows from a table, picked for variety. */
31
31
  getSampleRows(tableName: string, count?: number): Promise<Record<string, any>[]>;
32
+ /** Get the underlying database handle (only available for SQL-backed connectors). */
33
+ getDatabase?(): any;
34
+ /** Invalidate cached schema so the next getSchema() rebuilds from the live database. */
35
+ invalidateSchema?(): void;
32
36
  /** Close the connection and free resources. */
33
37
  close(): Promise<void>;
34
38
  }
package/src/index.ts CHANGED
@@ -42,26 +42,11 @@ export type {
42
42
  TableColumn,
43
43
  CompoundLayout,
44
44
  Interaction,
45
- DslJoin,
46
- DslQuery,
47
- DslSelectField,
48
- DslAggregateField,
49
- DslWindowFunction,
50
- DslWindowField,
51
- DslGroupByField,
52
- DslFilter,
53
- DslFilterOp,
54
- DslOrderBy,
55
- DslAggregate,
56
- SourceDataRef,
57
- DashboardSpec,
58
- DashboardViewSpec,
59
- DashboardFilter,
60
- DashboardLayout,
61
- DashboardInteraction,
45
+ RowFilter,
46
+ RowFilterOp,
62
47
  } from './types.js';
63
48
 
64
- export { isCompoundSpec, isDashboardSpec, isDslAggregateField, isDslWindowField } from './types.js';
49
+ export { isCompoundSpec } from './types.js';
65
50
 
66
51
  // ─── PATTERNS ────────────────────────────────────────────────────────────────
67
52
 
@@ -125,6 +110,4 @@ export {
125
110
  } from './renderers/html/index.js';
126
111
 
127
112
  export { buildCompoundHtml } from './renderers/html/builders/compound.js';
128
- export { buildDashboardHtml } from './renderers/html/builders/dashboard.js';
129
- export type { DashboardViewData } from './renderers/html/builders/dashboard.js';
130
113
  export { shouldCompound, buildCompoundSpec } from './renderers/html/compound.js';
@@ -193,9 +193,8 @@ html, body {
193
193
  root.style.display = 'block';
194
194
  root.innerHTML = '';
195
195
 
196
- var isDashboard = html.indexOf('dashboard-grid') !== -1;
197
196
  var isCompound = html.indexOf('compound-container') !== -1;
198
- var initialHeight = isDashboard ? 900 : isCompound ? 700 : DEFAULT_HEIGHT;
197
+ var initialHeight = isCompound ? 700 : DEFAULT_HEIGHT;
199
198
 
200
199
  var iframe = document.createElement('iframe');
201
200
  iframe.id = 'chart-frame';
package/src/mcp/index.ts CHANGED
@@ -5,23 +5,24 @@
5
5
  * An MCP server that provides visualization intelligence from a handcrafted
6
6
  * pattern library that goes far beyond bar/line/pie.
7
7
  *
8
- * 17 tools:
9
- * visualize — Inline data + intent → ranked visualization recommendations
10
- * visualize_data — CSV data (DSL query) + intent → ranked visualization recommendations
8
+ * 18 tools:
9
+ * visualize — Data (inline, cached, or CSV+SQL) + intent → ranked visualization recommendations
11
10
  * list_patterns — Browse all available visualization patterns
12
11
  * refine_visualization — Tweak a visualization spec
13
- * create_dashboard — Multi-view dashboard from a CSV dataset
14
- * refine_dashboard — Iterate on a dashboard (add/remove views, layout, filters, theme)
15
12
  * load_csv — Load a CSV file or directory
16
13
  * list_data — List loaded datasets
17
14
  * remove_data — Remove a loaded dataset
18
15
  * describe_data — Re-examine column profiles and sample rows for a dataset
19
- * analyze_data — Generate a structured analysis plan with DSL queries
20
- * query_data — Run a declarative DSL query and see tabular results
16
+ * analyze_data — Generate a structured analysis plan with SQL queries
17
+ * query_data — Run a declarative SQL query and see tabular results
21
18
  * server_status — Inspect cached data in server memory
22
19
  * clear_cache — Clear cached specs, results, and sessions
23
20
  * export_html — Get the full rendered HTML for a visualization by specId
24
21
  * screenshot — Render a visualization to PNG via headless Chromium
22
+ * transform_data — Create derived columns with the expression language
23
+ * promote_columns — Promote working columns to derived (persisted)
24
+ * list_transforms — List columns by layer (source/derived/working)
25
+ * drop_columns — Drop derived or working columns
25
26
  * report_bug — Generate a sanitized bug report for GitHub issues
26
27
  */
27
28
 
@@ -34,7 +35,6 @@ import {
34
35
  } from '@modelcontextprotocol/ext-apps/server';
35
36
 
36
37
  import { visualizeInputSchema, handleVisualize } from './tools/visualize.js';
37
- import { visualizeFromSourceInputSchema, handleVisualizeFromSource } from './tools/visualize-from-source.js';
38
38
  import { handleListPatterns } from './tools/list-patterns.js';
39
39
  import { refineInputSchema, handleRefine } from './tools/refine.js';
40
40
  import {
@@ -48,8 +48,6 @@ import {
48
48
  } from './tools/sources.js';
49
49
  import { analyzeSourceInputSchema, handleAnalyzeSource } from './tools/analyze.js';
50
50
  import { querySourceInputSchema, handleQuerySource } from './tools/query-source.js';
51
- import { createDashboardInputSchema, handleCreateDashboard } from './tools/dashboard.js';
52
- import { refineDashboardInputSchema, handleRefineDashboard } from './tools/dashboard-refine.js';
53
51
  import {
54
52
  clearCacheInputSchema,
55
53
  handleServerStatus,
@@ -58,6 +56,17 @@ import {
58
56
  import { bugReportInputSchema, handleReportBug } from './tools/bug-report.js';
59
57
  import { exportHtmlInputSchema, handleExportHtml } from './tools/export-html.js';
60
58
  import { screenshotInputSchema, handleScreenshot, closeBrowser } from './tools/screenshot.js';
59
+ import {
60
+ transformDataBaseSchema,
61
+ transformDataSchema,
62
+ promoteColumnsSchema,
63
+ listTransformsSchema,
64
+ dropColumnsSchema,
65
+ } from './tools/transform-schemas.js';
66
+ import { handleTransformData } from './tools/transform-data.js';
67
+ import { handlePromoteColumns } from './tools/promote-columns.js';
68
+ import { handleListTransforms } from './tools/list-transforms.js';
69
+ import { handleDropColumns } from './tools/drop-columns.js';
61
70
  import { specStore } from './spec-store.js';
62
71
  import { registerPrompts } from './prompts.js';
63
72
 
@@ -105,28 +114,23 @@ const server = new McpServer(
105
114
  'WORKFLOW:',
106
115
  '• Got a CSV file? → load_csv(name, path) immediately, don\'t verify — this server runs locally on the user\'s machine',
107
116
  '• Got inline data? → visualize(data, intent) directly',
108
- '• Need to explore? → load_csv → analyze_data → visualize_data per step',
109
- '• Need a dashboard? → load_csv → create_dashboard with views array',
117
+ '• Need to explore? → load_csv → analyze_data → visualize(sourceId, sql, intent) per step',
110
118
  '',
111
119
  'CONTINUATION (dataset already loaded):',
112
- '• Chart from data → visualize_data(sourceId, table, query, intent)',
120
+ '• Chart from data → visualize(sourceId, sql, intent)',
113
121
  '• Want to SEE rows (answer a question, validate data, show a table)? → query_data',
114
122
  '• Want to CHART rows you already queried? → visualize(resultId=...) to reuse cached data',
115
123
  '• Want a table view? → query_data for raw data, or visualize with includeDataTable=true for a formatted table with chart',
116
124
  '• Tweak a chart → refine_visualization(specId, ...) — always use the MOST RECENT specId',
117
- '• Tweak a dashboard → refine_dashboard(currentSpec, refinement)',
118
- '• specId expired? → re-run the original visualize/visualize_data call, then continue refining from the new specId',
125
+ '• specId expired? → re-run the original visualize call, then continue refining from the new specId',
119
126
  '',
120
127
  'TOOL GUIDE:',
121
128
  '• load_csv: Load a CSV file or directory. Returns sourceId.',
122
129
  '• describe_data: See schema, stats, samples. Use detail="compact" for large schemas.',
123
- '• analyze_data: Auto-generate analysis plan with ready DSL queries. Execute each step with visualize_data; present results one at a time.',
124
- '• query_data: Run DSL query, get rows. Returns resultId for visualize().',
125
- '• visualize: Chart from inline data OR resultId from query_data. Auto-selects best pattern. Set title/subtitle here to avoid a refine round-trip.',
126
- '• visualize_data: Chart from loaded CSV + DSL query. Same as visualize but queries server-side — saves tokens.',
130
+ '• analyze_data: Auto-generate analysis plan with ready SQL queries. Execute each step with visualize; present results one at a time.',
131
+ '• query_data: Run SQL query, get rows. Returns resultId for visualize().',
132
+ '• visualize: Chart data. Pass inline data array, resultId from query_data, or sourceId + sql for server-side query. Auto-selects best pattern. Set title/subtitle here to avoid a refine round-trip.',
127
133
  '• refine_visualization: Tweak a chart — sort, limit, filter, palette, highlight, flip, title, format. Each call returns a new specId.',
128
- '• create_dashboard: Multi-chart layout from loaded data with per-view queries.',
129
- '• refine_dashboard: Iterate dashboard — add/remove views, filters, layout, theme.',
130
134
  '• list_patterns: Browse available chart types. Only needed when the user asks what charts are available or you need a pattern ID.',
131
135
  '',
132
136
  'Utility tools: list_data, remove_data, server_status (inspect cached data), clear_cache, report_bug (generate GitHub issue), export_html (get chart HTML by specId), screenshot (render to PNG).',
@@ -134,7 +138,7 @@ const server = new McpServer(
134
138
  'COLOR: Set palette (categorical/blue/warm/blueRed/etc.) and/or highlight specific values. Use colorField to control which column drives color.',
135
139
  'PATTERNS: 43 types auto-selected by data shape + intent. When user names a specific chart type, pass pattern="<id>" to force it. Use list_patterns to browse.',
136
140
  '',
137
- 'ERRORS: If a DSL query fails with field name suggestions, retry with the corrected name. If specId is expired, re-run visualize.',
141
+ 'ERRORS: If a SQL query fails, check the error message for available columns/tables and retry. If specId is expired, re-run visualize.',
138
142
  '',
139
143
  'DON\'T use Dolex for: simple arithmetic, explanations of chart types, non-data questions, or file format conversions (CSV export, PowerPoint, etc.).',
140
144
  'DO use Dolex when the user asks "what chart should I use" — run visualize and let the pattern selector recommend.',
@@ -172,7 +176,7 @@ registerAppTool(
172
176
  'visualize',
173
177
  {
174
178
  title: 'Visualize Data',
175
- description: 'Chart inline data or cached query results. Pass data array + intent, OR resultId from query_data.\n\nWhen to use: You have data in the conversation (pasted, generated, or from query_data resultId). Use visualize_data instead when data lives in a loaded CSV — saves tokens.\n\nKey params: pattern (force a specific chart type), palette, highlight, colorField, title, subtitle.\n\nResponse: specId (use in refine calls — always use the most recent one), recommended pattern + reasoning, alternatives, data shape summary. Chart HTML in structuredContent. If the response includes notes, present each note to the user — they explain decisions the system made automatically.',
179
+ description: 'Chart data from inline arrays, cached query results, or loaded CSVs.\n\nData source (provide one):\n• data: inline rows\n• resultId: reuse query_data result\n• sourceId + sql: query a loaded CSV server-side (saves tokens)\n\nReturns specId (for refine calls), pattern recommendation, alternatives, chart HTML.\nPresent any notes to the user.',
176
180
  inputSchema: visualizeInputSchema.shape,
177
181
  _meta: {
178
182
  ui: {
@@ -183,34 +187,14 @@ registerAppTool(
183
187
  },
184
188
  },
185
189
  },
186
- handleVisualize(selectPatternCallback),
187
- );
188
-
189
- // CSV data visualization tool
190
- registerAppTool(
191
- server,
192
- 'visualize_data',
193
- {
194
- title: 'Visualize Data',
195
- description: 'Chart data from a loaded CSV. Queries server-side — no data in the context window.\n\nWhen to use: CSV already loaded via load_csv. Prefer this over query_data + visualize for one-step charting.\n\nKey params: sourceId, table, query (DSL: { select, groupBy, filter, orderBy, limit }), intent, pattern, palette, highlight, colorField.\n\nResponse: Same as visualize — specId, pattern, alternatives, chart HTML.',
196
- inputSchema: visualizeFromSourceInputSchema.shape,
197
- _meta: {
198
- ui: {
199
- resourceUri: CHART_RESOURCE_URI,
200
- csp: {
201
- resourceDomains: ['https://d3js.org', 'https://cdn.jsdelivr.net'],
202
- },
203
- },
204
- },
205
- },
206
- handleVisualizeFromSource(selectPatternCallback, { sourceManager }),
190
+ handleVisualize(selectPatternCallback, { sourceManager }),
207
191
  );
208
192
 
209
193
  server.registerTool(
210
194
  'list_patterns',
211
195
  {
212
196
  title: 'List Visualization Patterns',
213
- description: 'Browse all 43 chart types with data requirements, capabilities, and examples. Returns per-pattern color encoding support and config options.\n\nWhen to use: User asks what charts are available, or you need to look up a pattern ID for the pattern parameter.',
197
+ description: 'Browse all 43 chart types with data requirements, capabilities, and config options.',
214
198
  },
215
199
  handleListPatterns(() => registry.getAll()),
216
200
  );
@@ -220,7 +204,7 @@ registerAppTool(
220
204
  'refine_visualization',
221
205
  {
222
206
  title: 'Refine Visualization',
223
- description: 'Tweak a chart using structured parameters. Pass specId from a previous visualize or refine call.\n\nAlways use the most recent specId — each refine returns a new one that includes all previous changes. If the response includes notes, present each note to the user.\n\nParameters (all optional except specId):\n• sort: { direction: "asc"|"desc", field?: "column_name" } — if field omitted, sorts by primary measure axis\n• limit: number (top N rows)\n• filter: [{ field: "col", op: "in"|"not_in"|"gt"|"gte"|"lt"|"lte", values: [...] }] — pass [] to clear filters\n• flip: true (swap axes — Cartesian charts only)\n• title / subtitle / xLabel / yLabel: strings\n• palette: "categorical"|"blue"|"warm"|"blueRed"|"green"|"purple"|"greenPurple"|"tealOrange"|"redGreen"|"traffic-light"|"profit-loss"|"temperature"\n• highlight: { values: ["val1", "val2"], color?: "css-color", mutedOpacity?: 0.3 } — pass null to clear\n• colorField: "column_name" (which field drives color)\n• flowColorBy: "source"|"target" (alluvial charts only)\n• format: "percent"|"dollar"|"integer"|"decimal"|"compact"\n• switchPattern: "pattern-id" (switch chart type)\n\nCompound chart params: removeTable, layout ("rows"|"columns"), hideColumns (array of column names to hide from data table).\n\nReturns new specId + changes applied + available alternatives.',
207
+ description: 'Tweak a chart. Pass the most recent specId — each call returns a new one.\nSort, limit, filter, flip, titles, labels, palette, highlight, colorField, switchPattern, format.\nCompound: removeTable, layout, hideColumns.\nReturns new specId + changes applied. Present any notes to the user.',
224
208
  inputSchema: refineInputSchema.shape,
225
209
  _meta: {
226
210
  ui: {
@@ -239,7 +223,7 @@ server.registerTool(
239
223
  'load_csv',
240
224
  {
241
225
  title: 'Load CSV Data',
242
- description: 'Load a CSV file or directory of CSV files. Call this immediately with any user-provided path — this server runs locally on the user\'s machine.\n\nDatasets persist across restarts.\n\nKey params: detail="compact" for just column names/types (saves tokens), detail="full" for stats + samples (default).\n\nReturns sourceId (use in all subsequent data operations).',
226
+ description: 'Load a CSV file or directory. Datasets persist across restarts. Returns sourceId.\nUse detail="compact" for column names/types only (saves tokens).',
243
227
  inputSchema: addSourceInputSchema,
244
228
  },
245
229
  handleAddSource({ sourceManager }),
@@ -268,7 +252,7 @@ server.registerTool(
268
252
  'describe_data',
269
253
  {
270
254
  title: 'Describe Data',
271
- description: 'Examine column profiles for a loaded dataset. Use to re-inspect data mid-conversation.\n\nKey params: detail="compact" for column names/types only (saves tokens), detail="full" for stats + samples (default).',
255
+ description: 'Column profiles for a loaded dataset. Use detail="compact" for names/types only.',
272
256
  inputSchema: describeSourceInputSchema,
273
257
  },
274
258
  handleDescribeSource({ sourceManager }),
@@ -278,7 +262,7 @@ server.registerTool(
278
262
  'analyze_data',
279
263
  {
280
264
  title: 'Analyze Data',
281
- description: 'Auto-generate a structured analysis plan with ready-to-execute DSL queries. Returns 4-6 analysis steps covering trends, comparisons, distributions, and relationships.\n\nWhen to use: After load_csv, to get an automatic data exploration plan. Execute each step with visualize_data and present results one at a time.',
265
+ description: 'Auto-generate an analysis plan with ready-to-execute SQL queries. Returns 4-6 steps covering trends, comparisons, distributions, and relationships.',
282
266
  inputSchema: analyzeSourceInputSchema.shape,
283
267
  },
284
268
  handleAnalyzeSource({ sourceManager }),
@@ -288,49 +272,51 @@ server.registerTool(
288
272
  'query_data',
289
273
  {
290
274
  title: 'Query Data',
291
- description: 'Run a DSL query and get tabular results. Returns resultId — pass to visualize(resultId=...) to chart the same data without re-sending rows.\n\nWhen to use: Need to see raw data, answer a data question, or validate before charting. For one-step charting, use visualize_data instead.\n\nKey params: sourceId, table, query (DSL: { select, groupBy, filter, join, orderBy, limit }).',
275
+ description: 'Run a SQL query on a loaded dataset. JOINs, GROUP BY, window functions, CTEs.\nCustom aggregates: MEDIAN, STDDEV, P25, P75, P10, P90.\nReturns resultId for visualize().',
292
276
  inputSchema: querySourceInputSchema,
293
277
  },
294
278
  handleQuerySource({ sourceManager }),
295
279
  );
296
280
 
297
- // Dashboard tools
298
- registerAppTool(
299
- server,
300
- 'create_dashboard',
281
+ // Derived data layer tools
282
+ server.registerTool(
283
+ 'transform_data',
301
284
  {
302
- title: 'Create Dashboard',
303
- description: 'Create a multi-view dashboard from a loaded CSV dataset. Each view has its own DSL query and intent.\n\nKey params: sourceId, table, views (array with id, title, intent, query per view), layout, filters.\n\nReturns DashboardSpec (pass to refine_dashboard for iterations) + rendered HTML.',
304
- inputSchema: createDashboardInputSchema.shape,
305
- _meta: {
306
- ui: {
307
- resourceUri: CHART_RESOURCE_URI,
308
- csp: {
309
- resourceDomains: ['https://d3js.org', 'https://cdn.jsdelivr.net'],
310
- },
311
- },
312
- },
285
+ title: 'Transform Data',
286
+ description: 'Create derived columns using expressions. Single-column mode: create + expr. Batch mode: transforms array.\n\nExpressions: arithmetic (score * 2), functions (log, zscore, if_else), column-wise stats (col_mean, rank), string/date ops.\n\nColumns start as "working" (session-only). Use promote_columns to persist them.\n\nExamples:\n• create: "doubled", expr: "score * 2"\n• create: "grade", expr: "if_else(score > 90, \\"A\\", if_else(score > 80, \\"B\\", \\"C\\"))"\n• create: "z_score", expr: "zscore(score)", partitionBy: "group"\n• transforms: [{ create: "a", expr: "x + 1" }, { create: "b", expr: "a * 2" }]',
287
+ inputSchema: transformDataBaseSchema.shape,
313
288
  },
314
- handleCreateDashboard({ sourceManager }),
289
+ handleTransformData({ sourceManager }),
315
290
  );
316
291
 
317
- registerAppTool(
318
- server,
319
- 'refine_dashboard',
292
+ server.registerTool(
293
+ 'promote_columns',
320
294
  {
321
- title: 'Refine Dashboard',
322
- description: 'Iterate on a dashboard using natural language. Pass currentSpec from create_dashboard or previous refine.\n\nUnlike refine_visualization which uses structured parameters, this tool accepts natural language descriptions of changes.\n\nExamples: "add a chart showing revenue by month", "remove the bar chart", "3 columns", "add region filter", "dark mode".\n\nReturns updated DashboardSpec + rendered HTML.',
323
- inputSchema: refineDashboardInputSchema.shape,
324
- _meta: {
325
- ui: {
326
- resourceUri: CHART_RESOURCE_URI,
327
- csp: {
328
- resourceDomains: ['https://d3js.org', 'https://cdn.jsdelivr.net'],
329
- },
330
- },
331
- },
295
+ title: 'Promote Columns',
296
+ description: 'Promote working columns to derived (persisted). Derived columns are saved to .dolex.json and automatically restored when the CSV is reloaded.\n\nUse ["*"] to promote all working columns.',
297
+ inputSchema: promoteColumnsSchema.shape,
298
+ },
299
+ handlePromoteColumns({ sourceManager }),
300
+ );
301
+
302
+ server.registerTool(
303
+ 'list_transforms',
304
+ {
305
+ title: 'List Transforms',
306
+ description: 'List all columns for a table grouped by layer: source (original CSV), derived (persisted), working (session-only). Shows expressions and types for derived/working columns.',
307
+ inputSchema: listTransformsSchema.shape,
308
+ },
309
+ handleListTransforms({ sourceManager }),
310
+ );
311
+
312
+ server.registerTool(
313
+ 'drop_columns',
314
+ {
315
+ title: 'Drop Columns',
316
+ description: 'Drop derived or working columns. For derived columns, validates no other columns depend on it. For working columns shadowing a derived column, restores the derived values.\n\nUse ["*"] with layer to drop all columns in a layer.',
317
+ inputSchema: dropColumnsSchema.shape,
332
318
  },
333
- handleRefineDashboard({ sourceManager }),
319
+ handleDropColumns({ sourceManager }),
334
320
  );
335
321
 
336
322
  // Privacy / cache management tools
@@ -340,7 +326,7 @@ server.registerTool(
340
326
  'server_status',
341
327
  {
342
328
  title: 'Server Status',
343
- description: 'Inspect cached data in server memory: specs with row counts, query results, connected sources, uptime. Use before clear_cache.',
329
+ description: 'Inspect cached specs, query results, connected sources, and uptime.',
344
330
  },
345
331
  handleServerStatus(privacyDeps),
346
332
  );
@@ -22,7 +22,7 @@ export function registerPrompts(server: McpServer) {
22
22
  'Please:',
23
23
  '1. Load it using load_csv',
24
24
  '2. Call analyze_data to get an automatic analysis plan',
25
- '3. For each step in the plan, call visualize_data with the provided query and use one of the suggested patterns',
25
+ '3. For each step in the plan, call visualize with sourceId, sql, and intent using one of the suggested patterns',
26
26
  '4. After each chart, write a 2-3 sentence finding explaining what the data reveals — be specific about numbers, trends, and outliers',
27
27
  '5. End with a "Key Takeaways" summary',
28
28
  '',