@outsidedata/dolex 6.0.0 → 6.1.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 (54) hide show
  1. package/dist/src/mcp/index.js +5 -5
  2. package/dist/src/mcp/index.js.map +1 -1
  3. package/dist/src/mcp/tools/drop-columns.d.ts.map +1 -1
  4. package/dist/src/mcp/tools/drop-columns.js +8 -21
  5. package/dist/src/mcp/tools/drop-columns.js.map +1 -1
  6. package/dist/src/mcp/tools/export-html.d.ts.map +1 -1
  7. package/dist/src/mcp/tools/export-html.js +10 -28
  8. package/dist/src/mcp/tools/export-html.js.map +1 -1
  9. package/dist/src/mcp/tools/list-transforms.d.ts.map +1 -1
  10. package/dist/src/mcp/tools/list-transforms.js +14 -29
  11. package/dist/src/mcp/tools/list-transforms.js.map +1 -1
  12. package/dist/src/mcp/tools/promote-columns.d.ts.map +1 -1
  13. package/dist/src/mcp/tools/promote-columns.js +8 -25
  14. package/dist/src/mcp/tools/promote-columns.js.map +1 -1
  15. package/dist/src/mcp/tools/refine-cli.d.ts.map +1 -1
  16. package/dist/src/mcp/tools/refine-cli.js +8 -39
  17. package/dist/src/mcp/tools/refine-cli.js.map +1 -1
  18. package/dist/src/mcp/tools/refine.d.ts.map +1 -1
  19. package/dist/src/mcp/tools/refine.js +1 -12
  20. package/dist/src/mcp/tools/refine.js.map +1 -1
  21. package/dist/src/mcp/tools/screenshot.d.ts.map +1 -1
  22. package/dist/src/mcp/tools/screenshot.js +4 -14
  23. package/dist/src/mcp/tools/screenshot.js.map +1 -1
  24. package/dist/src/mcp/tools/shared.d.ts +55 -1
  25. package/dist/src/mcp/tools/shared.d.ts.map +1 -1
  26. package/dist/src/mcp/tools/shared.js +89 -0
  27. package/dist/src/mcp/tools/shared.js.map +1 -1
  28. package/dist/src/mcp/tools/sources.d.ts +0 -3
  29. package/dist/src/mcp/tools/sources.d.ts.map +1 -1
  30. package/dist/src/mcp/tools/sources.js +59 -8
  31. package/dist/src/mcp/tools/sources.js.map +1 -1
  32. package/dist/src/mcp/tools/transform-data.d.ts.map +1 -1
  33. package/dist/src/mcp/tools/transform-data.js +11 -31
  34. package/dist/src/mcp/tools/transform-data.js.map +1 -1
  35. package/dist/src/mcp/tools/visualize-cli.d.ts.map +1 -1
  36. package/dist/src/mcp/tools/visualize-cli.js +23 -113
  37. package/dist/src/mcp/tools/visualize-cli.js.map +1 -1
  38. package/dist/src/mcp/tools/visualize.d.ts.map +1 -1
  39. package/dist/src/mcp/tools/visualize.js +13 -49
  40. package/dist/src/mcp/tools/visualize.js.map +1 -1
  41. package/package.json +1 -1
  42. package/src/mcp/index.ts +5 -5
  43. package/src/mcp/tools/drop-columns.ts +8 -21
  44. package/src/mcp/tools/export-html.ts +9 -26
  45. package/src/mcp/tools/list-transforms.ts +14 -31
  46. package/src/mcp/tools/promote-columns.ts +7 -28
  47. package/src/mcp/tools/refine-cli.ts +7 -41
  48. package/src/mcp/tools/refine.ts +1 -14
  49. package/src/mcp/tools/screenshot.ts +4 -13
  50. package/src/mcp/tools/shared.ts +127 -0
  51. package/src/mcp/tools/sources.ts +56 -12
  52. package/src/mcp/tools/transform-data.ts +24 -47
  53. package/src/mcp/tools/visualize-cli.ts +27 -123
  54. package/src/mcp/tools/visualize.ts +16 -54
@@ -4,7 +4,7 @@
4
4
  * Promotes working columns to derived (persisted in .dolex.json manifest).
5
5
  */
6
6
  import type { z } from 'zod';
