@outsidedata/dolex 8.0.2 → 9.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 (84) hide show
  1. package/README.md +33 -7
  2. package/dist/src/analysis/clean-exec.d.ts +23 -0
  3. package/dist/src/analysis/clean-exec.js +87 -0
  4. package/dist/src/analysis/data-context.d.ts +140 -0
  5. package/dist/src/analysis/data-context.js +96 -0
  6. package/dist/src/analysis/planner.d.ts +2 -1
  7. package/dist/src/analysis/planner.js +2 -2
  8. package/dist/src/analysis/quality.d.ts +23 -0
  9. package/dist/src/analysis/quality.js +386 -11
  10. package/dist/src/analysis/rules.d.ts +22 -2
  11. package/dist/src/analysis/rules.js +100 -18
  12. package/dist/src/cleaning/author.d.ts +30 -0
  13. package/dist/src/cleaning/author.js +7 -0
  14. package/dist/src/cleaning/exec.d.ts +29 -0
  15. package/dist/src/cleaning/exec.js +161 -0
  16. package/dist/src/cleaning/handlers.d.ts +16 -0
  17. package/dist/src/cleaning/handlers.js +82 -0
  18. package/dist/src/cleaning/index.d.ts +4 -0
  19. package/dist/src/cleaning/index.js +9 -0
  20. package/dist/src/cleaning/manifest.d.ts +35 -0
  21. package/dist/src/cleaning/manifest.js +95 -0
  22. package/dist/src/cleaning/replay.d.ts +34 -0
  23. package/dist/src/cleaning/replay.js +58 -0
  24. package/dist/src/cli/commands/analyze.js +13 -1
  25. package/dist/src/cli/commands/check.js +2 -89
  26. package/dist/src/cli/commands/clean.d.ts +1 -0
  27. package/dist/src/cli/commands/clean.js +127 -0
  28. package/dist/src/cli/commands/deps.d.ts +1 -0
  29. package/dist/src/cli/commands/deps.js +41 -0
  30. package/dist/src/cli/commands/help.js +3 -1
  31. package/dist/src/cli/commands/query.js +4 -1
  32. package/dist/src/cli/commands/sources.d.ts +2 -2
  33. package/dist/src/cli/commands/sources.js +138 -12
  34. package/dist/src/cli/commands/transform.js +19 -4
  35. package/dist/src/cli/commands/visualize.js +2 -0
  36. package/dist/src/cli/index.js +5 -0
  37. package/dist/src/connectors/csv.js +110 -8
  38. package/dist/src/connectors/index.d.ts +2 -0
  39. package/dist/src/connectors/index.js +2 -0
  40. package/dist/src/connectors/manager.d.ts +49 -1
  41. package/dist/src/connectors/manager.js +200 -14
  42. package/dist/src/connectors/mongo/index.d.ts +13 -0
  43. package/dist/src/connectors/mongo/index.js +323 -0
  44. package/dist/src/connectors/pg/index.d.ts +2 -0
  45. package/dist/src/connectors/pg/index.js +248 -0
  46. package/dist/src/connectors/source-factory.d.ts +38 -0
  47. package/dist/src/connectors/source-factory.js +80 -0
  48. package/dist/src/connectors/sql-safety.d.ts +68 -0
  49. package/dist/src/connectors/sql-safety.js +167 -0
  50. package/dist/src/connectors/types.d.ts +51 -0
  51. package/dist/src/connectors/types.js +11 -1
  52. package/dist/src/mcp/index.d.ts +1 -1
  53. package/dist/src/mcp/index.js +29 -10
  54. package/dist/src/mcp/tools/analyze.js +11 -1
  55. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  56. package/dist/src/mcp/tools/capabilities.js +14 -0
  57. package/dist/src/mcp/tools/clean-column.d.ts +5 -0
  58. package/dist/src/mcp/tools/clean-column.js +47 -0
  59. package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
  60. package/dist/src/mcp/tools/clean-schemas.js +9 -0
  61. package/dist/src/mcp/tools/drop-columns.js +2 -0
  62. package/dist/src/mcp/tools/list-transforms.js +22 -0
  63. package/dist/src/mcp/tools/promote-columns.js +2 -0
  64. package/dist/src/mcp/tools/query-source.d.ts +2 -2
  65. package/dist/src/mcp/tools/query-source.js +2 -1
  66. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  67. package/dist/src/mcp/tools/refine.d.ts +4 -4
  68. package/dist/src/mcp/tools/shared.d.ts +6 -0
  69. package/dist/src/mcp/tools/shared.js +12 -5
  70. package/dist/src/mcp/tools/sources.d.ts +46 -3
  71. package/dist/src/mcp/tools/sources.js +44 -4
  72. package/dist/src/mcp/tools/transform-data.js +22 -0
  73. package/dist/src/mcp/tools/visualize-cli.d.ts +2 -2
  74. package/dist/src/mcp/tools/visualize.d.ts +3 -2
  75. package/dist/src/mcp/tools/visualize.js +1 -0
  76. package/dist/src/transforms/evaluator.js +58 -3
  77. package/dist/src/transforms/tokenizer.js +20 -2
  78. package/dist/src/transforms/types.d.ts +6 -6
  79. package/dist/src/types.d.ts +39 -2
  80. package/dist/src/utils/capabilities.d.ts +28 -0
  81. package/dist/src/utils/capabilities.js +58 -0
  82. package/dist/src/utils/optional-deps.d.ts +8 -0
  83. package/dist/src/utils/optional-deps.js +8 -0
  84. package/package.json +9 -3
