@outsidedata/dolex 0.1.13 → 1.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 (215) hide show
  1. package/README.md +8 -8
  2. package/dist/src/analysis/rules.d.ts.map +1 -1
  3. package/dist/src/analysis/rules.js +8 -2
  4. package/dist/src/analysis/rules.js.map +1 -1
  5. package/dist/src/connectors/csv.d.ts.map +1 -1
  6. package/dist/src/connectors/csv.js +31 -1
  7. package/dist/src/connectors/csv.js.map +1 -1
  8. package/dist/src/connectors/dsl-compiler.d.ts +7 -6
  9. package/dist/src/connectors/dsl-compiler.d.ts.map +1 -1
  10. package/dist/src/connectors/dsl-compiler.js +72 -79
  11. package/dist/src/connectors/dsl-compiler.js.map +1 -1
  12. package/dist/src/connectors/dsl-validator.js +6 -1
  13. package/dist/src/connectors/dsl-validator.js.map +1 -1
  14. package/dist/src/connectors/index.d.ts +0 -3
  15. package/dist/src/connectors/index.d.ts.map +1 -1
  16. package/dist/src/connectors/index.js +0 -3
  17. package/dist/src/connectors/index.js.map +1 -1
  18. package/dist/src/connectors/js-aggregation.d.ts +4 -4
  19. package/dist/src/connectors/js-aggregation.d.ts.map +1 -1
  20. package/dist/src/connectors/js-aggregation.js +22 -16
  21. package/dist/src/connectors/js-aggregation.js.map +1 -1
  22. package/dist/src/connectors/manager.d.ts.map +1 -1
  23. package/dist/src/connectors/manager.js +4 -21
  24. package/dist/src/connectors/manager.js.map +1 -1
  25. package/dist/src/mcp/app-shell.js +1 -1
  26. package/dist/src/mcp/index.d.ts +8 -8
  27. package/dist/src/mcp/index.js +87 -53
  28. package/dist/src/mcp/index.js.map +1 -1
  29. package/dist/src/mcp/prompts.js +4 -4
  30. package/dist/src/mcp/prompts.js.map +1 -1
  31. package/dist/src/mcp/spec-store.d.ts +2 -1
  32. package/dist/src/mcp/spec-store.d.ts.map +1 -1
  33. package/dist/src/mcp/spec-store.js +4 -2
  34. package/dist/src/mcp/spec-store.js.map +1 -1
  35. package/dist/src/mcp/tools/analyze.d.ts +1 -1
  36. package/dist/src/mcp/tools/analyze.js +2 -2
  37. package/dist/src/mcp/tools/analyze.js.map +1 -1
  38. package/dist/src/mcp/tools/bug-report.d.ts.map +1 -1
  39. package/dist/src/mcp/tools/bug-report.js +2 -10
  40. package/dist/src/mcp/tools/bug-report.js.map +1 -1
  41. package/dist/src/mcp/tools/dashboard.js +1 -1
  42. package/dist/src/mcp/tools/dashboard.js.map +1 -1
  43. package/dist/src/mcp/tools/dsl-schemas.d.ts +53 -52
  44. package/dist/src/mcp/tools/dsl-schemas.d.ts.map +1 -1
  45. package/dist/src/mcp/tools/dsl-schemas.js +3 -3
  46. package/dist/src/mcp/tools/dsl-schemas.js.map +1 -1
  47. package/dist/src/mcp/tools/export-html.d.ts +1 -1
  48. package/dist/src/mcp/tools/export-html.js +2 -2
  49. package/dist/src/mcp/tools/export-html.js.map +1 -1
  50. package/dist/src/mcp/tools/list-patterns.js +2 -2
  51. package/dist/src/mcp/tools/list-patterns.js.map +1 -1
  52. package/dist/src/mcp/tools/query-source.d.ts +17 -17
  53. package/dist/src/mcp/tools/query-source.js +4 -4
  54. package/dist/src/mcp/tools/query-source.js.map +1 -1
  55. package/dist/src/mcp/tools/refine.d.ts +124 -15
  56. package/dist/src/mcp/tools/refine.d.ts.map +1 -1
  57. package/dist/src/mcp/tools/refine.js +335 -253
  58. package/dist/src/mcp/tools/refine.js.map +1 -1
  59. package/dist/src/mcp/tools/result-cache.d.ts +1 -1
  60. package/dist/src/mcp/tools/result-cache.js +1 -1
  61. package/dist/src/mcp/tools/screenshot.js +1 -1
  62. package/dist/src/mcp/tools/screenshot.js.map +1 -1
  63. package/dist/src/mcp/tools/server-privacy.d.ts.map +1 -1
  64. package/dist/src/mcp/tools/server-privacy.js +6 -7
  65. package/dist/src/mcp/tools/server-privacy.js.map +1 -1
  66. package/dist/src/mcp/tools/shared.d.ts +15 -2
  67. package/dist/src/mcp/tools/shared.d.ts.map +1 -1
  68. package/dist/src/mcp/tools/shared.js +64 -6
  69. package/dist/src/mcp/tools/shared.js.map +1 -1
  70. package/dist/src/mcp/tools/sources.d.ts +5 -113
  71. package/dist/src/mcp/tools/sources.d.ts.map +1 -1
  72. package/dist/src/mcp/tools/sources.js +15 -44
  73. package/dist/src/mcp/tools/sources.js.map +1 -1
  74. package/dist/src/mcp/tools/visualize-from-source.d.ts +53 -77
  75. package/dist/src/mcp/tools/visualize-from-source.d.ts.map +1 -1
  76. package/dist/src/mcp/tools/visualize-from-source.js +24 -9
  77. package/dist/src/mcp/tools/visualize-from-source.js.map +1 -1
  78. package/dist/src/mcp/tools/visualize.d.ts +47 -102
  79. package/dist/src/mcp/tools/visualize.d.ts.map +1 -1
  80. package/dist/src/mcp/tools/visualize.js +24 -24
  81. package/dist/src/mcp/tools/visualize.js.map +1 -1
  82. package/dist/src/patterns/definitions/comparison/grouped-bar.js +5 -5
  83. package/dist/src/patterns/definitions/comparison/grouped-bar.js.map +1 -1
  84. package/dist/src/patterns/definitions/composition/waffle.d.ts.map +1 -1
  85. package/dist/src/patterns/definitions/composition/waffle.js +17 -3
  86. package/dist/src/patterns/definitions/composition/waffle.js.map +1 -1
  87. package/dist/src/patterns/definitions/distribution/strip-plot.d.ts.map +1 -1
  88. package/dist/src/patterns/definitions/distribution/strip-plot.js +12 -3
  89. package/dist/src/patterns/definitions/distribution/strip-plot.js.map +1 -1
  90. package/dist/src/patterns/definitions/time/sparkline-grid.js +2 -2
  91. package/dist/src/patterns/definitions/time/sparkline-grid.js.map +1 -1
  92. package/dist/src/patterns/selector.d.ts.map +1 -1
  93. package/dist/src/patterns/selector.js +46 -1
  94. package/dist/src/patterns/selector.js.map +1 -1
  95. package/dist/src/renderers/d3/comparison/bar.d.ts.map +1 -1
  96. package/dist/src/renderers/d3/comparison/bar.js +24 -1
  97. package/dist/src/renderers/d3/comparison/bar.js.map +1 -1
  98. package/dist/src/renderers/d3/comparison/grouped-bar.d.ts.map +1 -1
  99. package/dist/src/renderers/d3/comparison/grouped-bar.js +9 -4
  100. package/dist/src/renderers/d3/comparison/grouped-bar.js.map +1 -1
  101. package/dist/src/renderers/d3/composition/donut.d.ts.map +1 -1
  102. package/dist/src/renderers/d3/composition/donut.js +12 -0
  103. package/dist/src/renderers/d3/composition/donut.js.map +1 -1
  104. package/dist/src/renderers/d3/composition/stacked-bar.d.ts.map +1 -1
  105. package/dist/src/renderers/d3/composition/stacked-bar.js +4 -0
  106. package/dist/src/renderers/d3/composition/stacked-bar.js.map +1 -1
  107. package/dist/src/renderers/d3/composition/treemap.js +2 -1
  108. package/dist/src/renderers/d3/composition/treemap.js.map +1 -1
  109. package/dist/src/renderers/d3/distribution/beeswarm.d.ts.map +1 -1
  110. package/dist/src/renderers/d3/distribution/beeswarm.js +8 -0
  111. package/dist/src/renderers/d3/distribution/beeswarm.js.map +1 -1
  112. package/dist/src/renderers/d3/distribution/histogram.js +36 -2
  113. package/dist/src/renderers/d3/distribution/histogram.js.map +1 -1
  114. package/dist/src/renderers/d3/flow/funnel.d.ts.map +1 -1
  115. package/dist/src/renderers/d3/flow/funnel.js +4 -0
  116. package/dist/src/renderers/d3/flow/funnel.js.map +1 -1
  117. package/dist/src/renderers/d3/flow/sankey-layout.js +20 -3
  118. package/dist/src/renderers/d3/flow/sankey-layout.js.map +1 -1
  119. package/dist/src/renderers/d3/heatmap.d.ts.map +1 -1
  120. package/dist/src/renderers/d3/heatmap.js +18 -3
  121. package/dist/src/renderers/d3/heatmap.js.map +1 -1
  122. package/dist/src/renderers/d3/radar.d.ts.map +1 -1
  123. package/dist/src/renderers/d3/radar.js +3 -1
  124. package/dist/src/renderers/d3/radar.js.map +1 -1
  125. package/dist/src/renderers/d3/relationship.d.ts.map +1 -1
  126. package/dist/src/renderers/d3/relationship.js +29 -7
  127. package/dist/src/renderers/d3/relationship.js.map +1 -1
  128. package/dist/src/renderers/d3/shared.js +7 -7
  129. package/dist/src/renderers/d3/shared.js.map +1 -1
  130. package/dist/src/renderers/d3/time/area.js +21 -7
  131. package/dist/src/renderers/d3/time/area.js.map +1 -1
  132. package/dist/src/renderers/d3/time/calendar-heatmap.js +6 -0
  133. package/dist/src/renderers/d3/time/calendar-heatmap.js.map +1 -1
  134. package/dist/src/renderers/d3/time/horizon-chart.d.ts.map +1 -1
  135. package/dist/src/renderers/d3/time/horizon-chart.js +10 -0
  136. package/dist/src/renderers/d3/time/horizon-chart.js.map +1 -1
  137. package/dist/src/renderers/d3/time/line.d.ts.map +1 -1
  138. package/dist/src/renderers/d3/time/line.js +27 -7
  139. package/dist/src/renderers/d3/time/line.js.map +1 -1
  140. package/dist/src/renderers/d3/time/small-multiples.js +8 -0
  141. package/dist/src/renderers/d3/time/small-multiples.js.map +1 -1
  142. package/dist/src/renderers/d3/time/sparkline-grid.d.ts.map +1 -1
  143. package/dist/src/renderers/d3/time/sparkline-grid.js +5 -2
  144. package/dist/src/renderers/d3/time/sparkline-grid.js.map +1 -1
  145. package/dist/src/renderers/d3/time/stream-graph.js +6 -0
  146. package/dist/src/renderers/d3/time/stream-graph.js.map +1 -1
  147. package/dist/src/renderers/html/_generated/bundles.d.ts +39 -39
  148. package/dist/src/renderers/html/_generated/bundles.d.ts.map +1 -1
  149. package/dist/src/renderers/html/_generated/bundles.js +39 -39
  150. package/dist/src/renderers/html/_generated/bundles.js.map +1 -1
  151. package/dist/src/renderers/html/builders/dashboard.js +2 -2
  152. package/dist/src/renderers/html/template.js +2 -2
  153. package/dist/src/renderers/html/template.js.map +1 -1
  154. package/dist/src/types.d.ts +33 -26
  155. package/dist/src/types.d.ts.map +1 -1
  156. package/dist/src/types.js.map +1 -1
  157. package/package.json +2 -4
  158. package/src/analysis/rules.ts +10 -2
  159. package/src/connectors/csv.ts +31 -1
  160. package/src/connectors/dsl-compiler.ts +76 -82
  161. package/src/connectors/dsl-validator.ts +6 -1
  162. package/src/connectors/index.ts +0 -3
  163. package/src/connectors/js-aggregation.ts +20 -15
  164. package/src/connectors/manager.ts +4 -24
  165. package/src/mcp/app-shell.ts +1 -1
  166. package/src/mcp/index.ts +87 -53
  167. package/src/mcp/prompts.ts +4 -4
  168. package/src/mcp/spec-store.ts +5 -1
  169. package/src/mcp/tools/analyze.ts +2 -2
  170. package/src/mcp/tools/bug-report.ts +2 -10
  171. package/src/mcp/tools/dashboard.ts +1 -1
  172. package/src/mcp/tools/dsl-schemas.ts +3 -3
  173. package/src/mcp/tools/export-html.ts +2 -2
  174. package/src/mcp/tools/list-patterns.ts +2 -2
  175. package/src/mcp/tools/query-source.ts +4 -4
  176. package/src/mcp/tools/refine.ts +333 -258
  177. package/src/mcp/tools/result-cache.ts +1 -1
  178. package/src/mcp/tools/screenshot.ts +1 -1
  179. package/src/mcp/tools/server-privacy.ts +6 -7
  180. package/src/mcp/tools/shared.ts +70 -7
  181. package/src/mcp/tools/sources.ts +18 -46
  182. package/src/mcp/tools/visualize-from-source.ts +24 -9
  183. package/src/mcp/tools/visualize.ts +27 -27
  184. package/src/patterns/definitions/comparison/grouped-bar.ts +5 -5
  185. package/src/patterns/definitions/composition/waffle.ts +17 -3
  186. package/src/patterns/definitions/distribution/strip-plot.ts +12 -3
  187. package/src/patterns/definitions/time/sparkline-grid.ts +2 -2
  188. package/src/patterns/selector.ts +47 -1
  189. package/src/renderers/d3/comparison/bar.ts +24 -1
  190. package/src/renderers/d3/comparison/grouped-bar.ts +9 -4
  191. package/src/renderers/d3/composition/donut.ts +14 -0
  192. package/src/renderers/d3/composition/stacked-bar.ts +5 -0
  193. package/src/renderers/d3/composition/treemap.ts +2 -1
  194. package/src/renderers/d3/distribution/beeswarm.ts +12 -0
  195. package/src/renderers/d3/distribution/histogram.ts +44 -2
  196. package/src/renderers/d3/flow/funnel.ts +8 -0
  197. package/src/renderers/d3/flow/sankey-layout.ts +23 -3
  198. package/src/renderers/d3/heatmap.ts +20 -2
  199. package/src/renderers/d3/radar.ts +4 -1
  200. package/src/renderers/d3/relationship.ts +31 -6
  201. package/src/renderers/d3/shared.ts +7 -7
  202. package/src/renderers/d3/time/area.ts +22 -7
  203. package/src/renderers/d3/time/calendar-heatmap.ts +5 -0
  204. package/src/renderers/d3/time/horizon-chart.ts +11 -0
  205. package/src/renderers/d3/time/line.ts +24 -9
  206. package/src/renderers/d3/time/small-multiples.ts +6 -0
  207. package/src/renderers/d3/time/sparkline-grid.ts +5 -2
  208. package/src/renderers/d3/time/stream-graph.ts +5 -0
  209. package/src/renderers/html/_generated/bundles.ts +39 -39
  210. package/src/renderers/html/builders/dashboard.ts +2 -2
  211. package/src/renderers/html/template.ts +2 -2
  212. package/src/types.ts +21 -33
  213. package/src/connectors/mysql.ts +0 -378
  214. package/src/connectors/postgres.ts +0 -367
  215. package/src/connectors/sqlite.ts +0 -364