7
- import { errorResponse, jsonResponse } from './shared.js';
7
+ import { errorResponse, jsonResponse, connectAndValidateTable, isTransformError } from './shared.js';
8
8
  import type { promoteColumnsSchema } from './transform-schemas.js';
9
9
  import { TransformMetadata } from '../../transforms/metadata.js';
10
10
  import { writeManifest, resolveManifestPath } from '../../transforms/manifest.js';
@@ -12,28 +12,12 @@ import type { CsvSourceConfig } from '../../types.js';
12
12
 
13
13
  export function handlePromoteColumns(deps: { sourceManager: any }) {
14
14
  return async (args: z.infer<typeof promoteColumnsSchema>) => {
15
- const connResult = await deps.sourceManager.connect(args.sourceId);
16
- if (!connResult.ok) {
17
- return errorResponse(`Source not found: ${args.sourceId}`);
18
- }
19
-
20
- const source = connResult.source!;
21
- const db = source.getDatabase?.();
22
- if (!db) {
23
- return errorResponse('Source does not support transforms (no database handle)');
24
- }
15
+ const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
16
+ if (isTransformError(ctx)) return ctx;
25
17
 
26
- const schema = await source.getSchema();
27
- const table = schema.tables.find((t: any) => t.name === args.table);
28
- if (!table) {
29
- const available = schema.tables.map((t: any) => t.name);
30
- return errorResponse(`Table '${args.table}' not found. Available: [${available.join(', ')}]`);
31
- }
32
-
33
- const metadata = new TransformMetadata(db);
18
+ const metadata = new TransformMetadata(ctx.db);
34
19
  metadata.init();
35
20
 
36
- // Resolve columns to promote
37
21
  let columnsToPromote: string[];
38
22
  if (args.columns.length === 1 && args.columns[0] === '*') {
39
23
  const working = metadata.list(args.table, 'working');
@@ -45,7 +29,6 @@ export function handlePromoteColumns(deps: { sourceManager: any }) {
45
29
  columnsToPromote = args.columns;
46
30
  }
47
31
 
48
- // Pre-validate all columns before promoting any (atomic: all-or-nothing)
49
32
  for (const col of columnsToPromote) {
50
33
  const record = metadata.get(args.table, col);
51
34
  if (!record) {
@@ -56,7 +39,6 @@ export function handlePromoteColumns(deps: { sourceManager: any }) {
56
39
  }
57
40
  }
58
41
 
59
- // Execute promotions
60
42
  const promoted: string[] = [];
61
43
  const overwroteExisting: string[] = [];
62
44
  for (const col of columnsToPromote) {
@@ -68,22 +50,19 @@ export function handlePromoteColumns(deps: { sourceManager: any }) {
68
50
  promoted.push(col);
69
51
  }
70
52
 
71
- // Write manifest
72
53
  const entry = deps.sourceManager.get(args.sourceId);
73
54
  if (entry?.config) {
55
+ const schema = await ctx.source.getSchema();
74
56
  const manifestPath = resolveManifestPath(entry.config as CsvSourceConfig);
75
57
  const tableNames = schema.tables.map((t: any) => t.name);
76
58
  writeManifest(metadata, tableNames, manifestPath);
77
59
  }
78
60
 
79
- const workingRemaining = metadata.list(args.table, 'working').length;
80
- const derivedTotal = metadata.list(args.table, 'derived').length;
81
-
82
61
  return jsonResponse({
83
62
  promoted,
84
63
  overwrote_existing: overwroteExisting,
85
- working_remaining: workingRemaining,
86
- derived_total: derivedTotal,
64
+ working_remaining: metadata.list(args.table, 'working').length,
65
+ derived_total: metadata.list(args.table, 'derived').length,
87
66
  });
88
67
  };
89
68
  }
@@ -10,46 +10,25 @@
10
10
  */
11
11
 
12
12
  import { z } from 'zod';
13
- import { writeFileSync, mkdirSync } from 'fs';
14
- import { dirname } from 'path';
15
- import type { VisualizationSpec, CompoundVisualizationSpec } from '../../types.js';
16
- import { isCompoundSpec } from '../../types.js';
17
- import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
18
- import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
19
13
  import { specStore } from '../spec-store.js';
20
- import { errorResponse } from './shared.js';
14
+ import { errorResponse, buildOutputHtml, writeHtmlToDisk } from './shared.js';
21
15
  import { refineInputSchema, handleRefine } from './refine.js';
22
16
 
23
- // Extend the refine schema with required writeTo
24
17
  export const refineCliInputSchema = refineInputSchema.extend({
25
18
  writeTo: z.string().describe('REQUIRED. File path to write the refined HTML chart to. The HTML is written to disk and NOT returned in the response.'),
26
19
  });
27
20
 
28
- function buildOutputHtml(spec: VisualizationSpec | CompoundVisualizationSpec): string | undefined {
29
- if (isCompoundSpec(spec)) {
30
- return buildCompoundHtml(spec);
31
- }
32
- if (isHtmlPatternSupported(spec.pattern)) {
33
- return buildChartHtml(spec);
34
- }
35
- return undefined;
36
- }
37
-
38
21
  export function handleRefineCli() {
39
- // Get the base refine handler to reuse its logic
40
22
  const baseRefine = handleRefine();
41
23
 
42
24
  return async (args: z.infer<typeof refineCliInputSchema>) => {
43
- // Call the base refine to do all the spec manipulation
44
25
  const stored = specStore.get(args.specId);
45
26
  if (!stored) {
46
27
  return errorResponse(`Spec "${args.specId}" not found. It may have expired. Re-run visualize to get a new specId.`);
47
28
  }
48
29
 
49
- // Run base refine (it will update the spec store)
50
30
  const baseResult = await baseRefine(args);
51
31
 
52
- // Extract the response body from base result
53
32
  const textContent = baseResult.content.find((c: any) => c.type === 'text');
54
33
  if (!textContent) {
55
34
  return errorResponse('Unexpected error: no text content from refine');
@@ -58,7 +37,6 @@ export function handleRefineCli() {
58
37
  const body = JSON.parse(textContent.text);
59
38
  const newSpecId = body.specId;
60
39
 
61
- // Get the updated spec and build HTML
62
40
  const updatedStored = specStore.get(newSpecId);
63
41
  if (!updatedStored) {
64
42
  return errorResponse('Unexpected error: refined spec not found');
@@ -66,28 +44,16 @@ export function handleRefineCli() {
66
44
 
67
45
  const outputHtml = buildOutputHtml(updatedStored.spec);
68
46
 
69
- // Write HTML to disk
70
- let writeResult: string;
71
47
  if (outputHtml) {
72
- try {
73
- mkdirSync(dirname(args.writeTo), { recursive: true });
74
- writeFileSync(args.writeTo, outputHtml, 'utf-8');
75
- writeResult = `Wrote ${outputHtml.length} bytes to ${args.writeTo}`;
76
- } catch (err) {
77
- return errorResponse(`Failed to write to ${args.writeTo}: ${err instanceof Error ? err.message : String(err)}`);
78
- }
48
+ const writeResult = writeHtmlToDisk(outputHtml, args.writeTo);
49
+ if (!writeResult.ok) return errorResponse(writeResult.error);
50
+ body.writeTo = args.writeTo;
51
+ body.writeResult = writeResult.message;
79
52
  } else {
80
- const pattern = isCompoundSpec(updatedStored.spec)
81
- ? (updatedStored.spec as any).views?.find((v: any) => v.type === 'chart')?.chart?.pattern
82
- : (updatedStored.spec as VisualizationSpec).pattern;
83
- writeResult = `No HTML builder for pattern "${pattern}"`;
53
+ body.writeTo = args.writeTo;
54
+ body.writeResult = `No HTML builder for current pattern`;
84
55
  }
85
56
 
86
- // Add write info to response
87
- body.writeTo = args.writeTo;
88
- body.writeResult = writeResult;
89
-
90
- // CLI tools NEVER return structuredContent - just text
91
57
  return {
92
58
  content: [{
93
59
  type: 'text' as const,
@@ -3,14 +3,11 @@ import type {
3
3
  VisualizationSpec,
4
4
  CompoundVisualizationSpec,
5
5
  RefineOutput,
6
- DataColumn,
7
6
  } from '../../types.js';
8
7
  import { isCompoundSpec } from '../../types.js';
9
- import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
10
- import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
11
8
  import { specStore } from '../spec-store.js';
12
9
  import type { StoredSpec } from '../spec-store.js';
13
- import { errorResponse, htmlResponse } from './shared.js';
10
+ import { errorResponse, htmlResponse, buildOutputHtml } from './shared.js';
14
11
  import { logOperation } from './operation-log.js';
15
12
  import { selectPattern } from '../../patterns/selector.js';
16
13
  import { ALL_PALETTE_NAMES } from './sql-schemas.js';
@@ -371,16 +368,6 @@ function applyCompoundParams(
371
368
  return { spec, changes, notes };
372
369
  }
373
370
 
374
- function buildOutputHtml(spec: VisualizationSpec | CompoundVisualizationSpec): string | undefined {
375
- if (isCompoundSpec(spec)) {
376
- return buildCompoundHtml(spec);
377
- }
378
- if (isHtmlPatternSupported(spec.pattern)) {
379
- return buildChartHtml(spec);
380
- }
381
- return undefined;
382
- }
383
-
384
371
  export function handleRefine() {
385
372
  return async (args: RefineArgs) => {
386
373
  const start = Date.now();
@@ -7,11 +7,8 @@
7
7
  */
8
8
 
9
9
  import { z } from 'zod';
10
- import { isCompoundSpec } from '../../types.js';
11
- import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
12
- import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
13
10
  import { specStore } from '../spec-store.js';
14
- import { errorResponse } from './shared.js';
11
+ import { errorResponse, buildOutputHtml } from './shared.js';
15
12
 
16
13
  export const screenshotInputSchema = z.object({
17
14
  specId: z.string().describe('Spec ID from a previous visualize or refine call'),
@@ -57,15 +54,9 @@ export function handleScreenshot() {
57
54
  return errorResponse(`Spec "${args.specId}" not found or expired. Create a new visualization first.`);
58
55
  }
59
56
 
60
- const { spec } = stored;
61
- let html: string;
62
-
63
- if (isCompoundSpec(spec)) {
64
- html = buildCompoundHtml(spec);
65
- } else if (isHtmlPatternSupported(spec.pattern)) {
66
- html = buildChartHtml(spec);
67
- } else {
68
- return errorResponse(`Pattern "${spec.pattern}" does not have an HTML builder.`);
57
+ const html = buildOutputHtml(stored.spec);
58
+ if (!html) {
59
+ return errorResponse(`Spec "${args.specId}" does not have an HTML builder.`);
69
60
  }
70
61
 
71
62
  const width = args.width ?? 800;
@@ -7,11 +7,17 @@
7
7
  * - Color preference application to visualization specs
8
8
  */
9
9
 
10
+ import { writeFileSync, mkdirSync } from 'fs';
11
+ import { dirname } from 'path';
10
12
  import type {
11
13
  DataColumn,
12
14
  VisualizationSpec,
15
+ CompoundVisualizationSpec,
13
16
  ColorPaletteName,
14
17
  } from '../../types.js';
18
+ import { isCompoundSpec } from '../../types.js';
19
+ import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
20
+ import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
15
21
 
16
22
  // ─── MCP RESPONSE BUILDERS ─────────────────────────────────────────────────
17
23
 
@@ -168,6 +174,28 @@ export function applyColorPreferences(
168
174
  return { notes };
169
175
  }
170
176
 
177
+ // ─── HTML BUILDING ──────────────────────────────────────────────────────────
178
+
179
+ export function buildOutputHtml(spec: VisualizationSpec | CompoundVisualizationSpec): string | undefined {
180
+ if (isCompoundSpec(spec)) {
181
+ return buildCompoundHtml(spec);
182
+ }
183
+ if (isHtmlPatternSupported(spec.pattern)) {
184
+ return buildChartHtml(spec);
185
+ }
186
+ return undefined;
187
+ }
188
+
189
+ export function writeHtmlToDisk(html: string, writeTo: string): { ok: true; message: string } | { ok: false; error: string } {
190
+ try {
191
+ mkdirSync(dirname(writeTo), { recursive: true });
192
+ writeFileSync(writeTo, html, 'utf-8');
193
+ return { ok: true, message: `Wrote ${html.length} bytes to ${writeTo}` };
194
+ } catch (err) {
195
+ return { ok: false, error: `Failed to write to ${writeTo}: ${err instanceof Error ? err.message : String(err)}` };
196
+ }
197
+ }
198
+
171
199
  // ─── FORMATTING ─────────────────────────────────────────────────────────────
172
200
 
173
201
  export function formatUptime(ms: number): string {
@@ -176,3 +204,102 @@ export function formatUptime(ms: number): string {
176
204
  return `${Math.floor(min / 60)}h ${min % 60}m`;
177
205
  }
178
206
 
207
+ // ─── DATA RESOLUTION ────────────────────────────────────────────────────────
208
+
209
+ export interface ResolvedData {
210
+ data: Record<string, any>[];
211
+ queryMeta?: { truncated?: boolean; totalSourceRows?: number };
212
+ extraMeta?: { sqlPreview?: string; sourceType?: string };
213
+ }
214
+
215
+ /**
216
+ * Resolves data from one of three sources: sourceId+sql, resultId, or inline data.
217
+ * Returns the resolved data or an error response.
218
+ */
219
+ export async function resolveData(
220
+ args: { data?: Record<string, any>[]; resultId?: string; sourceId?: string; sql?: string },
221
+ deps: { sourceManager?: any; getResult: (id: string) => { rows: Record<string, any>[]; columns: { name: string; type: string }[] } | null },
222
+ ): Promise<ResolvedData | McpResponse> {
223
+ let data = args.data;
224
+ let queryMeta: ResolvedData['queryMeta'];
225
+ let extraMeta: ResolvedData['extraMeta'];
226
+
227
+ if (args.sourceId && args.sql) {
228
+ if (!deps.sourceManager) {
229
+ return errorResponse('Source manager not available.');
230
+ }
231
+ const source = deps.sourceManager.get?.(args.sourceId);
232
+ const sourceType = source?.type;
233
+
234
+ const result = await deps.sourceManager.querySql(args.sourceId, args.sql);
235
+ if (!result.ok) {
236
+ return errorResponse(result.error);
237
+ }
238
+ data = result.rows;
239
+ queryMeta = { truncated: result.truncated, totalSourceRows: result.totalRows };
240
+ extraMeta = { sqlPreview: args.sql.slice(0, 200), sourceType };
241
+ }
242
+
243
+ if (!data && args.resultId) {
244
+ const cached = deps.getResult(args.resultId);
245
+ if (!cached) {
246
+ return errorResponse(`Result "${args.resultId}" not found or expired. Re-run query_data to get a new resultId.`);
247
+ }
248
+ data = cached.rows;
249
+ }
250
+
251
+ if (!data || data.length === 0) {
252
+ return errorResponse('No data provided. Pass data array, resultId from query_data, or sourceId + sql.');
253
+ }
254
+
255
+ return { data, queryMeta, extraMeta };
256
+ }
257
+
258
+ /** Type guard: checks if a resolveData result is an error response. */
259
+ export function isErrorResponse(result: ResolvedData | McpResponse): result is McpResponse {
260
+ return 'content' in result && 'isError' in result;
261
+ }
262
+
263
+ // ─── TRANSFORM TOOL HELPERS ─────────────────────────────────────────────────
264
+
265
+ export interface TransformContext {
266
+ source: any;
267
+ db: any;
268
+ table: any;
269
+ }
270
+
271
+ /**
272
+ * Shared setup for all transform tools: connect to source, get database handle,
273
+ * validate table exists. Returns either the context or an error response.
274
+ */
275
+ export async function connectAndValidateTable(
276
+ deps: { sourceManager: any },
277
+ sourceId: string,
278
+ tableName: string,
279
+ ): Promise<TransformContext | McpResponse> {
280
+ const connResult = await deps.sourceManager.connect(sourceId);
281
+ if (!connResult.ok) {
282
+ return errorResponse(`Source not found: ${sourceId}`);
283
+ }
284
+
285
+ const source = connResult.source!;
286
+ const db = source.getDatabase?.();
287
+ if (!db) {
288
+ return errorResponse('Source does not support transforms (no database handle)');
289
+ }
290
+
291
+ const schema = await source.getSchema();
292
+ const table = schema.tables.find((t: any) => t.name === tableName);
293
+ if (!table) {
294
+ const available = schema.tables.map((t: any) => t.name);
295
+ return errorResponse(`Table '${tableName}' not found. Available: [${available.join(', ')}]`);
296
+ }
297
+
298
+ return { source, db, table };
299
+ }
300
+
301
+ /** Type guard: checks if a connectAndValidateTable result is an error response. */
302
+ export function isTransformError(result: TransformContext | McpResponse): result is McpResponse {
303
+ return 'content' in result;
304
+ }
305
+
@@ -20,7 +20,6 @@ export function isSandboxPath(filePath: string): boolean {
20
20
  export const addSourceInputSchema = z.object({
21
21
  name: z.string().describe('Name for this dataset'),
22
22
  path: z.string().describe('Path to a CSV file or directory of CSV files'),
23
- detail: z.enum(['compact', 'full']).default('compact').describe('Schema detail level: "compact" (default) returns just column names/types + row counts; "full" includes stats, top values, and sample rows'),
24
23
  });
25
24
 
26
25
  export const removeSourceInputSchema = z.object({
@@ -33,7 +32,7 @@ export const describeSourceInputSchema = z.object({
33
32
  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'),
34
33
  });
35
34
 
36
- /** Build a table profile from schema table + connected source */
35
+ /** Build a table profile from schema table + connected source (for describe_data) */
37
36
  async function buildTableProfile(t: any, connectedSource: any, detail: 'compact' | 'full' = 'full') {
38
37
  if (detail === 'compact') {
39
38
  return {
@@ -61,6 +60,56 @@ async function buildTableProfile(t: any, connectedSource: any, detail: 'compact'
61
60
  };
62
61
  }
63
62
 
63
+ /**
64
+ * Build a smart summary for load_csv — minimal tokens but enough to write SQL.
65
+ * - Categorical columns (≤20 unique): list the values
66
+ * - Categorical columns (>20 unique): just show count
67
+ * - Numeric columns: show min/max range
68
+ * - Text/ID columns: just name and type
69
+ */
70
+ function buildSmartSummary(t: any): string {
71
+ const lines: string[] = [];
72
+ lines.push(`${t.name}: ${t.rowCount.toLocaleString()} rows`);
73
+ lines.push('');
74
+
75
+ for (const c of t.columns) {
76
+ const { name, type, uniqueCount, stats, topValues } = c;
77
+
78
+ if (type === 'numeric' || type === 'integer') {
79
+ // Numeric: show range
80
+ if (stats && stats.min !== undefined && stats.max !== undefined) {
81
+ lines.push(`- ${name} (${type}): ${stats.min} – ${stats.max}`);
82
+ } else {
83
+ lines.push(`- ${name} (${type})`);
84
+ }
85
+ } else if (type === 'date' || type === 'datetime') {
86
+ // Date: show range if available
87
+ if (stats && stats.min !== undefined && stats.max !== undefined) {
88
+ lines.push(`- ${name} (${type}): ${stats.min} – ${stats.max}`);
89
+ } else {
90
+ lines.push(`- ${name} (${type})`);
91
+ }
92
+ } else if (topValues && topValues.length > 0) {
93
+ // Categorical: list values if ≤20, otherwise show count
94
+ if (uniqueCount && uniqueCount <= 20) {
95
+ const vals = topValues.map((tv: any) => tv.value).join(', ');
96
+ lines.push(`- ${name} (${uniqueCount} values): ${vals}`);
97
+ } else if (uniqueCount) {
98
+ lines.push(`- ${name} (${uniqueCount} unique)`);
99
+ } else {
100
+ lines.push(`- ${name} (text)`);
101
+ }
102
+ } else if (type === 'id') {
103
+ lines.push(`- ${name} (id)`);
104
+ } else {
105
+ // Fallback: just name and type
106
+ lines.push(`- ${name} (${type})`);
107
+ }
108
+ }
109
+
110
+ return lines.join('\n');
111
+ }
112
+
64
113
  export function handleListSources(deps: { sourceManager: any }) {
65
114
  return async () => jsonResponse(deps.sourceManager.list());
66
115
  }
@@ -106,21 +155,16 @@ export function handleAddSource(deps: { sourceManager: any }) {
106
155
  const schemaResult = await deps.sourceManager.getSchema(entry.id);
107
156
  const schema = schemaResult.ok ? schemaResult.schema : null;
108
157
 
109
- const connResult = await deps.sourceManager.connect(entry.id);
110
- const connectedSource = connResult.ok ? connResult.source : null;
111
-
112
- const tables = await Promise.all(
113
- (schema?.tables ?? []).map((t: any) => buildTableProfile(t, connectedSource, args.detail))
114
- );
115
-
116
158
  const tableCount = schema?.tables.length ?? 0;
117
159
  const verb = reconnected ? 'Reconnected' : 'Loaded';
118
160
 
161
+ // Build smart summaries for each table (minimal tokens, enough to write SQL)
162
+ const summaries = (schema?.tables ?? []).map((t: any) => buildSmartSummary(t));
163
+
119
164
  return jsonResponse({
120
165
  sourceId: entry.id,
121
- name: entry.name,
122
- tables,
123
- message: `${verb} "${args.name}" — ${tableCount} tables found`,
166
+ summary: summaries.join('\n\n'),
167
+ message: `${verb} "${args.name}" — ${tableCount} table${tableCount === 1 ? '' : 's'}. Use describe_data for full column stats.`,
124
168
  });
125
169
  };
126
170
  }
@@ -5,66 +5,43 @@
5
5
  * Supports single-column and batch modes.
6
6
  */
7
7
  import type { z } from 'zod';
8
- import { errorResponse, jsonResponse } from './shared.js';
8
+ import { errorResponse, jsonResponse, connectAndValidateTable, isTransformError } from './shared.js';
9
9
  import type { transformDataSchema } from './transform-schemas.js';
10
10
  import { TransformMetadata } from '../../transforms/metadata.js';
11
11
  import { executeSingleTransform, executeBatchTransform } from '../../transforms/pipeline.js';
12
- import { ColumnManager } from '../../transforms/column-manager.js';
13
12
 
14
13
  export function handleTransformData(deps: { sourceManager: any }) {
15
14
  return async (args: z.infer<typeof transformDataSchema>) => {
16
- const connResult = await deps.sourceManager.connect(args.sourceId);
17
- if (!connResult.ok) {
18
- return errorResponse(`Source not found: ${args.sourceId}`);
19
- }
20
-
21
- const source = connResult.source!;
22
- const db = source.getDatabase?.();
23
- if (!db) {
24
- return errorResponse('Source does not support transforms (no database handle)');
25
- }
26
-
27
- const schema = await source.getSchema();
28
- const table = schema.tables.find((t: any) => t.name === args.table);
29
- if (!table) {
30
- const available = schema.tables.map((t: any) => t.name);
31
- return errorResponse(`Table '${args.table}' not found. Available: [${available.join(', ')}]`);
32
- }
15
+ const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
16
+ if (isTransformError(ctx)) return ctx;
33
17
 
34
- const metadata = new TransformMetadata(db);
18
+ const metadata = new TransformMetadata(ctx.db);
35
19
  metadata.init();
36
20
 
37
- // Source columns = schema columns minus any transform-tracked columns.
38
- // After schema invalidation, derived columns appear in the schema for DSL
39
- // validation, but they're not source columns for collision detection.
40
21
  const transformedNames = new Set(metadata.list(args.table).map(r => r.column));
41
- const sourceColumns = table.columns.map((c: any) => c.name).filter((n: string) => !transformedNames.has(n));
22
+ const sourceColumns = ctx.table.columns.map((c: any) => c.name).filter((n: string) => !transformedNames.has(n));
42
23
 
43
24
  try {
44
- let result;
45
- if (args.transforms) {
46
- result = executeBatchTransform(db, metadata, {
47
- sourceId: args.sourceId,
48
- table: args.table,
49
- transforms: args.transforms,
50
- type: args.type,
51
- filter: args.filter,
52
- partitionBy: args.partitionBy,
53
- }, sourceColumns);
54
- } else {
55
- result = executeSingleTransform(db, metadata, {
56
- sourceId: args.sourceId,
57
- table: args.table,
58
- create: args.create!,
59
- expr: args.expr!,
60
- type: args.type,
61
- filter: args.filter,
62
- partitionBy: args.partitionBy,
63
- }, sourceColumns);
64
- }
25
+ const result = args.transforms
26
+ ? executeBatchTransform(ctx.db, metadata, {
27
+ sourceId: args.sourceId,
28
+ table: args.table,
29
+ transforms: args.transforms,
30
+ type: args.type,
31
+ filter: args.filter,
32
+ partitionBy: args.partitionBy,
33
+ }, sourceColumns)
34
+ : executeSingleTransform(ctx.db, metadata, {
35
+ sourceId: args.sourceId,
36
+ table: args.table,
37
+ create: args.create!,
38
+ expr: args.expr!,
39
+ type: args.type,
40
+ filter: args.filter,
41
+ partitionBy: args.partitionBy,
42
+ }, sourceColumns);
65
43
 
66
- // Invalidate cached schema so DSL queries can see the new columns
67
- source.invalidateSchema?.();
44
+ ctx.source.invalidateSchema?.();
68
45
 
69
46
  return jsonResponse({
70
47
  created: result.created.map(c => ({