@@ -1,4 +1,14 @@
1
1
  /**
2
2
  * Connector-specific types for Dolex data source connectors.
3
3
  */
4
- export {};
4
+ /**
5
+ * Reflect a session-derived column in a connector's cached schema, so downstream consumers
6
+ * (schemaText, describe_data) see it. Shared by the live connectors' applyDerivation
7
+ * (Postgres shadow view / Mongo $set) — idempotent; a no-op if the column already exists.
8
+ */
9
+ export function registerDerivedColumn(schema, table, column) {
10
+ const t = schema.tables.find((tt) => tt.name === table);
11
+ if (t && !t.columns.find((cc) => cc.name === column)) {
12
+ t.columns.push({ name: column, type: 'text', sampleValues: [], uniqueCount: 0, nullCount: 0, totalCount: t.rowCount, layer: 'derived' });
13
+ }
14
+ }
@@ -9,7 +9,7 @@
9
9
  * visualize — Data (inline, cached, or CSV+SQL) + intent → ranked visualization recommendations
10
10
  * list_patterns — Browse all available visualization patterns
11
11
  * refine_visualization — Tweak a visualization spec
12
- * load_csv — Load a CSV file or directory
12
+ * load_source — Load a CSV / Postgres / MongoDB source
13
13
  * list_data — List loaded datasets
14
14
  * remove_data — Remove a loaded dataset
15
15
  * describe_data — Re-examine column profiles and sample rows for a dataset
@@ -9,7 +9,7 @@
9
9
  * visualize — Data (inline, cached, or CSV+SQL) + intent → ranked visualization recommendations
10
10
  * list_patterns — Browse all available visualization patterns
11
11
  * refine_visualization — Tweak a visualization spec
12
- * load_csv — Load a CSV file or directory
12
+ * load_source — Load a CSV / Postgres / MongoDB source
13
13
  * list_data — List loaded datasets
14
14
  * remove_data — Remove a loaded dataset
15
15
  * describe_data — Re-examine column profiles and sample rows for a dataset
@@ -32,11 +32,12 @@ import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE, } from '@mode
32
32
  import { visualizeInputSchema, handleVisualize } from './tools/visualize.js';
33
33
  import { handleListPatterns } from './tools/list-patterns.js';
34
34
  import { refineInputSchema, handleRefine } from './tools/refine.js';
35
- import { addSourceInputSchema, removeSourceInputSchema, describeSourceInputSchema, handleListSources, handleAddSource, handleRemoveSource, handleDescribeSource, } from './tools/sources.js';
35
+ import { addSourceInputSchema, removeSourceInputSchema, describeSourceInputSchema, testSourceInputSchema, handleListSources, handleAddSource, handleRemoveSource, handleDescribeSource, handleTestSource, } from './tools/sources.js';
36
36
  import { analyzeSourceInputSchema, handleAnalyzeSource } from './tools/analyze.js';
37
37
  import { querySourceInputSchema, handleQuerySource } from './tools/query-source.js';
38
38
  import { clearCacheInputSchema, handleServerStatus, handleClearCache, } from './tools/server-privacy.js';
39
39
  import { exportHtmlInputSchema, handleExportHtml } from './tools/export-html.js';
40
+ import { handleCapabilities } from './tools/capabilities.js';
40
41
  import { screenshotInputSchema, handleScreenshot, closeBrowser } from './tools/screenshot.js';
41
42
  import { visualizeCliInputSchema, handleVisualizeCli } from './tools/visualize-cli.js';
42
43
  import { refineCliInputSchema, handleRefineCli } from './tools/refine-cli.js';
@@ -45,6 +46,8 @@ import { handleTransformData } from './tools/transform-data.js';
45
46
  import { handlePromoteColumns } from './tools/promote-columns.js';
46
47
  import { handleListTransforms } from './tools/list-transforms.js';
47
48
  import { handleDropColumns } from './tools/drop-columns.js';
49
+ import { cleanColumnSchema } from './tools/clean-schemas.js';
50
+ import { handleCleanColumn } from './tools/clean-column.js';
48
51
  import { specStore } from './spec-store.js';
49
52
  import { mkdirSync, readFileSync } from 'fs';
50
53
  import { join } from 'path';