@@ -1,5 +1,5 @@
1
1
  /**
2
- * In-memory result cache for query_source → visualize flow.
2
+ * In-memory result cache for query_data → visualize flow.
3
3
  * Max 20 entries, 10-minute TTL.
4
4
  */
5
5
 
@@ -14,7 +14,7 @@ import { specStore } from '../spec-store.js';
14
14
  import { errorResponse } from './shared.js';
15
15
 
16
16
  export const screenshotInputSchema = z.object({
17
- specId: z.string().describe('Spec ID from a previous visualize, visualize_from_source, or refine call'),
17
+ specId: z.string().describe('Spec ID from a previous visualize, visualize_data, or refine call'),
18
18
  width: z.number().optional().describe('Image width in pixels (default: 800)'),
19
19
  height: z.number().optional().describe('Image height in pixels (default: 600)'),
20
20
  });
@@ -27,11 +27,10 @@ export function handleServerStatus(deps: PrivacyDeps) {
27
27
  const specStats = specStore.stats();
28
28
  const resultStats = resultCacheStats();
29
29
 
30
- const sources = deps.sourceManager.list();
31
- const sourcesSummary = sources.map(s => ({
30
+ const datasets = deps.sourceManager.list();
31
+ const datasetsSummary = datasets.map((s: any) => ({
32
32
  id: s.id,
33
33
  name: s.name,
34
- type: s.type,
35
34
  connected: deps.sourceManager.isConnected(s.id),
36
35
  }));
37
36
 
@@ -52,10 +51,10 @@ export function handleServerStatus(deps: PrivacyDeps) {
52
51
  totalDataRows: resultStats.totalRows,
53
52
  ttl: '10 minutes',
54
53
  },
55
- sources: {
56
- registered: sources.length,
57
- connected: sourcesSummary.filter(s => s.connected).length,
58
- list: sourcesSummary,
54
+ datasets: {
55
+ loaded: datasets.length,
56
+ connected: datasetsSummary.filter((s: any) => s.connected).length,
57
+ list: datasetsSummary,
59
58
  },
60
59
  });
61
60
  };
@@ -67,9 +67,23 @@ export function inferColumns(data: Record<string, any>[]): DataColumn[] {
67
67
  values.every(v => /^\d{4}[-/]/.test(String(v)));
68
68
  const isId = /^id$|_id$|Id$/i.test(key) && uniqueValues.length > data.length * 0.5;
69
69
 
70
+ const YEAR_NAME_PATTERN = /\byear\b|\bcohort\b|\bfiscal\b|\bfy\b|\bsemester\b|\bvintage\b|\bclass_of\b|\bgraduating\b|\bperiod\b|\bseason\b/i;
71
+
72
+ const looksLikeYear = isNumeric &&
73
+ !isDate &&
74
+ YEAR_NAME_PATTERN.test(key) &&
75
+ values.length > 0 &&
76
+ values.every(v => {
77
+ const n = Number(v);
78
+ return Number.isInteger(n) && n >= 1900 && n <= 2100;
79
+ }) &&
80
+ uniqueValues.length <= 50 &&
81
+ uniqueValues.length > 1 &&
82
+ (Math.max(...values.map(Number)) - Math.min(...values.map(Number))) < 200;
83
+
70
84
  let type: DataColumn['type'] = 'categorical';
71
85
  if (isId) type = 'id';
72
- else if (isDate) type = 'date';
86
+ else if (isDate || looksLikeYear) type = 'date';
73
87
  else if (isNumeric) type = 'numeric';
74
88
 
75
89
  return {
@@ -87,9 +101,11 @@ export function inferColumns(data: Record<string, any>[]): DataColumn[] {
87
101
 
88
102
  export function applyColorPreferences(
89
103
  spec: VisualizationSpec,
90
- prefs?: DashboardViewSpec['colorPreferences'],
91
- ): void {
92
- if (!prefs) return;
104
+ prefs?: { palette?: string; highlight?: { values: any[]; color?: string | string[]; mutedColor?: string; mutedOpacity?: number }; colorField?: string },
105
+ data?: Record<string, any>[],
106
+ ): { notes: string[] } {
107
+ const notes: string[] = [];
108
+ if (!prefs) return { notes };
93
109
  if (!spec.encoding.color) spec.encoding.color = {};
94
110
 
95
111
  if (prefs.palette) {
@@ -107,6 +123,53 @@ export function applyColorPreferences(
107
123
  spec.encoding.color.field = prefs.colorField;
108
124
  if (!spec.encoding.color.type) spec.encoding.color.type = 'nominal';
109
125
  }
126
+
127
+ // Auto-infer color field if palette or highlight was set but no field exists
128
+ if ((prefs.palette || prefs.highlight) && !spec.encoding.color?.field) {
129
+ let inferred: string | null = null;
130
+
131
+ // Strategy 1: use nominal axis
132
+ if (spec.encoding.x?.type === 'nominal') inferred = spec.encoding.x.field;
133
+ else if (spec.encoding.y?.type === 'nominal') inferred = spec.encoding.y.field;
134
+
135
+ // Strategy 2: find a suitable categorical column from data
136
+ if (!inferred && data && data.length > 0) {
137
+ const keys = Object.keys(data[0]);
138
+ for (const key of keys) {
139
+ if (/^id$|_id$|Id$/i.test(key)) continue;
140
+ const vals = data.map(d => d[key]).filter(v => v != null);
141
+ const isNum = vals.every(v => typeof v === 'number' || !isNaN(Number(v)));
142
+ if (isNum) continue;
143
+ const unique = new Set(vals.map(String));
144
+ if (unique.size <= 20) {
145
+ inferred = key;
146
+ break;
147
+ }
148
+ }
149
+ }
150
+
151
+ if (inferred) {
152
+ spec.encoding.color!.field = inferred;
153
+ if (!spec.encoding.color!.type) spec.encoding.color!.type = 'nominal';
154
+ notes.push(`Color field auto-detected as '${inferred}'. Use colorField to override.`);
155
+ } else if (prefs.palette) {
156
+ notes.push(`Palette '${prefs.palette}' ignored — no categorical column found with ≤20 unique values. Use colorField to specify.`);
157
+ }
158
+ }
159
+
160
+ // Validate highlight values against data
161
+ if (prefs.highlight && spec.encoding.color?.field && data) {
162
+ const field = spec.encoding.color.field;
163
+ const dataValues = new Set(data.map(d => String(d[field]).toLowerCase()));
164
+ const unmatched = prefs.highlight.values.filter(
165
+ (v: any) => !dataValues.has(String(v).toLowerCase())
166
+ );
167
+ if (unmatched.length > 0) {
168
+ notes.push(`Highlight: ${unmatched.map((v: any) => `'${v}'`).join(', ')} not found in data for field '${field}'.`);
169
+ }
170
+ }
171
+
172
+ return { notes };
110
173
  }
111
174
 
112
175
  // ─── TIME BUCKET HELPERS ────────────────────────────────────────────────────
@@ -118,7 +181,7 @@ function getTimeBucketedFields(groupBy?: DslGroupByField[]): string[] {
118
181
  .map(g => g.field);
119
182
  }
120
183
 
121
- function enhanceIntentForTimeBucket(intent: string, groupBy?: DslGroupByField[]): string {
184
+ export function enhanceIntentForTimeBucket(intent: string, groupBy?: DslGroupByField[]): string {
122
185
  const bucketedFields = getTimeBucketedFields(groupBy);
123
186
  if (bucketedFields.length > 0 && !/time.series|trend|over.time/i.test(intent)) {
124
187
  return intent + ' (time series trend)';
@@ -126,7 +189,7 @@ function enhanceIntentForTimeBucket(intent: string, groupBy?: DslGroupByField[])
126
189
  return intent;
127
190
  }
128
191
 
129
- function applyTimeBucketColumnTypes(columns: DataColumn[], groupBy?: DslGroupByField[]): void {
192
+ export function applyTimeBucketColumnTypes(columns: DataColumn[], groupBy?: DslGroupByField[]): void {
130
193
  const bucketedFields = getTimeBucketedFields(groupBy);
131
194
  for (const col of columns) {
132
195
  if (bucketedFields.some(f => col.name.includes(f) || f.includes(col.name))) {
@@ -206,7 +269,7 @@ export async function executeDashboardViews(
206
269
  if (view.config) {
207
270
  spec.config = { ...spec.config, ...view.config };
208
271
  }
209
- applyColorPreferences(spec, view.colorPreferences);
272
+ applyColorPreferences(spec, view.colorPreferences, data);
210
273
 
211
274
  viewData.push({ viewId: view.id, data, spec });
212
275
  viewReasonings.push({ viewId: view.id, pattern: spec.pattern, reasoning });
@@ -1,6 +1,6 @@
1
1
  /**
2
- * MCP Tools: list_sources, add_source, remove_source, describe_source
3
- * Manage data source connections.
2
+ * MCP Tools: list_data, load_csv, remove_data, describe_data
3
+ * Manage CSV datasets.
4
4
  */
5
5
 
6
6
  import { z } from 'zod';
@@ -18,44 +18,17 @@ export function isSandboxPath(filePath: string): boolean {
18
18
  }
19
19
 
20
20
  export const addSourceInputSchema = z.object({
21
- name: z.string().describe('Human-readable name for this data source'),
22
- type: z.enum(['csv', 'sqlite', 'postgres', 'mysql']).describe('Type of data source'),
23
- config: z.union([
24
- z.object({
25
- type: z.literal('csv'),
26
- path: z.string().describe('Path to CSV file or directory of CSV files'),
27
- }),
28
- z.object({
29
- type: z.literal('sqlite'),
30
- path: z.string().describe('Path to SQLite database file'),
31
- }),
32
- z.object({
33
- type: z.literal('postgres'),
34
- host: z.string(),
35
- port: z.number().default(5432),
36
- database: z.string(),
37
- user: z.string(),
38
- password: z.string(),
39
- ssl: z.boolean().optional(),
40
- }),
41
- z.object({
42
- type: z.literal('mysql'),
43
- host: z.string(),
44
- port: z.number().default(3306),
45
- database: z.string(),
46
- user: z.string(),
47
- password: z.string(),
48
- }),
49
- ]).describe('Connection configuration'),
21
+ name: z.string().describe('Name for this dataset'),
22
+ path: z.string().describe('Path to a CSV file or directory of CSV files'),
50
23
  detail: z.enum(['compact', 'full']).default('full').describe('Schema detail level: "compact" returns just column names/types + row counts (saves tokens); "full" (default) includes stats, top values, and sample rows'),
51
24
  });
52
25
 
53
26
  export const removeSourceInputSchema = z.object({
54
- sourceId: z.string().describe('ID of the data source to remove'),
27
+ sourceId: z.string().describe('Dataset ID returned by load_csv'),
55
28
  });
56
29
 
57
30
  export const describeSourceInputSchema = z.object({
58
- sourceId: z.string().describe('Source ID from add_source'),
31
+ sourceId: z.string().describe('Dataset ID returned by load_csv'),
59
32
  table: z.string().optional().describe('Table name (optional — if omitted, returns all tables)'),
60
33
  detail: z.enum(['compact', 'full']).default('full').describe('Schema detail level: "compact" returns just column names/types + row counts; "full" (default) includes stats, top values, and sample rows'),
61
34
  });
@@ -94,16 +67,16 @@ export function handleListSources(deps: { sourceManager: any }) {
94
67
 
95
68
  export function handleAddSource(deps: { sourceManager: any }) {
96
69
  return async (args: z.infer<typeof addSourceInputSchema>) => {
97
- if ((args.config.type === 'csv' || args.config.type === 'sqlite') && 'path' in args.config) {
98
- if (isSandboxPath(args.config.path)) {
99
- return errorResponse(
100
- 'This path looks like a cloud sandbox path, not a local filesystem path. '
101
- + 'Dolex runs on the user\'s machine and can access any local file — but not cloud sandbox uploads. '
102
- + 'Ask the user for the real local path (e.g. /Users/name/Downloads/data.csv).'
103
- );
104
- }
70
+ if (isSandboxPath(args.path)) {
71
+ return errorResponse(
72
+ 'This path looks like a cloud sandbox path, not a local filesystem path. '
73
+ + 'Dolex runs on the user\'s machine and can access any local file — but not cloud sandbox uploads. '
74
+ + 'Ask the user for the real local path (e.g. /Users/name/Downloads/data.csv).'
75
+ );
105
76
  }
106
77
 
78
+ const config = { type: 'csv' as const, path: args.path };
79
+
107
80
  let entry: any;
108
81
  let reconnected = false;
109
82
 
@@ -114,18 +87,18 @@ export function handleAddSource(deps: { sourceManager: any }) {
114
87
  } else {
115
88
  let addResult: any;
116
89
  try {
117
- addResult = await deps.sourceManager.add(args.name, args.config);
90
+ addResult = await deps.sourceManager.add(args.name, config);
118
91
  } catch (err: any) {
119
92
  if (err.code === 'ENOENT') {
120
93
  return errorResponse(
121
- `File not found: ${(args.config as any).path}. `
94
+ `File not found: ${args.path}. `
122
95
  + 'Ask the user to double-check the path exists on their machine.'
123
96
  );
124
97
  }
125
98
  return errorResponse(err.message);
126
99
  }
127
100
  if (!addResult.ok || !addResult.entry) {
128
- return errorResponse(addResult.error ?? 'Failed to add source');
101
+ return errorResponse(addResult.error ?? 'Failed to load CSV');
129
102
  }
130
103
  entry = addResult.entry;
131
104
  }
@@ -141,12 +114,11 @@ export function handleAddSource(deps: { sourceManager: any }) {
141
114
  );
142
115
 
143
116
  const tableCount = schema?.tables.length ?? 0;
144
- const verb = reconnected ? 'Reconnected to' : 'Connected to';
117
+ const verb = reconnected ? 'Reconnected' : 'Loaded';
145
118
 
146
119
  return jsonResponse({
147
120
  sourceId: entry.id,
148
121
  name: entry.name,
149
- type: entry.type,
150
122
  tables,
151
123
  message: `${verb} "${args.name}" — ${tableCount} tables found`,
152
124
  });
@@ -1,5 +1,5 @@
1
1
  /**
2
- * MCP Tool: visualize_from_source
2
+ * MCP Tool: visualize_data
3
3
  * Takes a data source + DSL query + intent and returns visualization
4
4
  * recommendations from the handcrafted pattern library.
5
5
  *
@@ -8,18 +8,17 @@
8
8
 
9
9
  import { z } from 'zod';
10
10
  import type { VisualizeInput, VisualizeOutput } from '../../types.js';
11
- import { dslQuerySchema } from './dsl-schemas.js';
11
+ import { dslQuerySchema, ALL_PALETTE_NAMES } from './dsl-schemas.js';
12
12
  import {
13
- colorPreferencesSchema,
14
13
  columnsSchema,
15
14
  dataShapeHintsSchema,
16
15
  handleVisualizeCore,
17
16
  } from './visualize.js';
18
- import { errorResponse } from './shared.js';
17
+ import { errorResponse, inferColumns, applyTimeBucketColumnTypes, enhanceIntentForTimeBucket } from './shared.js';
19
18
  import { logOperation, extractDslStructure } from './operation-log.js';
20
19
 
21
20
  export const visualizeFromSourceInputSchema = z.object({
22
- sourceId: z.string().describe('Source ID from add_source'),
21
+ sourceId: z.string().describe('Dataset ID returned by load_csv'),
23
22
  table: z.string().describe('Base table within the source'),
24
23
  query: dslQuerySchema.describe('Declarative query to slice/aggregate the data before visualizing'),
25
24
  intent: z.string().describe('What the user wants to see — e.g., "compare sales by region", "show distribution of ages", "how do rankings change over time"'),
@@ -29,7 +28,15 @@ export const visualizeFromSourceInputSchema = z.object({
29
28
  title: z.string().optional().describe('Chart title — set upfront to avoid a refine round-trip'),
30
29
  subtitle: z.string().optional().describe('Chart subtitle — set upfront to avoid a refine round-trip'),
31
30
  includeDataTable: z.boolean().optional().describe('Whether to add a companion sortable data table with linked highlighting below the chart. Default: true'),
32
- colorPreferences: colorPreferencesSchema,
31
+ palette: z.enum(ALL_PALETTE_NAMES).optional()
32
+ .describe('Named palette: categorical, blue, green, purple, warm, blueRed, etc.'),
33
+ highlight: z.object({
34
+ values: z.array(z.union([z.string(), z.number()])).describe('Values to emphasize'),
35
+ color: z.union([z.string(), z.array(z.string())]).optional(),
36
+ mutedColor: z.string().optional(),
37
+ mutedOpacity: z.number().optional(),
38
+ }).optional(),
39
+ colorField: z.string().optional().describe('Which data field to base colors on'),
33
40
  maxAlternativeChartTypes: z.number().optional().describe('Max alternative chart type recommendations to return (default: 2, set 0 for none)'),
34
41
  geoLevel: z.enum(['country', 'subdivision']).optional()
35
42
  .describe('Geographic level: "country" (each row = a nation) or "subdivision" (each row = a state/province). Auto-detected if omitted.'),
@@ -41,7 +48,7 @@ export function handleVisualizeFromSource(
41
48
  selectPatterns: (input: VisualizeInput) => VisualizeOutput,
42
49
  deps: { sourceManager: any },
43
50
  ) {
44
- const core = handleVisualizeCore(selectPatterns, 'visualize_from_source');
51
+ const core = handleVisualizeCore(selectPatterns, 'visualize_data');
45
52
 
46
53
  return async (args: z.infer<typeof visualizeFromSourceInputSchema>) => {
47
54
  const start = Date.now();
@@ -56,7 +63,7 @@ export function handleVisualizeFromSource(
56
63
  const result = await deps.sourceManager.queryDsl(args.sourceId, args.table, args.query);
57
64
  if (!result.ok) {
58
65
  logOperation({
59
- toolName: 'visualize_from_source',
66
+ toolName: 'visualize_data',
60
67
  timestamp: start,
61
68
  durationMs: Date.now() - start,
62
69
  success: false,
@@ -69,7 +76,15 @@ export function handleVisualizeFromSource(
69
76
  return errorResponse(result.error);
70
77
  }
71
78
 
72
- return core(result.rows, args, { truncated: result.truncated, totalSourceRows: result.totalRows }, {
79
+ // Enrich column types and intent with time bucket context (matches dashboard behavior)
80
+ if (!args.columns && args.query.groupBy) {
81
+ const columns = inferColumns(result.rows);
82
+ applyTimeBucketColumnTypes(columns, args.query.groupBy);
83
+ args = { ...args, columns: columns as any };
84
+ }
85
+ const enrichedIntent = enhanceIntentForTimeBucket(args.intent, args.query.groupBy);
86
+
87
+ return core(result.rows, { ...args, intent: enrichedIntent }, { truncated: result.truncated, totalSourceRows: result.totalRows }, {
73
88
  dslStructure: extractDslStructure(args.query),
74
89
  sourceType,
75
90
  });
@@ -3,7 +3,7 @@
3
3
  * Takes inline data + intent and returns visualization recommendations
4
4
  * from the handcrafted pattern library.
5
5
  *
6
- * For source-based data (sourceId + table + query), use visualize_from_source.
6
+ * For source-based data (sourceId + table + query), use visualize_data.
7
7
  *
8
8
  * Returns compact text content (specId + metadata, no data) while
9
9
  * structuredContent still gets the full pre-rendered chart HTML.
@@ -12,6 +12,7 @@
12
12
  import { z } from 'zod';
13
13
  import type { VisualizeInput, VisualizeOutput, DataColumn, VisualizationSpec } from '../../types.js';
14
14
  import { isCompoundSpec } from '../../types.js';
15
+ import { ALL_PALETTE_NAMES } from './dsl-schemas.js';
15
16
  import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
16
17
  import { shouldCompound, buildCompoundSpec } from '../../renderers/html/compound.js';
17
18
  import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
@@ -21,23 +22,6 @@ import { errorResponse, inferColumns, applyColorPreferences } from './shared.js'
21
22
  import { logOperation } from './operation-log.js';
22
23
  import type { OperationMeta } from './operation-log.js';
23
24
 
24
- const ALL_PALETTE_NAMES = [
25
- 'categorical', 'blue', 'green', 'purple', 'warm',
26
- 'blueRed', 'greenPurple', 'tealOrange', 'redGreen',
27
- 'traffic-light', 'profit-loss', 'temperature',
28
- ] as const;
29
-
30
- export const colorPreferencesSchema = z.object({
31
- palette: z.enum(ALL_PALETTE_NAMES).optional().describe('Named palette: categorical, blue, green, purple, warm, blueRed, greenPurple, tealOrange, redGreen, traffic-light, profit-loss, temperature'),
32
- highlight: z.object({
33
- values: z.array(z.any()).describe('Values to emphasize — all others become muted gray'),
34
- color: z.union([z.string(), z.array(z.string())]).optional().describe('Color(s) for highlighted values. Single CSS color or array matching values length.'),
35
- mutedColor: z.string().optional().describe('Color for non-highlighted items (default: #6b7280)'),
36
- mutedOpacity: z.number().optional().describe('Opacity for muted items (default: 1.0, lower for stronger de-emphasis)'),
37
- }).optional(),
38
- colorField: z.string().optional().describe('Which data field to base colors on'),
39
- }).optional().describe('Color preferences applied to the visualization');
40
-
41
25
  export const columnsSchema = z.array(z.object({
42
26
  name: z.string(),
43
27
  type: z.enum(['numeric', 'categorical', 'date', 'id', 'text']),
@@ -61,7 +45,7 @@ export const dataShapeHintsSchema = z.object({
61
45
 
62
46
  export const visualizeInputSchema = z.object({
63
47
  data: z.array(z.record(z.any())).optional().describe('Array of data rows to visualize. Optional if resultId is provided.'),
64
- resultId: z.string().optional().describe('Result ID from a previous query_source call — reuses cached data without re-sending it'),
48
+ resultId: z.string().optional().describe('Result ID from a previous query_data call — reuses cached data without re-sending it'),
65
49
  intent: z.string().describe('What the user wants to see — e.g., "compare sales by region", "show distribution of ages", "how do rankings change over time"'),
66
50
  columns: columnsSchema,
67
51
  dataShapeHints: dataShapeHintsSchema,
@@ -69,7 +53,15 @@ export const visualizeInputSchema = z.object({
69
53
  title: z.string().optional().describe('Chart title — set upfront to avoid a refine round-trip'),
70
54
  subtitle: z.string().optional().describe('Chart subtitle — set upfront to avoid a refine round-trip'),
71
55
  includeDataTable: z.boolean().optional().describe('Whether to add a companion sortable data table with linked highlighting below the chart. Default: true'),
72
- colorPreferences: colorPreferencesSchema,
56
+ palette: z.enum(ALL_PALETTE_NAMES).optional()
57
+ .describe('Named palette: categorical, blue, green, purple, warm, blueRed, etc.'),
58
+ highlight: z.object({
59
+ values: z.array(z.union([z.string(), z.number()])).describe('Values to emphasize'),
60
+ color: z.union([z.string(), z.array(z.string())]).optional(),
61
+ mutedColor: z.string().optional(),
62
+ mutedOpacity: z.number().optional(),
63
+ }).optional(),
64
+ colorField: z.string().optional().describe('Which data field to base colors on'),
73
65
  maxAlternativeChartTypes: z.number().optional().describe('Max alternative chart type recommendations to return (default: 2, set 0 for none)'),
74
66
  geoLevel: z.enum(['country', 'subdivision']).optional()
75
67
  .describe('Geographic level: "country" (each row = a nation) or "subdivision" (each row = a state/province). Auto-detected if omitted.'),
@@ -78,7 +70,7 @@ export const visualizeInputSchema = z.object({
78
70
  });
79
71
 
80
72
  /**
81
- * Shared core logic for both visualize and visualize_from_source.
73
+ * Shared core logic for both visualize and visualize_data.
82
74
  * Takes resolved data + args and returns the MCP response.
83
75
  */
84
76
  export function handleVisualizeCore(
@@ -93,12 +85,15 @@ export function handleVisualizeCore(
93
85
  title?: string;
94
86
  subtitle?: string;
95
87
  includeDataTable?: boolean;
96
- colorPreferences?: z.infer<typeof colorPreferencesSchema>;
88
+ palette?: string;
89
+ highlight?: { values: any[]; color?: string | string[]; mutedColor?: string; mutedOpacity?: number };
90
+ colorField?: string;
97
91
  maxAlternativeChartTypes?: number;
98
92
  geoLevel?: 'country' | 'subdivision';
99
93
  geoRegion?: string;
100
94
  }, queryMeta?: { truncated?: boolean; totalSourceRows?: number }, extraMeta?: Partial<OperationMeta>) => {
101
95
  const start = Date.now();
96
+ const notes: string[] = [];
102
97
  const columns = (args.columns as DataColumn[]) || inferColumns(data);
103
98
  const maxAlternativeChartTypes = args.maxAlternativeChartTypes ?? 2;
104
99
 
@@ -116,8 +111,12 @@ export function handleVisualizeCore(
116
111
 
117
112
  const alternatives = result.alternatives.slice(0, maxAlternativeChartTypes);
118
113
 
119
- if (args.colorPreferences) {
120
- applyColorPreferences(result.recommended.spec, args.colorPreferences);
114
+ const colorPrefs = (args.palette || args.highlight || args.colorField)
115
+ ? { palette: args.palette, highlight: args.highlight, colorField: args.colorField }
116
+ : undefined;
117
+ if (colorPrefs) {
118
+ const colorResult = applyColorPreferences(result.recommended.spec, colorPrefs, data);
119
+ notes.push(...colorResult.notes);
121
120
  }
122
121
 
123
122
  const spec = result.recommended.spec;
@@ -139,10 +138,11 @@ export function handleVisualizeCore(
139
138
  for (const alt of alternatives) {
140
139
  alternativesMap.set(alt.pattern, alt.spec);
141
140
  }
142
- const specId = specStore.save(finalSpec, columns, alternativesMap);
141
+ const specId = specStore.save(finalSpec, columns, alternativesMap, data);
143
142
 
144
143
  const compactResponse: Record<string, any> = {
145
144
  specId,
145
+ ...(notes.length > 0 ? { notes } : {}),
146
146
  recommended: {
147
147
  pattern: result.recommended.pattern,
148
148
  title: spec.title,
@@ -215,13 +215,13 @@ export function handleVisualize(
215
215
  if (args.resultId) {
216
216
  const cached = getResult(args.resultId);
217
217
  if (!cached) {
218
- return errorResponse(`Result "${args.resultId}" not found or expired. Re-run query_source to get a new resultId.`);
218
+ return errorResponse(`Result "${args.resultId}" not found or expired. Re-run query_data to get a new resultId.`);
219
219
  }
220
220
  data = cached.rows;
221
221
  }
222
222
 
223
223
  if (!data || data.length === 0) {
224
- return errorResponse('No data provided. Pass either `data` array or `resultId` from query_source.');
224
+ return errorResponse('No data provided. Pass either `data` array or `resultId` from query_data.');
225
225
  }
226
226
 
227
227
  return core(data, args);
@@ -93,7 +93,7 @@ export const groupedBarPattern: VisualizationPattern = {
93
93
  generateSpec: (data, columns, options) => {
94
94
  const categoryCol = columns[0];
95
95
  const seriesCol = columns.length > 2 ? columns[1] : undefined;
96
- const valueCol = columns.length > 2 ? columns[2] : columns.length > 1 ? columns[1] : columns[0];
96
+ const valueCol = columns.length > 2 ? columns[2] : columns.length > 1 ? columns[1] : undefined;
97
97
 
98
98
  const spec: VisualizationSpec = {
99
99
  pattern: 'grouped-bar',
@@ -101,15 +101,15 @@ export const groupedBarPattern: VisualizationPattern = {
101
101
  data,
102
102
  encoding: {
103
103
  x: { field: categoryCol, type: 'nominal', title: categoryCol },
104
- y: { field: valueCol, type: 'quantitative', title: valueCol },
104
+ y: valueCol ? { field: valueCol, type: 'quantitative', title: valueCol } : undefined,
105
105
  color: seriesCol
106
106
  ? { field: seriesCol, type: 'nominal', scale: {} }
107
- : { field: categoryCol, type: 'nominal', scale: {} },
107
+ : undefined,
108
108
  },
109
109
  config: {
110
110
  categoryField: categoryCol,
111
- seriesField: seriesCol,
112
- valueField: valueCol,
111
+ seriesField: seriesCol ?? null,
112
+ valueField: valueCol ?? null,
113
113
  orientation: options?.orientation ?? 'vertical',
114
114
  },
115
115
  };
@@ -33,8 +33,8 @@ export const wafflePattern: VisualizationPattern = {
33
33
 
34
34
  selectionRules: [
35
35
  {
36
- condition: 'Part-to-whole with few categories — waffle beats pie every time',
37
- weight: 75,
36
+ condition: 'Part-to-whole with few categories',
37
+ weight: 40,
38
38
  matches: (ctx) => {
39
39
  return (
40
40
  ctx.dataShape.categoryCount >= 2 &&
@@ -52,13 +52,27 @@ export const wafflePattern: VisualizationPattern = {
52
52
  );
53
53
  },
54
54
  },
55
+ {
56
+ condition: 'Composition intent — proportion, breakdown, split',
57
+ weight: 40,
58
+ matches: (ctx) => {
59
+ return /\b(proportion|share|part.of|breakdown|split|how\s+much\s+of)\b/i.test(ctx.intent);
60
+ },
61
+ },
55
62
  {
56
63
  condition: 'Very few categories (2-4) — waffle is clearest',
57
- weight: 30,
64
+ weight: 15,
58
65
  matches: (ctx) => {
59
66
  return ctx.dataShape.categoryCount >= 2 && ctx.dataShape.categoryCount <= 4;
60
67
  },
61
68
  },
69
+ {
70
+ condition: 'Penalize for comparison intent — bar chart is better',
71
+ weight: -25,
72
+ matches: (ctx) => {
73
+ return /(compar|rank|top|bottom|highest|lowest|bar\s*chart)/i.test(ctx.intent);
74
+ },
75
+ },
62
76
  {
63
77
  condition: 'Penalize for too many categories — colors become indistinguishable',
64
78
  weight: -40,
@@ -30,18 +30,19 @@ export const stripPlotPattern: VisualizationPattern = {
30
30
  selectionRules: [
31
31
  {
32
32
  condition: 'Very small dataset — strip plot shows every point clearly',
33
- weight: 70,
33
+ weight: 35,
34
34
  matches: (ctx) => {
35
35
  return (
36
36
  ctx.dataShape.rowCount >= 3 &&
37
37
  ctx.dataShape.rowCount <= 50 &&
38
- ctx.dataShape.numericColumnCount >= 1
38
+ ctx.dataShape.numericColumnCount >= 1 &&
39
+ !ctx.dataShape.hasTimeSeries
39
40
  );
40
41
  },
41
42
  },
42
43
  {
43
44
  condition: 'Distribution intent with small data — too few points for histogram/violin',
44
- weight: 60,
45
+ weight: 65,
45
46
  matches: (ctx) => {
46
47
  return (
47
48
  /\b(distribut|spread|point|individual)\b/i.test(ctx.intent) &&
@@ -58,6 +59,14 @@ export const stripPlotPattern: VisualizationPattern = {
58
59
  return avgPerGroup < 15 && avgPerGroup >= 3;
59
60
  },
60
61
  },
62
+ {
63
+ condition: 'Penalize for time/comparison/composition signals — strip-plot is wrong',
64
+ weight: -30,
65
+ matches: (ctx) => {
66
+ return ctx.dataShape.hasTimeSeries ||
67
+ /(compar|rank|trend|over\s*time|composition|proportion)/i.test(ctx.intent);
68
+ },
69
+ },
61
70
  {
62
71
  condition: 'Penalize for large datasets — too many overlapping points',
63
72
  weight: -50,
@@ -123,8 +123,8 @@ export const sparklineGridPattern: VisualizationPattern = {
123
123
  seriesField: seriesCol,
124
124
  gridCols,
125
125
  seriesMeta,
126
- cellWidth: options?.cellWidth ?? 100,
127
- cellHeight: options?.cellHeight ?? 30,
126
+ cellWidth: options?.cellWidth ?? undefined,
127
+ cellHeight: options?.cellHeight ?? undefined,
128
128
  curveType: options?.curveType ?? 'monotone',
129
129
  showSeriesLabel: options?.showSeriesLabel ?? true,
130
130
  showLatestValue: options?.showLatestValue ?? true,