@outsidedata/dolex 8.1.0 → 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.
- package/README.md +30 -7
- package/dist/src/analysis/planner.d.ts +2 -1
- package/dist/src/analysis/planner.js +2 -2
- package/dist/src/analysis/quality.js +96 -5
- package/dist/src/analysis/rules.d.ts +22 -2
- package/dist/src/analysis/rules.js +64 -23
- package/dist/src/cleaning/index.d.ts +2 -6
- package/dist/src/cleaning/index.js +8 -3
- package/dist/src/cleaning/replay.d.ts +34 -0
- package/dist/src/cleaning/replay.js +58 -0
- package/dist/src/cli/commands/analyze.js +13 -1
- package/dist/src/cli/commands/clean.js +15 -3
- package/dist/src/cli/commands/deps.d.ts +1 -0
- package/dist/src/cli/commands/deps.js +41 -0
- package/dist/src/cli/commands/help.js +2 -1
- package/dist/src/cli/commands/sources.d.ts +2 -2
- package/dist/src/cli/commands/sources.js +138 -12
- package/dist/src/cli/commands/transform.js +19 -4
- package/dist/src/cli/index.js +3 -0
- package/dist/src/connectors/csv.js +29 -0
- package/dist/src/connectors/index.d.ts +2 -0
- package/dist/src/connectors/index.js +2 -0
- package/dist/src/connectors/manager.d.ts +39 -1
- package/dist/src/connectors/manager.js +142 -15
- package/dist/src/connectors/mongo/index.d.ts +13 -0
- package/dist/src/connectors/mongo/index.js +323 -0
- package/dist/src/connectors/pg/index.d.ts +2 -0
- package/dist/src/connectors/pg/index.js +248 -0
- package/dist/src/connectors/source-factory.d.ts +38 -0
- package/dist/src/connectors/source-factory.js +80 -0
- package/dist/src/connectors/sql-safety.js +3 -3
- package/dist/src/connectors/types.d.ts +51 -0
- package/dist/src/connectors/types.js +11 -1
- package/dist/src/mcp/index.d.ts +1 -1
- package/dist/src/mcp/index.js +20 -9
- package/dist/src/mcp/tools/analyze.js +11 -1
- package/dist/src/mcp/tools/capabilities.d.ts +1 -0
- package/dist/src/mcp/tools/capabilities.js +14 -0
- package/dist/src/mcp/tools/clean-column.js +2 -0
- package/dist/src/mcp/tools/drop-columns.js +2 -0
- package/dist/src/mcp/tools/list-transforms.js +22 -0
- package/dist/src/mcp/tools/promote-columns.js +2 -0
- package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
- package/dist/src/mcp/tools/refine.d.ts +4 -4
- package/dist/src/mcp/tools/shared.d.ts +5 -0
- package/dist/src/mcp/tools/shared.js +11 -4
- package/dist/src/mcp/tools/sources.d.ts +46 -3
- package/dist/src/mcp/tools/sources.js +44 -4
- package/dist/src/mcp/tools/transform-data.js +22 -0
- package/dist/src/types.d.ts +29 -2
- package/dist/src/utils/capabilities.d.ts +28 -0
- package/dist/src/utils/capabilities.js +58 -0
- package/dist/src/utils/optional-deps.d.ts +8 -0
- package/dist/src/utils/optional-deps.js +8 -0
- package/package.json +5 -2
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { registerDerivedColumn } from '../types.js';
|
|
2
|
+
import { importOptional } from '../../utils/optional-deps.js';
|
|
3
|
+
/** Lazily load the pg driver so the base install never requires it — a missing package becomes a
|
|
4
|
+
* friendly "npm install pg", surfaced only when a Postgres source is actually used. */
|
|
5
|
+
const loadPg = () => importOptional('pg', 'postgres');
|
|
6
|
+
const q = (id) => '"' + id.replace(/"/g, '""') + '"';
|
|
7
|
+
function poolFor(PoolCtor, cfg) {
|
|
8
|
+
if (cfg.connectionString)
|
|
9
|
+
return new PoolCtor({ connectionString: cfg.connectionString, max: 4 });
|
|
10
|
+
// The secret is either the literal password or (preferred) read from an env var at connect time,
|
|
11
|
+
// so it need never be persisted in the registry file.
|
|
12
|
+
const password = cfg.password ?? (cfg.passwordEnv ? process.env[cfg.passwordEnv] : undefined);
|
|
13
|
+
return new PoolCtor({
|
|
14
|
+
host: cfg.host, port: cfg.port, database: cfg.database, user: cfg.user, password, max: 4,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
// Postgres type OIDs that should surface as JS numbers: int2/int4/int8, float4/float8, numeric.
|
|
18
|
+
const PG_NUMERIC_OIDS = new Set([20, 21, 23, 700, 701, 1700]);
|
|
19
|
+
const NUMERIC_TYPES = new Set(['numeric', 'integer', 'bigint', 'double precision', 'real', 'smallint', 'decimal']);
|
|
20
|
+
const DATE_TYPES = new Set(['date', 'timestamp without time zone', 'timestamp with time zone', 'time without time zone']);
|
|
21
|
+
function classify(dataType, name, distinct, total) {
|
|
22
|
+
if (NUMERIC_TYPES.has(dataType)) {
|
|
23
|
+
if (/(^|_)id$/i.test(name) && total > 0 && distinct >= total * 0.9)
|
|
24
|
+
return 'id';
|
|
25
|
+
return 'numeric';
|
|
26
|
+
}
|
|
27
|
+
if (DATE_TYPES.has(dataType))
|
|
28
|
+
return 'date';
|
|
29
|
+
// text-ish
|
|
30
|
+
if (total > 0 && distinct <= Math.min(1000, Math.max(50, total * 0.5)) && distinct <= 200)
|
|
31
|
+
return 'categorical';
|
|
32
|
+
return 'text';
|
|
33
|
+
}
|
|
34
|
+
async function profileTable(pool, schema, table) {
|
|
35
|
+
// column list + pg data types
|
|
36
|
+
const colRes = await pool.query(`SELECT column_name, data_type FROM information_schema.columns
|
|
37
|
+
WHERE table_schema=$1 AND table_name=$2 ORDER BY ordinal_position`, [schema, table]);
|
|
38
|
+
const cols = colRes.rows.map((r) => ({ name: r.column_name, dataType: r.data_type }));
|
|
39
|
+
// one scan: COUNT(*) + per-column distinct + non-null counts
|
|
40
|
+
const countSel = ['COUNT(*)::bigint AS __total'];
|
|
41
|
+
for (const c of cols) {
|
|
42
|
+
countSel.push(`COUNT(DISTINCT ${q(c.name)})::bigint AS ${q('d_' + c.name)}`);
|
|
43
|
+
countSel.push(`COUNT(${q(c.name)})::bigint AS ${q('n_' + c.name)}`);
|
|
44
|
+
}
|
|
45
|
+
const counts = (await pool.query(`SELECT ${countSel.join(', ')} FROM ${q(schema)}.${q(table)}`)).rows[0];
|
|
46
|
+
const total = Number(counts.__total);
|
|
47
|
+
const columns = [];
|
|
48
|
+
for (const c of cols) {
|
|
49
|
+
const distinct = Number(counts['d_' + c.name]);
|
|
50
|
+
const nonNull = Number(counts['n_' + c.name]);
|
|
51
|
+
const type = classify(c.dataType, c.name, distinct, total);
|
|
52
|
+
// sample values (distinct, for display)
|
|
53
|
+
const sv = await pool.query(`SELECT DISTINCT ${q(c.name)}::text AS v FROM ${q(schema)}.${q(table)} WHERE ${q(c.name)} IS NOT NULL LIMIT 20`);
|
|
54
|
+
const sampleValues = sv.rows.map((r) => String(r.v)).slice(0, 5);
|
|
55
|
+
let stats;
|
|
56
|
+
let topValues;
|
|
57
|
+
if (type === 'numeric' && nonNull > 0) {
|
|
58
|
+
const s = (await pool.query(`SELECT MIN(${q(c.name)})::float8 AS min, MAX(${q(c.name)})::float8 AS max, AVG(${q(c.name)})::float8 AS mean,
|
|
59
|
+
COALESCE(STDDEV_POP(${q(c.name)}),0)::float8 AS stddev,
|
|
60
|
+
percentile_cont(0.5) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS median,
|
|
61
|
+
percentile_cont(0.25) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p25,
|
|
62
|
+
percentile_cont(0.75) WITHIN GROUP (ORDER BY ${q(c.name)})::float8 AS p75
|
|
63
|
+
FROM ${q(schema)}.${q(table)} WHERE ${q(c.name)} IS NOT NULL`)).rows[0];
|
|
64
|
+
stats = { min: s.min, max: s.max, mean: s.mean, median: s.median, stddev: s.stddev, p25: s.p25, p75: s.p75 };
|
|
65
|
+
}
|
|
66
|
+
else if (type === 'categorical' || type === 'date') {
|
|
67
|
+
const tv = await pool.query(`SELECT ${q(c.name)}::text AS value, COUNT(*)::int AS count FROM ${q(schema)}.${q(table)}
|
|
68
|
+
WHERE ${q(c.name)} IS NOT NULL GROUP BY ${q(c.name)} ORDER BY COUNT(*) DESC LIMIT 10`);
|
|
69
|
+
topValues = tv.rows.map((r) => ({ value: String(r.value), count: r.count }));
|
|
70
|
+
}
|
|
71
|
+
columns.push({
|
|
72
|
+
name: c.name, type, sampleValues,
|
|
73
|
+
uniqueCount: distinct, nullCount: total - nonNull, totalCount: total,
|
|
74
|
+
layer: 'source', stats, topValues,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
return { name: table, columns, rowCount: total };
|
|
78
|
+
}
|
|
79
|
+
async function readForeignKeys(pool, schema) {
|
|
80
|
+
const res = await pool.query(`SELECT tc.table_name AS ft, kcu.column_name AS fc, ccu.table_name AS tt, ccu.column_name AS tcol
|
|
81
|
+
FROM information_schema.table_constraints tc
|
|
82
|
+
JOIN information_schema.key_column_usage kcu ON tc.constraint_name=kcu.constraint_name AND tc.table_schema=kcu.table_schema
|
|
83
|
+
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name=tc.constraint_name AND ccu.table_schema=tc.table_schema
|
|
84
|
+
WHERE tc.constraint_type='FOREIGN KEY' AND tc.table_schema=$1
|
|
85
|
+
ORDER BY ft, fc`, [schema]);
|
|
86
|
+
return res.rows.map((r) => ({ fromTable: r.ft, fromColumn: r.fc, toTable: r.tt, toColumn: r.tcol }));
|
|
87
|
+
}
|
|
88
|
+
class PgConnectedSource {
|
|
89
|
+
id;
|
|
90
|
+
name;
|
|
91
|
+
pool;
|
|
92
|
+
schemaName;
|
|
93
|
+
schema;
|
|
94
|
+
type = 'postgres';
|
|
95
|
+
/** Once a derivation exists, ALL queries ride this ONE pinned client so pg_temp (the shadow
|
|
96
|
+
* view + temp table) is visible — a pooled connection would not see them (exp 043). */
|
|
97
|
+
pinned = null;
|
|
98
|
+
/** table → derived columns materialized this session, in creation order. */
|
|
99
|
+
derived = new Map();
|
|
100
|
+
constructor(id, name, pool, schemaName, schema) {
|
|
101
|
+
this.id = id;
|
|
102
|
+
this.name = name;
|
|
103
|
+
this.pool = pool;
|
|
104
|
+
this.schemaName = schemaName;
|
|
105
|
+
this.schema = schema;
|
|
106
|
+
}
|
|
107
|
+
async getSchema() {
|
|
108
|
+
return this.schema;
|
|
109
|
+
}
|
|
110
|
+
/** The query runner: the pinned client once a derivation is active, else the pool. */
|
|
111
|
+
runner() {
|
|
112
|
+
return this.pinned ?? this.pool;
|
|
113
|
+
}
|
|
114
|
+
async executeQuery(sql) {
|
|
115
|
+
try {
|
|
116
|
+
const r = await this.runner().query(sql);
|
|
117
|
+
// Coerce by the RESULT column's actual Postgres type (OID), not by source-column
|
|
118
|
+
// name — so aliased aggregates (AVG/SUM AS x) and computed columns are typed
|
|
119
|
+
// correctly. node-postgres returns numeric/bigint as strings; we surface them as JS
|
|
120
|
+
// numbers for consumer parity with the CSV path (charts/aggregation downstream).
|
|
121
|
+
// Math already happened in SQL (policy B, exp 038); this final cast is display-side and
|
|
122
|
+
// carries the same float64 ceiling the CSV connector has.
|
|
123
|
+
const columns = r.fields.map((f) => f.name);
|
|
124
|
+
const numericField = new Set(r.fields.filter((f) => PG_NUMERIC_OIDS.has(f.dataTypeID)).map((f) => f.name));
|
|
125
|
+
const rows = r.rows.map((row) => {
|
|
126
|
+
const out = {};
|
|
127
|
+
for (const col of columns) {
|
|
128
|
+
const v = row[col];
|
|
129
|
+
if (numericField.has(col) && typeof v === 'string' && v !== '' && !isNaN(Number(v)))
|
|
130
|
+
out[col] = Number(v);
|
|
131
|
+
else
|
|
132
|
+
out[col] = v;
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
});
|
|
136
|
+
return { columns, rows };
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
return { columns: [], rows: [{ error: err.message }] };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async getSampleRows(tableName, count = 5) {
|
|
143
|
+
const total = this.schema.tables.find((t) => t.name === tableName)?.rowCount ?? 0;
|
|
144
|
+
if (total === 0)
|
|
145
|
+
return [];
|
|
146
|
+
if (total <= count) {
|
|
147
|
+
return (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)}`)).rows;
|
|
148
|
+
}
|
|
149
|
+
// block-level server-side sample; fall back to a bounded scan if it under-fills
|
|
150
|
+
const pct = Math.min(100, Math.max(1, Math.ceil((count / total) * 100 * 20)));
|
|
151
|
+
let rows = (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)} TABLESAMPLE SYSTEM(${pct}) LIMIT ${count}`)).rows;
|
|
152
|
+
if (rows.length < count) {
|
|
153
|
+
rows = (await this.pool.query(`SELECT * FROM ${q(this.schemaName)}.${q(tableName)} LIMIT ${count}`)).rows;
|
|
154
|
+
}
|
|
155
|
+
return rows;
|
|
156
|
+
}
|
|
157
|
+
// getDatabase intentionally omitted → the derivation seam no longer keys on a raw db handle.
|
|
158
|
+
/**
|
|
159
|
+
* Postgres derives via a session-local TEMP TABLE keyed by `id`, exposed to arbitrary later
|
|
160
|
+
* queries through a same-named TEMP VIEW on ONE pinned client. Declared here; the materialization
|
|
161
|
+
* itself is wired in a subsequent stage.
|
|
162
|
+
*/
|
|
163
|
+
derivationCapabilities() {
|
|
164
|
+
return { canDerive: true, materialization: 'session-temp', rowKey: 'id', serverSideQueryable: true };
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Materialize a derived column as a session-local shadow TEMP VIEW on the pinned client.
|
|
168
|
+
* `expr` is a Postgres SQL expression over the table's columns. pg_temp precedes the schema in
|
|
169
|
+
* search_path, so a later unqualified `FROM <table>` transparently reads the view. The base
|
|
170
|
+
* table (schema-qualified inside the view) is never written. Multiple derivations accumulate.
|
|
171
|
+
*/
|
|
172
|
+
async applyDerivation(table, column, expr) {
|
|
173
|
+
if (/;|--|\/\*/.test(expr))
|
|
174
|
+
throw new Error('derivation expr must be a single SQL expression (no ";" or comments)');
|
|
175
|
+
if (!this.pinned)
|
|
176
|
+
this.pinned = await this.pool.connect();
|
|
177
|
+
const c = this.pinned;
|
|
178
|
+
const cols = this.derived.get(table) ?? [];
|
|
179
|
+
const existing = cols.find((d) => d.column === column);
|
|
180
|
+
if (existing)
|
|
181
|
+
existing.expr = expr;
|
|
182
|
+
else
|
|
183
|
+
cols.push({ column, expr });
|
|
184
|
+
this.derived.set(table, cols);
|
|
185
|
+
const projected = cols.map((d) => `(${d.expr}) AS ${q(d.column)}`).join(', ');
|
|
186
|
+
await c.query(`DROP VIEW IF EXISTS pg_temp.${q(table)}`);
|
|
187
|
+
await c.query(`CREATE TEMP VIEW ${q(table)} AS SELECT b.*, ${projected} FROM ${q(this.schemaName)}.${q(table)} b`);
|
|
188
|
+
registerDerivedColumn(this.schema, table, column);
|
|
189
|
+
}
|
|
190
|
+
async close() {
|
|
191
|
+
try {
|
|
192
|
+
if (this.pinned) {
|
|
193
|
+
this.pinned.release();
|
|
194
|
+
this.pinned = null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch { /* noop */ }
|
|
198
|
+
try {
|
|
199
|
+
await this.pool.end();
|
|
200
|
+
}
|
|
201
|
+
catch { /* already closed */ }
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
export const pgConnector = {
|
|
205
|
+
type: 'postgres',
|
|
206
|
+
async test(config) {
|
|
207
|
+
const cfg = config;
|
|
208
|
+
if (cfg.type !== 'postgres')
|
|
209
|
+
return { ok: false, error: 'Config type must be "postgres"' };
|
|
210
|
+
const { Pool } = await loadPg();
|
|
211
|
+
const pool = poolFor(Pool, cfg);
|
|
212
|
+
try {
|
|
213
|
+
await pool.query('SELECT 1');
|
|
214
|
+
return { ok: true };
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
// A connection refusal often arrives as an AggregateError with an empty top-level message;
|
|
218
|
+
// fall back to the code / nested reason so the caller (and the AI agent) gets something actionable.
|
|
219
|
+
const reason = err?.message || err?.code || err?.errors?.map((e) => e?.message || e?.code).filter(Boolean).join('; ') || String(err);
|
|
220
|
+
return { ok: false, error: `Cannot connect to Postgres: ${reason}` };
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
await pool.end();
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
async connect(config) {
|
|
227
|
+
const cfg = config;
|
|
228
|
+
if (cfg.type !== 'postgres')
|
|
229
|
+
throw new Error('Config type must be "postgres"');
|
|
230
|
+
const schema = cfg.schema || 'public';
|
|
231
|
+
const { Pool } = await loadPg();
|
|
232
|
+
const pool = poolFor(Pool, cfg);
|
|
233
|
+
const tableRes = await pool.query(`SELECT table_name FROM information_schema.tables
|
|
234
|
+
WHERE table_schema=$1 AND table_type='BASE TABLE' ORDER BY table_name`, [schema]);
|
|
235
|
+
const tables = [];
|
|
236
|
+
for (const row of tableRes.rows) {
|
|
237
|
+
tables.push(await profileTable(pool, schema, row.table_name));
|
|
238
|
+
}
|
|
239
|
+
const foreignKeys = await readForeignKeys(pool, schema);
|
|
240
|
+
const dataSchema = {
|
|
241
|
+
tables, foreignKeys,
|
|
242
|
+
source: { id: '', type: 'postgres', name: cfg.database || 'postgres', config },
|
|
243
|
+
};
|
|
244
|
+
const id = `pg-${cfg.database || 'db'}`;
|
|
245
|
+
dataSchema.source.id = id;
|
|
246
|
+
return new PgConnectedSource(id, cfg.database || 'postgres', pool, schema, dataSchema);
|
|
247
|
+
},
|
|
248
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source factory — turn generic frontend arguments (a `--type`, a connection
|
|
3
|
+
* string, or discrete host/port/database fields) into a typed
|
|
4
|
+
* `DataSourceConfig` the `SourceManager` can register and connect.
|
|
5
|
+
*
|
|
6
|
+
* Model-free and dependency-free: it only shapes/validates a config object; it
|
|
7
|
+
* never opens a connection (the connector's `test()`/`connect()` does that).
|
|
8
|
+
* Shared by the CLI `sources add` command; the MCP loader can adopt it later.
|
|
9
|
+
*
|
|
10
|
+
* Backward compatibility: an omitted `--type` with a bare path resolves to CSV,
|
|
11
|
+
* so `dolex sources add <name> <path>` keeps working unchanged.
|
|
12
|
+
*/
|
|
13
|
+
import type { DataSourceConfig } from '../types.js';
|
|
14
|
+
/** Generic, frontend-agnostic inputs a factory resolves into a typed config. */
|
|
15
|
+
export interface SourceFactoryArgs {
|
|
16
|
+
/** csv | postgres | mongodb. Omitted ⇒ defaults to 'csv'. */
|
|
17
|
+
type?: string;
|
|
18
|
+
/** CSV: path to a `.csv` file or a directory of CSVs. */
|
|
19
|
+
path?: string;
|
|
20
|
+
/** Connection string: libpq DSN (postgres) or Mongo URI (mongodb). */
|
|
21
|
+
uri?: string;
|
|
22
|
+
host?: string;
|
|
23
|
+
port?: number;
|
|
24
|
+
database?: string;
|
|
25
|
+
user?: string;
|
|
26
|
+
password?: string;
|
|
27
|
+
/** Name of an env var holding the Postgres password (kept out of the registry file). */
|
|
28
|
+
passwordEnv?: string;
|
|
29
|
+
/** Postgres schema to introspect (default: public). */
|
|
30
|
+
schema?: string;
|
|
31
|
+
/** Mongo: restrict introspection to these collections. */
|
|
32
|
+
collections?: string[];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Resolve generic args into a typed `DataSourceConfig`. Throws an `Error` with
|
|
36
|
+
* an actionable message when required fields are missing or the type is unknown.
|
|
37
|
+
*/
|
|
38
|
+
export declare function resolveSourceConfig(args: SourceFactoryArgs): DataSourceConfig;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source factory — turn generic frontend arguments (a `--type`, a connection
|
|
3
|
+
* string, or discrete host/port/database fields) into a typed
|
|
4
|
+
* `DataSourceConfig` the `SourceManager` can register and connect.
|
|
5
|
+
*
|
|
6
|
+
* Model-free and dependency-free: it only shapes/validates a config object; it
|
|
7
|
+
* never opens a connection (the connector's `test()`/`connect()` does that).
|
|
8
|
+
* Shared by the CLI `sources add` command; the MCP loader can adopt it later.
|
|
9
|
+
*
|
|
10
|
+
* Backward compatibility: an omitted `--type` with a bare path resolves to CSV,
|
|
11
|
+
* so `dolex sources add <name> <path>` keeps working unchanged.
|
|
12
|
+
*/
|
|
13
|
+
const SUPPORTED_TYPES = ['csv', 'postgres', 'mongodb'];
|
|
14
|
+
/**
|
|
15
|
+
* Resolve generic args into a typed `DataSourceConfig`. Throws an `Error` with
|
|
16
|
+
* an actionable message when required fields are missing or the type is unknown.
|
|
17
|
+
*/
|
|
18
|
+
export function resolveSourceConfig(args) {
|
|
19
|
+
const rawType = args.type?.trim().toLowerCase();
|
|
20
|
+
const type = (rawType || 'csv');
|
|
21
|
+
if (!SUPPORTED_TYPES.includes(type)) {
|
|
22
|
+
throw new Error(`Unsupported source type "${args.type}". Use one of: ${SUPPORTED_TYPES.join(', ')}.`);
|
|
23
|
+
}
|
|
24
|
+
switch (type) {
|
|
25
|
+
case 'csv':
|
|
26
|
+
return resolveCsv(args);
|
|
27
|
+
case 'postgres':
|
|
28
|
+
return resolvePostgres(args);
|
|
29
|
+
case 'mongodb':
|
|
30
|
+
return resolveMongo(args);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function resolveCsv(args) {
|
|
34
|
+
if (!args.path) {
|
|
35
|
+
throw new Error('CSV source requires a path to a .csv file or a directory of CSVs.');
|
|
36
|
+
}
|
|
37
|
+
return { type: 'csv', path: args.path };
|
|
38
|
+
}
|
|
39
|
+
function resolvePostgres(args) {
|
|
40
|
+
const hasDiscrete = Boolean(args.host || args.database || args.user);
|
|
41
|
+
if (!args.uri && !hasDiscrete) {
|
|
42
|
+
throw new Error('Postgres source requires --uri <connection-string>, or discrete --host/--database (plus optional --port/--user/--password/--schema).');
|
|
43
|
+
}
|
|
44
|
+
const config = { type: 'postgres' };
|
|
45
|
+
if (args.uri)
|
|
46
|
+
config.connectionString = args.uri;
|
|
47
|
+
if (args.host)
|
|
48
|
+
config.host = args.host;
|
|
49
|
+
if (args.port !== undefined)
|
|
50
|
+
config.port = args.port;
|
|
51
|
+
if (args.database)
|
|
52
|
+
config.database = args.database;
|
|
53
|
+
if (args.user)
|
|
54
|
+
config.user = args.user;
|
|
55
|
+
if (args.password)
|
|
56
|
+
config.password = args.password;
|
|
57
|
+
if (args.passwordEnv)
|
|
58
|
+
config.passwordEnv = args.passwordEnv;
|
|
59
|
+
if (args.schema)
|
|
60
|
+
config.schema = args.schema;
|
|
61
|
+
return config;
|
|
62
|
+
}
|
|
63
|
+
function resolveMongo(args) {
|
|
64
|
+
if (!args.database) {
|
|
65
|
+
throw new Error('Mongo source requires --database (a Mongo connection has no single default db).');
|
|
66
|
+
}
|
|
67
|
+
if (!args.uri && !args.host) {
|
|
68
|
+
throw new Error('Mongo source requires --uri <connection-string> or --host (plus optional --port).');
|
|
69
|
+
}
|
|
70
|
+
const config = { type: 'mongodb', database: args.database };
|
|
71
|
+
if (args.uri)
|
|
72
|
+
config.uri = args.uri;
|
|
73
|
+
if (args.host)
|
|
74
|
+
config.host = args.host;
|
|
75
|
+
if (args.port !== undefined)
|
|
76
|
+
config.port = args.port;
|
|
77
|
+
if (args.collections && args.collections.length > 0)
|
|
78
|
+
config.collections = args.collections;
|
|
79
|
+
return config;
|
|
80
|
+
}
|
|
@@ -32,7 +32,7 @@ const OPERAND = String.raw `(?:\w+\s*\([^()]*\)|\w+(?:\.\w+)?|\d+(?:\.\d+)?)`;
|
|
|
32
32
|
const TERM = new RegExp(`${OPERAND}(?:\\s*[*/]\\s*${OPERAND})+`, 'g');
|
|
33
33
|
const FLOAT_LIT = /\d+\.\d+/;
|
|
34
34
|
const CAST_REAL = /CAST\s*\([^()]*AS\s+(?:REAL|FLOAT|DOUBLE)/i;
|
|
35
|
-
const TERM_FUNCS = new Set(['sum', 'avg', 'count', 'min', 'max', 'cast', 'as', 'real', 'float', 'double', 'total', 'abs', 'round']);
|
|
35
|
+
const TERM_FUNCS = new Set(['sum', 'avg', 'count', 'min', 'max', 'cast', 'as', 'real', 'float', 'double', 'total', 'abs', 'round', 'distinct', 'all']);
|
|
36
36
|
/** Multiplicative terms containing a `/` that are NOT already float-safe (no float
|
|
37
37
|
* literal, no CAST-to-real), with their candidate column identifiers. Pure syntax
|
|
38
38
|
* — cheap enough to use as a pre-filter before any type probing. */
|
|
@@ -158,8 +158,8 @@ export async function detectSqlFootguns(sql, columnType) {
|
|
|
158
158
|
if (allInteger) {
|
|
159
159
|
warnings.push({
|
|
160
160
|
code: 'integer-division',
|
|
161
|
-
message: `Integer division in "${term.trim()}"
|
|
162
|
-
`
|
|
161
|
+
message: `Integer division in "${term.trim()}" truncates toward zero (int/int floors — e.g. 16/32 → 0, not 0.5). ` +
|
|
162
|
+
`Cast a numeric operand first: CAST(<numerator> AS REAL) / <denominator>.`,
|
|
163
163
|
});
|
|
164
164
|
}
|
|
165
165
|
}
|
|
@@ -2,6 +2,42 @@
|
|
|
2
2
|
* Connector-specific types for Dolex data source connectors.
|
|
3
3
|
*/
|
|
4
4
|
import type { DataSourceType, DataSourceConfig, DataSchema } from '../types.js';
|
|
5
|
+
/**
|
|
6
|
+
* Reflect a session-derived column in a connector's cached schema, so downstream consumers
|
|
7
|
+
* (schemaText, describe_data) see it. Shared by the live connectors' applyDerivation
|
|
8
|
+
* (Postgres shadow view / Mongo $set) — idempotent; a no-op if the column already exists.
|
|
9
|
+
*/
|
|
10
|
+
export declare function registerDerivedColumn(schema: DataSchema, table: string, column: string): void;
|
|
11
|
+
/**
|
|
12
|
+
* How a source materializes a derived column, declared by the connector itself
|
|
13
|
+
* so the transform/clean surfaces stay source-agnostic (no getDatabase-truthiness gate).
|
|
14
|
+
*
|
|
15
|
+
* - `sqlite-alter` — CSV: ALTER TABLE + rowid-keyed UPDATE on the in-memory SQLite db.
|
|
16
|
+
* - `session-temp` — Postgres: a session-local TEMP TABLE keyed by `id`, exposed to
|
|
17
|
+
* arbitrary later queries via a same-named TEMP VIEW on ONE pinned client.
|
|
18
|
+
* - `computed-set` — Mongo: a `$set` aggregation expression prepended to every incoming pipeline,
|
|
19
|
+
* computing the derived field server-side on read. Base collection never written.
|
|
20
|
+
* - `sidecar` — Mongo alt: a throwaway sidecar collection keyed by `_id`, joined via $lookup
|
|
21
|
+
* (used when the derived value is precomputed rather than an expression).
|
|
22
|
+
* - `none` — the source cannot derive columns.
|
|
23
|
+
*/
|
|
24
|
+
export type DerivationMaterialization = 'sqlite-alter' | 'session-temp' | 'computed-set' | 'sidecar' | 'none';
|
|
25
|
+
/** The row key a derivation joins the derived value back on. */
|
|
26
|
+
export type DerivationRowKey = 'rowid' | 'id' | '_id' | null;
|
|
27
|
+
/**
|
|
28
|
+
* A connector's self-declared derivation contract. The transform/clean surfaces read this
|
|
29
|
+
* (via `ConnectedSource.derivationCapabilities()`) instead of probing for a raw db handle.
|
|
30
|
+
*/
|
|
31
|
+
export interface DerivationCapabilities {
|
|
32
|
+
/** Can this source materialize a derived column at all? */
|
|
33
|
+
canDerive: boolean;
|
|
34
|
+
/** How the derived column is materialized. */
|
|
35
|
+
materialization: DerivationMaterialization;
|
|
36
|
+
/** The key column the derived value is joined back on. */
|
|
37
|
+
rowKey: DerivationRowKey;
|
|
38
|
+
/** Is the derived column visible to arbitrary subsequent analyst queries (not just an explicit JOIN)? */
|
|
39
|
+
serverSideQueryable: boolean;
|
|
40
|
+
}
|
|
5
41
|
/**
|
|
6
42
|
* A data connector knows how to connect to a specific data source type,
|
|
7
43
|
* introspect its schema, and execute queries against it.
|
|
@@ -31,6 +67,21 @@ export interface ConnectedSource {
|
|
|
31
67
|
getSampleRows(tableName: string, count?: number): Promise<Record<string, any>[]>;
|
|
32
68
|
/** Get the underlying database handle (only available for SQL-backed connectors). */
|
|
33
69
|
getDatabase?(): any;
|
|
70
|
+
/**
|
|
71
|
+
* Declare how (or whether) this source can materialize a derived column. The source-agnostic
|
|
72
|
+
* transform/clean surfaces gate on this instead of probing `getDatabase`. A connector that does
|
|
73
|
+
* not implement it is treated as non-deriving.
|
|
74
|
+
*/
|
|
75
|
+
derivationCapabilities?(): DerivationCapabilities;
|
|
76
|
+
/**
|
|
77
|
+
* Materialize a derived column named `column` on `table` from `expr` — an expression in THIS
|
|
78
|
+
* source's own native language (a SQL expression for a SQL source, a Mongo `$set` aggregation
|
|
79
|
+
* expression for Mongo). The derived column must become visible to arbitrary subsequent
|
|
80
|
+
* `executeQuery` calls WITHOUT mutating the base table/collection (a session-local temp view on
|
|
81
|
+
* Postgres, a prepended `$set` on Mongo). Only implemented by connectors that declare
|
|
82
|
+
* `serverSideQueryable` derivation. Throws on an unsafe/invalid expression.
|
|
83
|
+
*/
|
|
84
|
+
applyDerivation?(table: string, column: string, expr: string): Promise<void>;
|
|
34
85
|
/** Invalidate cached schema so the next getSchema() rebuilds from the live database. */
|
|
35
86
|
invalidateSchema?(): void;
|
|
36
87
|
/** Close the connection and free resources. */
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Connector-specific types for Dolex data source connectors.
|
|
3
3
|
*/
|
|
4
|
-
|
|
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
|
+
}
|
package/dist/src/mcp/index.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
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
|
package/dist/src/mcp/index.js
CHANGED
|
@@ -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
|
-
*
|
|
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';
|
|
@@ -81,9 +82,10 @@ const server = new McpServer({
|
|
|
81
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.",
|
|
82
83
|
'',
|
|
83
84
|
'WORKFLOW:',
|
|
84
|
-
'• Got a CSV file? →
|
|
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.',
|
|
85
87
|
'• Got inline data? → visualize(data, intent) directly',
|
|
86
|
-
'• Need to explore? →
|
|
88
|
+
'• Need to explore? → load_source → analyze_data → visualize(sourceId, sql, intent) per step',
|
|
87
89
|
'',
|
|
88
90
|
'CONTINUATION (dataset already loaded):',
|
|
89
91
|
'• Chart from data → visualize(sourceId, sql, intent)',
|
|
@@ -94,7 +96,7 @@ const server = new McpServer({
|
|
|
94
96
|
'• specId expired? → re-run the original visualize call, then continue refining from the new specId',
|
|
95
97
|
'',
|
|
96
98
|
'TOOL GUIDE:',
|
|
97
|
-
'•
|
|
99
|
+
'• load_source: Load a CSV / Postgres / MongoDB source. Returns sourceId + smart summary (columns, types, ranges, categorical values) — enough to query.',
|
|
98
100
|
'• describe_data: Full column stats, top values, sample rows. Call only when you need deep exploration.',
|
|
99
101
|
'• analyze_data: Auto-generate analysis plan with ready SQL queries. Execute each step with visualize; present results one at a time.',
|
|
100
102
|
'• query_data: Run SQL query, get rows. Returns resultId for visualize().',
|
|
@@ -147,9 +149,9 @@ registerAppTool(server, 'refine_visualization', {
|
|
|
147
149
|
},
|
|
148
150
|
}, handleRefine());
|
|
149
151
|
// CSV data management tools
|
|
150
|
-
server.registerTool('
|
|
151
|
-
title: 'Load
|
|
152
|
-
description: 'Load a CSV file or
|
|
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.',
|
|
153
155
|
inputSchema: addSourceInputSchema,
|
|
154
156
|
}, handleAddSource({ sourceManager }));
|
|
155
157
|
server.registerTool('list_data', {
|
|
@@ -163,7 +165,7 @@ server.registerTool('remove_data', {
|
|
|
163
165
|
}, handleRemoveSource({ sourceManager }));
|
|
164
166
|
server.registerTool('describe_data', {
|
|
165
167
|
title: 'Describe Data',
|
|
166
|
-
description: 'Full column profiles: stats (min/max/mean/median), top values with counts, sample rows.\nUse only when you need deep exploration —
|
|
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.',
|
|
167
169
|
inputSchema: describeSourceInputSchema,
|
|
168
170
|
}, handleDescribeSource({ sourceManager }));
|
|
169
171
|
server.registerTool('analyze_data', {
|
|
@@ -208,6 +210,15 @@ server.registerTool('server_status', {
|
|
|
208
210
|
title: 'Server Status',
|
|
209
211
|
description: 'Inspect cached specs, query results, connected sources, and uptime.',
|
|
210
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 }));
|
|
211
222
|
server.registerTool('clear_cache', {
|
|
212
223
|
title: 'Clear Cache',
|
|
213
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
|
-
|
|
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
|
+
}
|
|
@@ -6,6 +6,8 @@ export function handleCleanColumn(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(`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.`);
|
|
9
11
|
const colNames = ctx.table.columns.map((c) => c.name);
|
|
10
12
|
if (!colNames.includes(args.column))
|
|
11
13
|
return errorResponse(`Column '${args.column}' not found. Available: [${colNames.join(', ')}]`);
|
|
@@ -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);
|