@@ -79,9 +82,10 @@ const server = new McpServer({
79
82
  "You are a data analyst working on the user's own CSV files: rigorous column profiling, data-quality auditing, a prioritized analysis plan, and findings rendered across 43 chart types as artifacts they keep.",
80
83
  '',
81
84
  'WORKFLOW:',
82
- '• Got a CSV file? → load_csv(name, path) — returns smart summary (column names, types, ranges, categorical values)',
85
+ '• Got a CSV file, Postgres, or MongoDB? → load_source(name, type, path|uri|host+database) — returns smart summary (column names, types, ranges, categorical values)',
86
+ '• For a Postgres/MongoDB source, call capabilities first to confirm its driver is installed here; if not, it tells the user the exact command (e.g. `npm install pg`). Loading a source whose driver is missing returns that same install message, never a crash.',
83
87
  '• Got inline data? → visualize(data, intent) directly',
84
- '• Need to explore? → load_csv → analyze_data → visualize(sourceId, sql, intent) per step',
88
+ '• Need to explore? → load_source → analyze_data → visualize(sourceId, sql, intent) per step',
85
89
  '',
86
90
  'CONTINUATION (dataset already loaded):',
87
91
  '• Chart from data → visualize(sourceId, sql, intent)',
@@ -92,10 +96,11 @@ const server = new McpServer({
92
96
  '• specId expired? → re-run the original visualize call, then continue refining from the new specId',
93
97
  '',
94
98
  'TOOL GUIDE:',
95
- '• load_csv: Load CSV. Returns sourceId + smart summary (columns, types, ranges, categorical values) — enough to write SQL.',
99
+ '• load_source: Load a CSV / Postgres / MongoDB source. Returns sourceId + smart summary (columns, types, ranges, categorical values) — enough to query.',
96
100
  '• describe_data: Full column stats, top values, sample rows. Call only when you need deep exploration.',
97
101
  '• analyze_data: Auto-generate analysis plan with ready SQL queries. Execute each step with visualize; present results one at a time.',
98
102
  '• query_data: Run SQL query, get rows. Returns resultId for visualize().',
103
+ '• clean_column: Clean one column with a Python clean(value) you write — parse messy dates, null sentinels, canonicalize categories. Preview first, then apply:true writes a non-destructive <column>_clean. (Requires python3.)',
99
104
  '• visualize: Chart data. Pass inline data array, resultId from query_data, or sourceId + sql for server-side query. Matches a chart to the shape of the data. Set title/subtitle here to avoid a refine round-trip.',
100
105
  '• refine_visualization: Tweak a chart — sort, limit, filter, palette, highlight, flip, title, format. Each call returns a new specId.',
101
106
  '• list_patterns: Browse available chart types. Only needed when the user asks what charts are available or you need a pattern ID.',
@@ -144,9 +149,9 @@ registerAppTool(server, 'refine_visualization', {
144
149
  },
145
150
  }, handleRefine());
146
151
  // CSV data management tools
147
- server.registerTool('load_csv', {
148
- title: 'Load CSV Data',
149
- description: 'Load a CSV file or directory. Datasets persist across restarts.\nReturns sourceId + smart summary: column names, types, numeric ranges, categorical values.\nThis gives you enough to write SQL. Call describe_data only if you need full stats.',
152
+ server.registerTool('load_source', {
153
+ title: 'Load a data source',
154
+ description: 'Load a data source: a CSV file/directory (type "csv" + path), a live Postgres database (type "postgres" + uri or host/database/user), or a MongoDB database (type "mongodb" + uri/host + database). Type defaults to "csv". Datasets persist across restarts.\nReturns sourceId + smart summary: column names, types, numeric ranges, categorical values.\nThis gives you enough to query. Call describe_data only if you need full stats.',
150
155
  inputSchema: addSourceInputSchema,
151
156
  }, handleAddSource({ sourceManager }));
152
157
  server.registerTool('list_data', {
@@ -160,7 +165,7 @@ server.registerTool('remove_data', {
160
165
  }, handleRemoveSource({ sourceManager }));
161
166
  server.registerTool('describe_data', {
162
167
  title: 'Describe Data',
163
- description: 'Full column profiles: stats (min/max/mean/median), top values with counts, sample rows.\nUse only when you need deep exploration — load_csv already gives you enough to write SQL.',
168
+ description: 'Full column profiles: stats (min/max/mean/median), top values with counts, sample rows.\nUse only when you need deep exploration — load_source already gives you enough to query.',
164
169
  inputSchema: describeSourceInputSchema,
165
170
  }, handleDescribeSource({ sourceManager }));
166
171
  server.registerTool('analyze_data', {
@@ -170,7 +175,7 @@ server.registerTool('analyze_data', {
170
175
  }, handleAnalyzeSource({ sourceManager }));
171
176
  server.registerTool('query_data', {
172
177
  title: 'Query Data',
173
- 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().',
178
+ description: 'Run a SQL query on a loaded dataset. JOINs, GROUP BY, window functions, CTEs.\nCustom aggregates: MEDIAN, STDDEV, CV, MAD, P1/P5/P10/P25/P75/P90/P95/P99.\nReturns resultId for visualize().',
174
179
  inputSchema: querySourceInputSchema,
175
180
  }, handleQuerySource({ sourceManager }));
176
181
  // Derived data layer tools
@@ -194,12 +199,26 @@ server.registerTool('drop_columns', {
194
199
  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.',
195
200
  inputSchema: dropColumnsSchema.shape,
196
201
  }, handleDropColumns({ sourceManager }));
202
+ server.registerTool('clean_column', {
203
+ title: 'Clean Column',
204
+ description: 'Clean one column by writing a Python `def clean(value):` function (you author it, the server runs it — the Python sibling of query_data). PREVIEW first (apply omitted/false): validates the fix and returns before→after stats + a sample WITHOUT writing. Then call again with apply:true to write a NEW column (<column>_clean) — NON-DESTRUCTIVE, the original column is kept.\n\nWHEN TO USE: after describe_data or the data-quality audit flags a column (a sentinel value, a mixed-type column, messy categories). Use it for fixes the SQL expression language can\'t do: parse a non-ISO date (datetime.strptime → ISO), null a sentinel (return None for "None"/"Undrafted"/999999), canonicalize a messy category (value.strip().lower()). NOTE: value arrives as a string (or None) — cast before numeric work.\n\nRequires python3 on PATH. Executes the Python you provide — same trust model as the SQL you pass to query_data.',
205
+ inputSchema: cleanColumnSchema.shape,
206
+ }, handleCleanColumn({ sourceManager }));
197
207
  // Privacy / cache management tools
198
208
  const privacyDeps = { sourceManager, serverStartTime };
199
209
  server.registerTool('server_status', {
200
210
  title: 'Server Status',
201
211
  description: 'Inspect cached specs, query results, connected sources, and uptime.',
202
212
  }, handleServerStatus(privacyDeps));
213
+ server.registerTool('capabilities', {
214
+ title: 'Environment Capabilities',
215
+ description: 'What this Dolex install can do here: which source types are ready (CSV always; Postgres/MongoDB only if their optional driver is installed), whether python3 is present (for clean_column), and the exact command to enable anything missing. Call this before loading a Postgres/Mongo source so you can tell the user how to install a missing driver instead of hitting an error.',
216
+ }, handleCapabilities());
217
+ server.registerTool('test_source', {
218
+ title: 'Test a Source',
219
+ description: 'Health-check a registered Postgres/Mongo source: is its saved database reachable with its credentials? Returns a classified reason (unreachable / auth-failed / db-not-found / driver-missing) so you can tell the user exactly what to fix. A source can be registered even while its DB is down — use this to confirm it once it is up.',
220
+ inputSchema: testSourceInputSchema,
221
+ }, handleTestSource({ sourceManager }));
203
222
  server.registerTool('clear_cache', {
204
223
  title: 'Clear Cache',
205
224
  description: 'Clear cached data from memory. Scope: "all" (specs + results), "specs" (visualization specs), "results" (query cache). Use after working with sensitive data.',
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { z } from 'zod';
6
6
  import { buildAnalysisPlan } from '../../analysis/planner.js';
7
+ import { plannerDialectForSource, PlannerUnsupportedSourceError } from '../../analysis/rules.js';
7
8
  import { errorResponse, jsonResponse } from './shared.js';
8
9
  export const analyzeSourceInputSchema = z.object({
9
10
  sourceId: z.string().describe('Dataset ID returned by load_csv'),
@@ -27,7 +28,16 @@ export function handleAnalyzeSource(deps) {
27
28
  : 'No tables found in source';
28
29
  return errorResponse(message);
29
30
  }
30
- const plan = buildAnalysisPlan(targetTable.columns, targetTable.name, schemaResult.schema.source?.name ?? args.sourceId, args.maxSteps ?? 6);
31
+ let dialect;
32
+ try {
33
+ dialect = plannerDialectForSource(schemaResult.schema.source?.type);
34
+ }
35
+ catch (err) {
36
+ if (err instanceof PlannerUnsupportedSourceError)
37
+ return errorResponse(err.message);
38
+ throw err;
39
+ }
40
+ const plan = buildAnalysisPlan(targetTable.columns, targetTable.name, schemaResult.schema.source?.name ?? args.sourceId, args.maxSteps ?? 6, dialect);
31
41
  return jsonResponse(plan);
32
42
  };
33
43
  }
@@ -0,0 +1 @@
1
+ export declare function handleCapabilities(): () => Promise<import("./shared.js").McpResponse>;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * MCP Tool: capabilities — what can Dolex do in THIS environment.
3
+ *
4
+ * An AI assistant calls this once to discover which source types are ready (CSV always; Postgres /
5
+ * MongoDB only if their optional driver is installed) and what to run to enable the rest, so it can
6
+ * drive Dolex within the available capabilities instead of attempting a source and hitting an error.
7
+ * Pairs with the connectors' graceful failure: an unavailable source, if attempted anyway, returns
8
+ * the same actionable "npm install …" message rather than a crash.
9
+ */
10
+ import { jsonResponse } from './shared.js';
11
+ import { probeCapabilities } from '../../utils/capabilities.js';
12
+ export function handleCapabilities() {
13
+ return async () => jsonResponse(probeCapabilities());
14
+ }
@@ -0,0 +1,5 @@
1
+ import type { z } from 'zod';
2
+ import type { cleanColumnSchema } from './clean-schemas.js';
3
+ export declare function handleCleanColumn(deps: {
4
+ sourceManager: any;
5
+ }): (args: z.infer<typeof cleanColumnSchema>) => Promise<import("./shared.js").McpResponse>;
@@ -0,0 +1,47 @@
1
+ import { connectAndValidateTable, isTransformError, errorResponse, jsonResponse } from './shared.js';
2
+ import { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn } from '../../cleaning/exec.js';
3
+ const q = (s) => `"${s.replace(/"/g, '""')}"`;
4
+ export function handleCleanColumn(deps) {
5
+ return async (args) => {
6
+ const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
7
+ if (isTransformError(ctx))
8
+ return ctx;
9
+ if (!ctx.db)
10
+ return errorResponse(`clean_column runs a Python clean() over CSV-backed rows. On a live ${ctx.source.type} source, express the fix as a derived column via transform_data using a native ${ctx.source.type === 'mongodb' ? 'aggregation ($set) expression' : 'SQL expression'} — non-destructive and server-side.`);
11
+ const colNames = ctx.table.columns.map((c) => c.name);
12
+ if (!colNames.includes(args.column))
13
+ return errorResponse(`Column '${args.column}' not found. Available: [${colNames.join(', ')}]`);
14
+ const newColumn = args.newColumn ?? `${args.column}_clean`;
15
+ if (colNames.includes(newColumn))
16
+ return errorResponse(`Column '${newColumn}' already exists. Pass a different newColumn or drop it first.`);
17
+ if (!pythonAvailable())
18
+ return errorResponse('clean_column requires python3 on PATH (not found). Install Python 3 to use this tool.');
19
+ const rows = ctx.db.prepare(`SELECT rowid AS __rid, ${q(args.column)} AS v FROM ${q(args.table)}`).all();
20
+ const rowids = rows.map((r) => r.__rid);
21
+ // Canonicalize blanks to null on the way IN: the CSV connector stores an empty cell as ''
22
+ // but treats '' as missing everywhere else, so clean(value) sees None for an empty cell.
23
+ const raw = rows.map((r) => (r.v === null || r.v === '' ? null : String(r.v)));
24
+ let cleaned;
25
+ let errors;
26
+ try {
27
+ ({ cleaned, errors } = runPythonClean(args.code, raw));
28
+ }
29
+ catch (e) {
30
+ return errorResponse(`clean() failed to run: ${e?.message ?? String(e)}`);
31
+ }
32
+ // Canonicalize blanks to null on the way OUT too, so stats/preview report exactly what
33
+ // applyCleanColumn writes (it stores '' as NULL). One canonical form across the pipeline.
34
+ cleaned = cleaned.map((v) => (v === '' ? null : v));
35
+ const stats = { ...cleanStats(raw, cleaned), errors };
36
+ const safety = safetyVerdict(raw, cleaned, errors);
37
+ const sample = previewSample(raw, cleaned, 20);
38
+ if (!safety.ok)
39
+ return errorResponse(`clean() rejected: ${safety.reason}. (nothing was applied)`);
40
+ if (!args.apply) {
41
+ return jsonResponse({ preview: true, column: args.column, newColumn, stats, sample, note: 'Preview only — pass apply:true to write the cleaned column (non-destructive; original kept).' });
42
+ }
43
+ applyCleanColumn(ctx.db, args.table, newColumn, rowids, cleaned);
44
+ ctx.source.invalidateSchema?.();
45
+ return jsonResponse({ applied: true, column: args.column, newColumn, stats, sample });
46
+ };
47
+ }
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ export declare const cleanColumnSchema: z.ZodObject<{
3
+ sourceId: z.ZodString;
4
+ table: z.ZodString;
5
+ column: z.ZodString;
6
+ code: z.ZodString;
7
+ newColumn: z.ZodOptional<z.ZodString>;
8
+ apply: z.ZodOptional<z.ZodBoolean>;
9
+ }, "strip", z.ZodTypeAny, {
10
+ table: string;
11
+ code: string;
12
+ column: string;
13
+ sourceId: string;
14
+ newColumn?: string | undefined;
15
+ apply?: boolean | undefined;
16
+ }, {
17
+ table: string;
18
+ code: string;
19
+ column: string;
20
+ sourceId: string;
21
+ newColumn?: string | undefined;
22
+ apply?: boolean | undefined;
23
+ }>;
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+ export const cleanColumnSchema = z.object({
3
+ sourceId: z.string().describe('Dataset ID returned by load_csv'),
4
+ table: z.string().describe('Table name within the source'),
5
+ column: z.string().describe('The column to clean'),
6
+ code: z.string().describe('A Python 3 function `def clean(value):` taking ONE raw cell value — ALWAYS a string, or None (cast it yourself with int()/float() before any numeric work) — and returning the cleaned value (None for missing/sentinel). May import stdlib (datetime, re). No I/O.'),
7
+ newColumn: z.string().optional().describe('Name for the cleaned column (default: <column>_clean). Non-destructive — the original column is kept.'),
8
+ apply: z.boolean().optional().describe('false (default) = PREVIEW (validate + show before→after, no write). true = write the cleaned column.'),
9
+ });
@@ -9,6 +9,8 @@ export function handleDropColumns(deps) {
9
9
  const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
10
10
  if (isTransformError(ctx))
11
11
  return ctx;
12
+ if (!ctx.db)
13
+ return errorResponse(`drop_columns manages CSV-side derived columns. On a live ${ctx.source.type} source, derived columns are session-local — end the session (or overwrite via transform_data) to discard them.`);
12
14
  const metadata = new TransformMetadata(ctx.db);
13
15
  metadata.init();
14
16
  const mgr = new ColumnManager(ctx.db);
@@ -6,6 +6,28 @@ export function handleListTransforms(deps) {
6
6
  const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
7
7
  if (isTransformError(ctx))
8
8
  return ctx;
9
+ // Live sources (Postgres/Mongo) have no SQLite handle. Their derived columns are
10
+ // session-local (created via transform_data) and surface in the introspected schema
11
+ // tagged layer:'derived'. List those from the schema instead of dereferencing a null
12
+ // db handle (which previously threw "Cannot read properties of undefined").
13
+ if (!ctx.db) {
14
+ const schema = await ctx.source.getSchema();
15
+ const tbl = schema.tables.find((t) => t.name === args.table);
16
+ const cols = tbl?.columns ?? [];
17
+ const derived = cols.filter((c) => c.layer === 'derived');
18
+ const sourceCols = cols.filter((c) => c.layer !== 'derived');
19
+ return jsonResponse({
20
+ source_columns: sourceCols.map((c) => c.name),
21
+ derived_columns: derived.map((c) => ({
22
+ column: c.name,
23
+ layer: 'derived',
24
+ note: 'session-local (created via transform_data); expression not tracked on a live source',
25
+ })),
26
+ working_columns: [],
27
+ total_columns: cols.length,
28
+ note: `Live ${ctx.source.type} source — derived columns are session-local to this connection and are not persisted (no working layer or manifest). Recreate them with transform_data.`,
29
+ });
30
+ }
9
31
  const metadata = new TransformMetadata(ctx.db);
10
32
  metadata.init();
11
33
  const mgr = new ColumnManager(ctx.db);
@@ -6,6 +6,8 @@ export function handlePromoteColumns(deps) {
6
6
  const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
7
7
  if (isTransformError(ctx))
8
8
  return ctx;
9
+ if (!ctx.db)
10
+ return errorResponse(`promote_columns persists derived columns to a CSV-side manifest. On a live ${ctx.source.type} source, derived columns are session-local (created with transform_data) and are not persisted — nothing to promote.`);
9
11
  const metadata = new TransformMetadata(ctx.db);
10
12
  metadata.init();
11
13
  let columnsToPromote;
@@ -8,12 +8,12 @@ export declare const querySourceInputSchema: z.ZodObject<{
8
8
  sql: z.ZodString;
9
9
  maxRows: z.ZodOptional<z.ZodNumber>;
10
10
  }, "strip", z.ZodTypeAny, {
11
- sourceId: string;
12
11
  sql: string;
12
+ sourceId: string;
13
13
  maxRows?: number | undefined;
14
14
  }, {
15
- sourceId: string;
16
15
  sql: string;
16
+ sourceId: string;
17
17
  maxRows?: number | undefined;
18
18
  }>;
19
19
  export declare function handleQuerySource(deps: {
@@ -8,7 +8,7 @@ import { errorResponse, jsonResponse } from './shared.js';
8
8
  import { logOperation } from './operation-log.js';
9
9
  export const querySourceInputSchema = z.object({
10
10
  sourceId: z.string().describe('Dataset ID returned by load_csv'),
11
- sql: z.string().describe('SQL SELECT query. Use table and column names from load_csv/describe_data. Supports JOINs, GROUP BY, HAVING, window functions, CTEs. Custom aggregates: MEDIAN, STDDEV, P25, P75, P10, P90.'),
11
+ sql: z.string().describe('SQL SELECT query. Use table and column names from load_csv/describe_data. Supports JOINs, GROUP BY, HAVING, window functions, CTEs. Custom aggregates: MEDIAN, STDDEV, CV (coeff. of variation), MAD (median abs. deviation), P1/P5/P10/P25/P75/P90/P95/P99.'),
12
12
  maxRows: z.number().optional().describe('Max rows to return (default: 10000)'),
13
13
  });
14
14
  export function handleQuerySource(deps) {
@@ -49,6 +49,7 @@ export function handleQuerySource(deps) {
49
49
  rows: result.rows,
50
50
  totalRows: result.totalRows,
51
51
  truncated: result.truncated ?? false,
52
+ ...(result.warnings?.length ? { warnings: result.warnings } : {}),
52
53
  queryTimeMs: Date.now() - start,
53
54
  });
54
55
  };
@@ -90,7 +90,7 @@ export declare const refineCliInputSchema: z.ZodObject<{
90
90
  direction: "asc" | "desc";
91
91
  field?: string | undefined;
92
92
  } | null | undefined;
93
- format?: "compact" | "integer" | "percent" | "dollar" | "decimal" | undefined;
93
+ format?: "compact" | "integer" | "decimal" | "percent" | "dollar" | undefined;
94
94
  colorField?: string | undefined;
95
95
  palette?: "categorical" | "blue" | "green" | "purple" | "warm" | "blueRed" | "greenPurple" | "tealOrange" | "redGreen" | "traffic-light" | "profit-loss" | "temperature" | undefined;
96
96
  filter?: {
@@ -98,9 +98,9 @@ export declare const refineCliInputSchema: z.ZodObject<{
98
98
  values: (string | number)[];
99
99
  op: "in" | "not_in" | "gt" | "gte" | "lt" | "lte";
100
100
  }[] | undefined;
101
+ limit?: number | undefined;
101
102
  layout?: "rows" | "columns" | undefined;
102
103
  subtitle?: string | undefined;
103
- limit?: number | undefined;
104
104
  flip?: boolean | undefined;
105
105
  xLabel?: string | undefined;
106
106
  yLabel?: string | undefined;
@@ -122,7 +122,7 @@ export declare const refineCliInputSchema: z.ZodObject<{
122
122
  direction: "asc" | "desc";
123
123
  field?: string | undefined;
124
124
  } | null | undefined;
125
- format?: "compact" | "integer" | "percent" | "dollar" | "decimal" | undefined;
125
+ format?: "compact" | "integer" | "decimal" | "percent" | "dollar" | undefined;
126
126
  colorField?: string | undefined;
127
127
  palette?: "categorical" | "blue" | "green" | "purple" | "warm" | "blueRed" | "greenPurple" | "tealOrange" | "redGreen" | "traffic-light" | "profit-loss" | "temperature" | undefined;
128
128
  filter?: {
@@ -130,9 +130,9 @@ export declare const refineCliInputSchema: z.ZodObject<{
130
130
  values: (string | number)[];
131
131
  op?: "=" | "!=" | "in" | "not_in" | "gt" | "gte" | "lt" | "lte" | undefined;
132
132
  }[] | undefined;
133
+ limit?: number | undefined;
133
134
  layout?: "rows" | "columns" | undefined;
134
135
  subtitle?: string | undefined;
135
- limit?: number | undefined;
136
136
  flip?: boolean | undefined;
137
137
  xLabel?: string | undefined;
138
138
  yLabel?: string | undefined;
@@ -77,7 +77,7 @@ export declare const refineInputSchema: z.ZodObject<{
77
77
  direction: "asc" | "desc";
78
78
  field?: string | undefined;
79
79
  } | null | undefined;
80
- format?: "compact" | "integer" | "percent" | "dollar" | "decimal" | undefined;
80
+ format?: "compact" | "integer" | "decimal" | "percent" | "dollar" | undefined;
81
81
  colorField?: string | undefined;
82
82
  palette?: "categorical" | "blue" | "green" | "purple" | "warm" | "blueRed" | "greenPurple" | "tealOrange" | "redGreen" | "traffic-light" | "profit-loss" | "temperature" | undefined;
83
83
  filter?: {
@@ -85,9 +85,9 @@ export declare const refineInputSchema: z.ZodObject<{
85
85
  values: (string | number)[];
86
86
  op: "in" | "not_in" | "gt" | "gte" | "lt" | "lte";
87
87
  }[] | undefined;
88
+ limit?: number | undefined;
88
89
  layout?: "rows" | "columns" | undefined;
89
90
  subtitle?: string | undefined;
90
- limit?: number | undefined;
91
91
  flip?: boolean | undefined;
92
92
  xLabel?: string | undefined;
93
93
  yLabel?: string | undefined;
@@ -108,7 +108,7 @@ export declare const refineInputSchema: z.ZodObject<{
108
108
  direction: "asc" | "desc";
109
109
  field?: string | undefined;
110
110
  } | null | undefined;
111
- format?: "compact" | "integer" | "percent" | "dollar" | "decimal" | undefined;
111
+ format?: "compact" | "integer" | "decimal" | "percent" | "dollar" | undefined;
112
112
  colorField?: string | undefined;
113
113
  palette?: "categorical" | "blue" | "green" | "purple" | "warm" | "blueRed" | "greenPurple" | "tealOrange" | "redGreen" | "traffic-light" | "profit-loss" | "temperature" | undefined;
114
114
  filter?: {
@@ -116,9 +116,9 @@ export declare const refineInputSchema: z.ZodObject<{
116
116
  values: (string | number)[];
117
117
  op?: "=" | "!=" | "in" | "not_in" | "gt" | "gte" | "lt" | "lte" | undefined;
118
118
  }[] | undefined;
119
+ limit?: number | undefined;
119
120
  layout?: "rows" | "columns" | undefined;
120
121
  subtitle?: string | undefined;
121
- limit?: number | undefined;
122
122
  flip?: boolean | undefined;
123
123
  xLabel?: string | undefined;
124
124
  yLabel?: string | undefined;
@@ -7,6 +7,7 @@
7
7
  * - Color preference application to visualization specs
8
8
  */
9
9
  import type { DataColumn, VisualizationSpec, CompoundVisualizationSpec } from '../../types.js';
10
+ import type { DerivationCapabilities } from '../../connectors/types.js';
10
11
  type McpTextContent = {
11
12
  type: 'text';
12
13
  text: string;
@@ -50,6 +51,7 @@ export interface ResolvedData {
50
51
  queryMeta?: {
51
52
  truncated?: boolean;
52
53
  totalSourceRows?: number;
54
+ warnings?: string[];
53
55
  };
54
56
  extraMeta?: {
55
57
  sqlPreview?: string;
@@ -79,8 +81,12 @@ export declare function resolveData(args: {
79
81
  export declare function isErrorResponse(result: ResolvedData | McpResponse): result is McpResponse;
80
82
  export interface TransformContext {
81
83
  source: any;
84
+ /** The raw SQLite handle — present only for the CSV/sqlite-alter materialization; undefined for
85
+ * a live source (PG/Mongo), which materializes via `source.applyDerivation`. */
82
86
  db: any;
83
87
  table: any;
88
+ /** The source's declared derivation contract (materialization / rowKey / server-side-queryable). */
89
+ caps: DerivationCapabilities;
84
90
  }
85
91
  /**
86
92
  * Shared setup for all transform tools: connect to source, get database handle,
@@ -211,7 +211,7 @@ export async function resolveData(args, deps) {
211
211
  return errorResponse(result.error);
212
212
  }
213
213
  data = result.rows;
214
- queryMeta = { truncated: result.truncated, totalSourceRows: result.totalRows };
214
+ queryMeta = { truncated: result.truncated, totalSourceRows: result.totalRows, warnings: result.warnings };
215
215
  extraMeta = { sqlPreview: args.sql.slice(0, 200), sourceType };
216
216
  }
217
217
  if (!data && args.resultId) {
@@ -240,10 +240,17 @@ export async function connectAndValidateTable(deps, sourceId, tableName) {
240
240
  return errorResponse(`Source not found: ${sourceId}`);
241
241
  }
242
242
  const source = connResult.source;
243
- const db = source.getDatabase?.();
244
- if (!db) {
245
- return errorResponse('Source does not support transforms (no database handle)');
243
+ // Source-agnostic derivation gate: the connector DECLARES whether/how it can derive a column
244
+ // (no longer a getDatabase-truthiness probe). A source that doesn't implement the seam is treated
245
+ // as non-deriving.
246
+ const caps = source.derivationCapabilities?.() ?? { canDerive: false, materialization: 'none', rowKey: null, serverSideQueryable: false };
247
+ if (!caps.canDerive) {
248
+ return errorResponse('Source does not support transforms');
246
249
  }
250
+ // CSV/sqlite-alter exposes a raw SQLite handle for the ALTER+rowid work; a live source (PG/Mongo)
251
+ // has no handle and materializes via source.applyDerivation. db may be undefined — each tool guards
252
+ // on what it needs (transform_data handles both; promote/drop/clean require the SQLite handle).
253
+ const db = source.getDatabase?.();
247
254
  let schema;
248
255
  try {
249
256
  schema = await source.getSchema();
@@ -256,7 +263,7 @@ export async function connectAndValidateTable(deps, sourceId, tableName) {
256
263
  const available = schema.tables.map((t) => t.name);
257
264
  return errorResponse(`Table '${tableName}' not found. Available: [${available.join(', ')}]`);
258
265
  }
259
- return { source, db, table };
266
+ return { source, db, table, caps };
260
267
  }
261
268
  /** Type guard: checks if a connectAndValidateTable result is an error response. */
262
269
  export function isTransformError(result) {
@@ -6,13 +6,43 @@ import { z } from 'zod';
6
6
  export declare function isSandboxPath(filePath: string): boolean;
7
7
  export declare const addSourceInputSchema: z.ZodObject<{
8
8
  name: z.ZodString;
9
- path: z.ZodString;
9
+ type: z.ZodOptional<z.ZodEnum<["csv", "postgres", "mongodb"]>>;
10
+ path: z.ZodOptional<z.ZodString>;
11
+ uri: z.ZodOptional<z.ZodString>;
12
+ host: z.ZodOptional<z.ZodString>;
13
+ port: z.ZodOptional<z.ZodNumber>;
14
+ database: z.ZodOptional<z.ZodString>;
15
+ user: z.ZodOptional<z.ZodString>;
16
+ password: z.ZodOptional<z.ZodString>;
17
+ passwordEnv: z.ZodOptional<z.ZodString>;
18
+ schema: z.ZodOptional<z.ZodString>;
19
+ collections: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
10
20
  }, "strip", z.ZodTypeAny, {
11
21
  name: string;
12
- path: string;
22
+ type?: "csv" | "postgres" | "mongodb" | undefined;
23
+ path?: string | undefined;
24
+ host?: string | undefined;
25
+ port?: number | undefined;
26
+ database?: string | undefined;
27
+ user?: string | undefined;
28
+ password?: string | undefined;
29
+ passwordEnv?: string | undefined;
30
+ schema?: string | undefined;
31
+ uri?: string | undefined;
32
+ collections?: string[] | undefined;
13
33
  }, {
14
34
  name: string;
15
- path: string;
35
+ type?: "csv" | "postgres" | "mongodb" | undefined;
36
+ path?: string | undefined;
37
+ host?: string | undefined;
38
+ port?: number | undefined;
39
+ database?: string | undefined;
40
+ user?: string | undefined;
41
+ password?: string | undefined;
42
+ passwordEnv?: string | undefined;
43
+ schema?: string | undefined;
44
+ uri?: string | undefined;
45
+ collections?: string[] | undefined;
16
46
  }>;
17
47
  export declare const removeSourceInputSchema: z.ZodObject<{
18
48
  sourceId: z.ZodString;
@@ -37,6 +67,19 @@ export declare const describeSourceInputSchema: z.ZodObject<{
37
67
  export declare function handleListSources(deps: {
38
68
  sourceManager: any;
39
69
  }): () => Promise<import("./shared.js").McpResponse>;
70
+ export declare const testSourceInputSchema: z.ZodObject<{
71
+ sourceId: z.ZodString;
72
+ }, "strip", z.ZodTypeAny, {
73
+ sourceId: string;
74
+ }, {
75
+ sourceId: string;
76
+ }>;
77
+ /** Connectivity health-check for a registered source — is the saved DB reachable with its credentials?
78
+ * Returns a classified kind (unreachable / auth-failed / db-not-found / driver-missing / …) so the
79
+ * assistant can give the user a specific fix, and repair via load_source (re-register) if needed. */
80
+ export declare function handleTestSource(deps: {
81
+ sourceManager: any;
82
+ }): (args: z.infer<typeof testSourceInputSchema>) => Promise<import("./shared.js").McpResponse>;
40
83
  export declare function handleAddSource(deps: {
41
84
  sourceManager: any;
42
85
  }): (args: z.infer<typeof addSourceInputSchema>) => Promise<import("./shared.js").McpResponse>;