@outsidedata/dolex 9.0.0 → 9.0.2
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/dist/src/cli/commands/sources.js +2 -1
- package/dist/src/cli/data-source.d.ts +0 -2
- package/dist/src/cli/data-source.js +0 -1
- package/dist/src/connectors/manager.js +71 -52
- package/dist/src/connectors/mongo/index.d.ts +8 -0
- package/dist/src/connectors/mongo/index.js +42 -6
- package/dist/src/connectors/pg/index.js +90 -22
- package/dist/src/connectors/sql-safety.d.ts +59 -17
- package/dist/src/connectors/sql-safety.js +275 -54
- package/dist/src/connectors/types.d.ts +8 -0
- package/dist/src/connectors/types.js +22 -0
- package/dist/src/mcp/index.js +23 -4
- package/dist/src/mcp/tools/analyze.js +1 -1
- package/dist/src/mcp/tools/clean-schemas.js +1 -1
- package/dist/src/mcp/tools/query-source.js +2 -2
- package/dist/src/mcp/tools/sources.d.ts +1 -1
- package/dist/src/mcp/tools/sources.js +7 -5
- package/dist/src/mcp/tools/transform-schemas.js +4 -4
- package/dist/src/mcp/tools/visualize-cli.js +1 -1
- package/dist/src/mcp/tools/visualize.js +2 -2
- package/dist/src/patterns/index.d.ts +1 -1
- package/dist/src/patterns/index.js +1 -1
- package/dist/src/patterns/registry.d.ts +1 -12
- package/dist/src/patterns/registry.js +0 -13
- package/dist/src/patterns/utils.d.ts +0 -24
- package/dist/src/patterns/utils.js +0 -71
- package/dist/src/renderers/d3/shared.d.ts +0 -18
- package/dist/src/renderers/d3/shared.js +0 -62
- package/dist/src/types.d.ts +1 -1
- package/dist/src/utils/capabilities.js +1 -1
- package/package.json +4 -4
- package/dist/src/analysis/clean-exec.d.ts +0 -23
- package/dist/src/analysis/clean-exec.js +0 -87
- package/dist/src/cleaning/author.d.ts +0 -30
- package/dist/src/cleaning/author.js +0 -7
- package/dist/src/cleaning/handlers.d.ts +0 -16
- package/dist/src/cleaning/handlers.js +0 -82
- package/dist/src/cleaning/manifest.d.ts +0 -35
- package/dist/src/cleaning/manifest.js +0 -95
|
@@ -12,19 +12,35 @@
|
|
|
12
12
|
* cried wolf on legitimate real-typed division. The promoted approach is
|
|
13
13
|
* term-aware + TYPE-aware detection with no mutation.
|
|
14
14
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* Integer division is caught two ways (experiment 061):
|
|
16
|
+
* • syntactically — a `/` term whose operand columns are all integer-typed. Column
|
|
17
|
+
* references resolve through the query's own FROM/JOIN aliases, so `B.H / B.AB`,
|
|
18
|
+
* `"wins"/"games"` and a column name shared by two tables all type correctly.
|
|
19
|
+
* • by asking the database — for each top-level output column whose expression
|
|
20
|
+
* divides, the caller probes the type of that column over the executed query. An
|
|
21
|
+
* integer-typed division result is truncation whatever produced it, which covers
|
|
22
|
+
* `(SUM(CASE …) + SUM(CASE …)) / COUNT(*)` and `(SELECT COUNT(*) …) / COUNT(*)`,
|
|
23
|
+
* shapes no operand-level rule can type.
|
|
18
24
|
*/
|
|
19
|
-
//
|
|
20
|
-
// quoted content
|
|
21
|
-
//
|
|
22
|
-
function
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
// String literals (with '' escapes) are blanked before anything else, so a `/` or a quote
|
|
26
|
+
// inside quoted content is never read as SQL. Quoted identifiers are UNQUOTED rather than
|
|
27
|
+
// blanked — blanking them made every `"col"` invisible to the detectors (issue #35).
|
|
28
|
+
export function stripSql(sql) {
|
|
29
|
+
const ids = new Map();
|
|
30
|
+
let n = 0;
|
|
31
|
+
const text = sql
|
|
32
|
+
.replace(/'(?:[^']|'')*'/g, "''")
|
|
33
|
+
.replace(/"((?:[^"]|"")+)"|`([^`]+)`/g, (_m, dq, bq) => {
|
|
34
|
+
const name = (dq ?? bq ?? '').replace(/""/g, '"');
|
|
35
|
+
if (/^[A-Za-z_]\w*$/.test(name))
|
|
36
|
+
return name;
|
|
37
|
+
const token = `__qid${n++}__`;
|
|
38
|
+
ids.set(token, name);
|
|
39
|
+
return token;
|
|
40
|
+
})
|
|
26
41
|
.replace(/--.*$/gm, '')
|
|
27
42
|
.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
43
|
+
return { text, ids };
|
|
28
44
|
}
|
|
29
45
|
// A maximal multiplicative term: operand ([*/] operand)+. operand = number |
|
|
30
46
|
// func(one paren level) | identifier. One level covers SUM(wins), AVG(x)/COUNT(*).
|
|
@@ -32,42 +48,195 @@ const OPERAND = String.raw `(?:\w+\s*\([^()]*\)|\w+(?:\.\w+)?|\d+(?:\.\d+)?)`;
|
|
|
32
48
|
const TERM = new RegExp(`${OPERAND}(?:\\s*[*/]\\s*${OPERAND})+`, 'g');
|
|
33
49
|
const FLOAT_LIT = /\d+\.\d+/;
|
|
34
50
|
const CAST_REAL = /CAST\s*\([^()]*AS\s+(?:REAL|FLOAT|DOUBLE)/i;
|
|
35
|
-
const
|
|
51
|
+
const KEYWORDS = new Set([
|
|
52
|
+
'sum', 'avg', 'count', 'min', 'max', 'cast', 'as', 'real', 'float', 'double', 'total', 'abs', 'round', 'distinct', 'all',
|
|
53
|
+
'case', 'when', 'then', 'else', 'end', 'and', 'or', 'not', 'null', 'is', 'in', 'like', 'between',
|
|
54
|
+
'integer', 'int', 'numeric', 'text', 'select', 'from', 'where',
|
|
55
|
+
]);
|
|
56
|
+
/** Column references in an expression: skips function names (an identifier followed by `(`),
|
|
57
|
+
* SQL keywords and numbers; keeps an `alias.` qualifier; maps placeholder tokens back. */
|
|
58
|
+
export function columnRefs(expr, ids) {
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const m of expr.matchAll(/([A-Za-z_]\w*)(?:\.([A-Za-z_]\w*))?(\s*\()?/g)) {
|
|
61
|
+
if (m[3])
|
|
62
|
+
continue;
|
|
63
|
+
const qualifier = m[2] ? m[1] : undefined;
|
|
64
|
+
const column = m[2] ?? m[1];
|
|
65
|
+
if (!qualifier && KEYWORDS.has(column.toLowerCase()))
|
|
66
|
+
continue;
|
|
67
|
+
out.push({ qualifier, column: ids.get(column) ?? column });
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
36
71
|
/** Multiplicative terms containing a `/` that are NOT already float-safe (no float
|
|
37
|
-
* literal, no CAST-to-real), with
|
|
38
|
-
*
|
|
72
|
+
* literal, no CAST-to-real), with the column references they read. Pure syntax —
|
|
73
|
+
* cheap enough to use as a pre-filter before any type probing. */
|
|
39
74
|
export function riskyDivisionTerms(sql) {
|
|
40
|
-
const
|
|
75
|
+
const { text, ids } = stripSql(sql);
|
|
41
76
|
const out = [];
|
|
42
|
-
for (const m of
|
|
77
|
+
for (const m of text.matchAll(TERM)) {
|
|
43
78
|
const term = m[0];
|
|
44
79
|
if (!term.includes('/'))
|
|
45
80
|
continue; // pure multiplication can't truncate
|
|
46
81
|
if (FLOAT_LIT.test(term) || CAST_REAL.test(term))
|
|
47
82
|
continue; // float context → safe
|
|
48
|
-
|
|
49
|
-
out.push({ term, columns });
|
|
83
|
+
out.push({ term, refs: columnRefs(term, ids) });
|
|
50
84
|
}
|
|
51
85
|
return out;
|
|
52
86
|
}
|
|
53
|
-
/** Division denominators (the operand right of each `/`) with
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
87
|
+
/** Division denominators (the operand right of each `/`) with the column references they
|
|
88
|
+
* read. A `NULLIF(...)`-wrapped denominator is already guarded and skipped. Applies to ALL
|
|
89
|
+
* division (float `x/0` also yields NULL in SQLite), so it is independent of the
|
|
90
|
+
* integer-truncation check above. */
|
|
57
91
|
export function divisionDenominators(sql) {
|
|
58
|
-
const
|
|
92
|
+
const { text, ids } = stripSql(sql);
|
|
59
93
|
const re = new RegExp(`/\\s*(${OPERAND})`, 'g');
|
|
60
94
|
const out = [];
|
|
61
|
-
for (const m of
|
|
95
|
+
for (const m of text.matchAll(re)) {
|
|
62
96
|
const denom = m[1].trim();
|
|
63
97
|
if (/^NULLIF\s*\(/i.test(denom))
|
|
64
98
|
continue; // already guarded
|
|
65
|
-
const
|
|
66
|
-
if (
|
|
67
|
-
out.push({ denom,
|
|
99
|
+
const refs = columnRefs(denom, ids);
|
|
100
|
+
if (refs.length)
|
|
101
|
+
out.push({ denom, refs });
|
|
68
102
|
}
|
|
69
103
|
return out;
|
|
70
104
|
}
|
|
105
|
+
/** Words that end a table reference — never an alias (`JOIN t ON …` has no alias). */
|
|
106
|
+
const CLAUSE_WORDS = new Set(['on', 'using', 'where', 'group', 'order', 'having', 'limit', 'join', 'left', 'right', 'inner', 'outer', 'cross', 'full', 'natural', 'union', 'except', 'intersect', 'window']);
|
|
107
|
+
/** Every table the query reads, keyed by each name it can be referenced by: its alias
|
|
108
|
+
* (lowercased) and its own name (lowercased). Covers `FROM a, b x`, `JOIN t AS y`, quoted
|
|
109
|
+
* and schema-qualified names. A derived-table subquery `FROM (SELECT …) s` names no table. */
|
|
110
|
+
export function tableAliases(sql) {
|
|
111
|
+
const { text, ids } = stripSql(sql);
|
|
112
|
+
const map = new Map();
|
|
113
|
+
const add = (ref) => {
|
|
114
|
+
const parts = ref.trim().split(/\s+/).filter((p) => p && !/^as$/i.test(p));
|
|
115
|
+
if (!parts[0] || parts[0].startsWith('('))
|
|
116
|
+
return; // a derived-table subquery names no table
|
|
117
|
+
const raw = ids.get(parts[0]) ?? parts[0];
|
|
118
|
+
const table = raw.includes('.') && !ids.has(parts[0]) ? raw.split('.').pop() : raw;
|
|
119
|
+
map.set(table.toLowerCase(), table);
|
|
120
|
+
const alias = parts[1];
|
|
121
|
+
if (alias && /^[A-Za-z_]\w*$/.test(alias) && !KEYWORDS.has(alias.toLowerCase()) && !CLAUSE_WORDS.has(alias.toLowerCase())) {
|
|
122
|
+
map.set(alias.toLowerCase(), table);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const lower = text.toLowerCase();
|
|
126
|
+
const isWord = (i) => /\w/.test(lower[i] ?? ' ');
|
|
127
|
+
const wordAt = (i, w) => lower.startsWith(w, i) && !isWord(i - 1) && !isWord(i + w.length);
|
|
128
|
+
// Each FROM clause runs to the next clause keyword at its own paren depth (or the `)` that
|
|
129
|
+
// closes its scope). Inside it, table references are separated by top-level commas and by
|
|
130
|
+
// JOIN keywords; an ON/USING condition belongs to the reference before it and is dropped.
|
|
131
|
+
const END = ['where', 'group', 'order', 'having', 'limit', 'union', 'except', 'intersect', 'window'];
|
|
132
|
+
const JOIN_WORDS = ['join', 'left', 'right', 'inner', 'outer', 'cross', 'full', 'natural'];
|
|
133
|
+
for (let f = 0; f < text.length; f++) {
|
|
134
|
+
if (!wordAt(f, 'from'))
|
|
135
|
+
continue;
|
|
136
|
+
let depth = 0;
|
|
137
|
+
let piece = '';
|
|
138
|
+
let inCondition = false;
|
|
139
|
+
const flush = () => { if (!inCondition)
|
|
140
|
+
add(piece); piece = ''; inCondition = false; };
|
|
141
|
+
for (let i = f + 4; i < text.length; i++) {
|
|
142
|
+
const ch = text[i];
|
|
143
|
+
if (ch === '(')
|
|
144
|
+
depth++;
|
|
145
|
+
if (ch === ')') {
|
|
146
|
+
if (depth === 0)
|
|
147
|
+
break;
|
|
148
|
+
depth--;
|
|
149
|
+
}
|
|
150
|
+
if (depth === 0) {
|
|
151
|
+
if (ch === ';' || END.some((w) => wordAt(i, w)))
|
|
152
|
+
break;
|
|
153
|
+
if (ch === ',') {
|
|
154
|
+
flush();
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const jw = JOIN_WORDS.find((w) => wordAt(i, w));
|
|
158
|
+
if (jw) {
|
|
159
|
+
if (piece.trim())
|
|
160
|
+
flush();
|
|
161
|
+
inCondition = false;
|
|
162
|
+
i += jw.length - 1;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (wordAt(i, 'on') || wordAt(i, 'using')) {
|
|
166
|
+
add(piece);
|
|
167
|
+
piece = '';
|
|
168
|
+
inCondition = true;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (!inCondition)
|
|
173
|
+
piece += ch;
|
|
174
|
+
}
|
|
175
|
+
flush();
|
|
176
|
+
}
|
|
177
|
+
return map;
|
|
178
|
+
}
|
|
179
|
+
/** The OUTERMOST select's top-level items (split on commas at paren depth 0), skipping any
|
|
180
|
+
* leading WITH clause. null when there is no top-level SELECT. */
|
|
181
|
+
export function selectItems(text) {
|
|
182
|
+
const lower = text.toLowerCase();
|
|
183
|
+
const isWord = (i) => /\w/.test(lower[i] ?? ' ');
|
|
184
|
+
let depth = 0;
|
|
185
|
+
let start = -1;
|
|
186
|
+
for (let i = 0; i < text.length; i++) {
|
|
187
|
+
const ch = text[i];
|
|
188
|
+
if (ch === '(')
|
|
189
|
+
depth++;
|
|
190
|
+
else if (ch === ')')
|
|
191
|
+
depth--;
|
|
192
|
+
else if (depth === 0 && lower.startsWith('select', i) && !isWord(i - 1) && !isWord(i + 6)) {
|
|
193
|
+
start = i + 6;
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (start < 0)
|
|
198
|
+
return null;
|
|
199
|
+
const items = [];
|
|
200
|
+
let cur = '';
|
|
201
|
+
depth = 0;
|
|
202
|
+
for (let i = start; i < text.length; i++) {
|
|
203
|
+
const ch = text[i];
|
|
204
|
+
if (ch === '(')
|
|
205
|
+
depth++;
|
|
206
|
+
else if (ch === ')')
|
|
207
|
+
depth--;
|
|
208
|
+
if (depth === 0 && lower.startsWith('from', i) && !isWord(i - 1) && !isWord(i + 4))
|
|
209
|
+
break;
|
|
210
|
+
if (depth === 0 && ch === ',') {
|
|
211
|
+
items.push(cur.trim());
|
|
212
|
+
cur = '';
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
cur += ch;
|
|
216
|
+
}
|
|
217
|
+
if (cur.trim())
|
|
218
|
+
items.push(cur.trim());
|
|
219
|
+
return items;
|
|
220
|
+
}
|
|
221
|
+
/** Positions (0-based, in output-column order) of the top-level select items whose
|
|
222
|
+
* expression divides outside a float context. null when the positions can't be trusted
|
|
223
|
+
* to line up with the output columns (a `*` item expands to an unknown number). */
|
|
224
|
+
export function dividingOutputPositions(sql) {
|
|
225
|
+
const items = selectItems(stripSql(sql).text);
|
|
226
|
+
if (!items)
|
|
227
|
+
return null;
|
|
228
|
+
if (items.some((it) => /(^|\.)\*$/.test(it.trim())))
|
|
229
|
+
return null;
|
|
230
|
+
const out = [];
|
|
231
|
+
items.forEach((it, k) => {
|
|
232
|
+
if (!it.includes('/'))
|
|
233
|
+
return;
|
|
234
|
+
if (FLOAT_LIT.test(it) || CAST_REAL.test(it))
|
|
235
|
+
return;
|
|
236
|
+
out.push(k);
|
|
237
|
+
});
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
71
240
|
/**
|
|
72
241
|
* Detect division whose denominator column actually CONTAINS a zero — `x / 0`
|
|
73
242
|
* silently yields NULL in SQLite (no error), which then vanishes from downstream
|
|
@@ -76,10 +245,10 @@ export function divisionDenominators(sql) {
|
|
|
76
245
|
*/
|
|
77
246
|
export async function detectDivByZero(sql, columnHasZero) {
|
|
78
247
|
const warnings = [];
|
|
79
|
-
for (const { denom,
|
|
248
|
+
for (const { denom, refs } of divisionDenominators(sql)) {
|
|
80
249
|
let zero = false;
|
|
81
|
-
for (const
|
|
82
|
-
if (await columnHasZero(
|
|
250
|
+
for (const ref of refs) {
|
|
251
|
+
if (await columnHasZero(ref)) {
|
|
83
252
|
zero = true;
|
|
84
253
|
break;
|
|
85
254
|
}
|
|
@@ -94,11 +263,40 @@ export async function detectDivByZero(sql, columnHasZero) {
|
|
|
94
263
|
}
|
|
95
264
|
return warnings;
|
|
96
265
|
}
|
|
97
|
-
const
|
|
98
|
-
/**
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
266
|
+
const AGG_NAMES = 'SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV';
|
|
267
|
+
/** Cut every aggregate call and every parenthesised scalar subquery out of a select list, with
|
|
268
|
+
* balanced parens, returning what's left and the aggregates found at this level. A one-level
|
|
269
|
+
* regex left `AVG((grid - (SELECT AVG(grid) …)))`'s inner columns behind as "bare" (exp. 065). */
|
|
270
|
+
function removeAggregates(list) {
|
|
271
|
+
const aggs = [];
|
|
272
|
+
const call = new RegExp(`^(${AGG_NAMES})\\s*\\(`, 'i');
|
|
273
|
+
let out = '';
|
|
274
|
+
for (let i = 0; i < list.length;) {
|
|
275
|
+
const m = /\w/.test(list[i - 1] ?? ' ') ? null : call.exec(list.slice(i));
|
|
276
|
+
const sub = /^\(\s*select\b/i.exec(list.slice(i));
|
|
277
|
+
if (m || sub) {
|
|
278
|
+
if (m)
|
|
279
|
+
aggs.push(m[1].toUpperCase());
|
|
280
|
+
let depth = 0;
|
|
281
|
+
let j = m ? i + m[0].length - 1 : i;
|
|
282
|
+
for (; j < list.length; j++) {
|
|
283
|
+
if (list[j] === '(')
|
|
284
|
+
depth++;
|
|
285
|
+
else if (list[j] === ')') {
|
|
286
|
+
depth--;
|
|
287
|
+
if (depth === 0) {
|
|
288
|
+
j++;
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
out += ' ';
|
|
294
|
+
i = j;
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
out += list[i++];
|
|
298
|
+
}
|
|
299
|
+
return { rest: out, aggs };
|
|
102
300
|
}
|
|
103
301
|
/**
|
|
104
302
|
* Detect a bare (non-aggregated, non-grouped) column selected ALONGSIDE an
|
|
@@ -111,22 +309,24 @@ function selectList(stripped) {
|
|
|
111
309
|
* too false-positive-prone);
|
|
112
310
|
* - skips a LONE MIN()/MAX(): SQLite has a documented special case where bare
|
|
113
311
|
* columns then take values from the extremal row, so that is actually correct;
|
|
114
|
-
* -
|
|
312
|
+
* - reads the OUTERMOST select list (a scalar subquery's FROM ends nothing) and removes
|
|
313
|
+
* aggregate calls with balanced parens, so a column nested inside an aggregate is never "bare";
|
|
314
|
+
* - only flags references that resolve to real base columns.
|
|
115
315
|
*/
|
|
116
316
|
export function detectBareAggregate(sql, isBaseColumn) {
|
|
117
|
-
const
|
|
118
|
-
if (/\bGROUP\s+BY\b/i.test(
|
|
317
|
+
const { text, ids } = stripSql(sql);
|
|
318
|
+
if (/\bGROUP\s+BY\b/i.test(text))
|
|
119
319
|
return []; // grouped → out of scope (conservative)
|
|
120
|
-
const
|
|
121
|
-
if (!
|
|
320
|
+
const items = selectItems(text);
|
|
321
|
+
if (!items)
|
|
322
|
+
return [];
|
|
323
|
+
const { rest, aggs } = removeAggregates(items.join(', '));
|
|
324
|
+
if (!aggs.length)
|
|
122
325
|
return [];
|
|
123
326
|
// Lone MIN()/MAX() → SQLite fills bare columns from the extremal row (correct).
|
|
124
|
-
const aggs = [...list.matchAll(/\b(SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/gi)].map((m) => m[1].toUpperCase());
|
|
125
327
|
if (aggs.length === 1 && (aggs[0] === 'MIN' || aggs[0] === 'MAX'))
|
|
126
328
|
return [];
|
|
127
|
-
|
|
128
|
-
const bare = list.replace(/\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\([^()]*\)/gi, ' ');
|
|
129
|
-
const cols = [...bare.matchAll(/[a-z_]\w*/gi)].map((m) => m[0]).filter((id) => !TERM_FUNCS.has(id.toLowerCase()) && isBaseColumn(id));
|
|
329
|
+
const cols = columnRefs(rest, ids).filter(isBaseColumn).map((r) => r.column);
|
|
130
330
|
if (cols.length === 0)
|
|
131
331
|
return [];
|
|
132
332
|
const uniq = [...new Set(cols)];
|
|
@@ -145,23 +345,44 @@ export function detectBareAggregate(sql, isBaseColumn) {
|
|
|
145
345
|
*/
|
|
146
346
|
export async function detectSqlFootguns(sql, columnType) {
|
|
147
347
|
const warnings = [];
|
|
148
|
-
for (const { term,
|
|
149
|
-
if (
|
|
348
|
+
for (const { term, refs } of riskyDivisionTerms(sql)) {
|
|
349
|
+
if (refs.length === 0)
|
|
150
350
|
continue;
|
|
151
351
|
let allInteger = true;
|
|
152
|
-
for (const
|
|
153
|
-
if ((await columnType(
|
|
352
|
+
for (const ref of refs) {
|
|
353
|
+
if ((await columnType(ref)) !== 'integer') {
|
|
154
354
|
allInteger = false;
|
|
155
355
|
break;
|
|
156
356
|
}
|
|
157
357
|
}
|
|
158
|
-
if (allInteger)
|
|
159
|
-
warnings.push({
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
358
|
+
if (allInteger)
|
|
359
|
+
warnings.push(integerDivisionWarning(`"${term.trim()}"`));
|
|
360
|
+
}
|
|
361
|
+
return warnings;
|
|
362
|
+
}
|
|
363
|
+
const integerDivisionWarning = (what) => ({
|
|
364
|
+
code: 'integer-division',
|
|
365
|
+
message: `Integer division in ${what} truncates toward zero (int/int floors — e.g. 16/32 → 0, not 0.5). ` +
|
|
366
|
+
`Cast a numeric operand first: CAST(<numerator> AS REAL) / <denominator>.`,
|
|
367
|
+
});
|
|
368
|
+
/**
|
|
369
|
+
* Ask the database: for each output column whose top-level expression divides, is the
|
|
370
|
+
* computed value integer-typed? `resultType(column)` reports the type of that output column
|
|
371
|
+
* over the executed query. Catches truncation in any expression shape (CASE sums, scalar
|
|
372
|
+
* subqueries, parenthesised arithmetic) because it reads the result, not the syntax.
|
|
373
|
+
*/
|
|
374
|
+
export async function detectIntegerDivisionResult(sql, outputColumns, resultType) {
|
|
375
|
+
const positions = dividingOutputPositions(sql);
|
|
376
|
+
if (!positions || !positions.length)
|
|
377
|
+
return [];
|
|
378
|
+
const items = selectItems(stripSql(sql).text) ?? [];
|
|
379
|
+
if (items.length !== outputColumns.length)
|
|
380
|
+
return []; // can't line items up with columns
|
|
381
|
+
const warnings = [];
|
|
382
|
+
for (const k of positions) {
|
|
383
|
+
const col = outputColumns[k];
|
|
384
|
+
if ((await resultType(col)) === 'integer')
|
|
385
|
+
warnings.push(integerDivisionWarning(`output column "${col}"`));
|
|
165
386
|
}
|
|
166
387
|
return warnings;
|
|
167
388
|
}
|
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
* Connector-specific types for Dolex data source connectors.
|
|
3
3
|
*/
|
|
4
4
|
import type { DataSourceType, DataSourceConfig, DataSchema } from '../types.js';
|
|
5
|
+
/** Strip inline userinfo (`user:pass@`) from a connection string / URI. */
|
|
6
|
+
export declare function redactUri(uri: string): string;
|
|
7
|
+
/** Redact secrets from a source config so it can safely reach a model context, a terminal, or a
|
|
8
|
+
* log. `list_data` and `dolex sources list` MUST pass configs through this — the registry stores
|
|
9
|
+
* passwords/URIs in plaintext (owner-only file), but they must never be echoed back out. */
|
|
10
|
+
export declare function redactConfig(config: DataSourceConfig): DataSourceConfig;
|
|
11
|
+
/** Registry entry with its config secrets redacted (see redactConfig). */
|
|
12
|
+
export declare function redactEntry(entry: SourceRegistryEntry): SourceRegistryEntry;
|
|
5
13
|
/**
|
|
6
14
|
* Reflect a session-derived column in a connector's cached schema, so downstream consumers
|
|
7
15
|
* (schemaText, describe_data) see it. Shared by the live connectors' applyDerivation
|
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Connector-specific types for Dolex data source connectors.
|
|
3
3
|
*/
|
|
4
|
+
const SECRET_MASK = '•••';
|
|
5
|
+
/** Strip inline userinfo (`user:pass@`) from a connection string / URI. */
|
|
6
|
+
export function redactUri(uri) {
|
|
7
|
+
return uri.replace(/(:\/\/)[^/@]*@/, `$1${SECRET_MASK}@`);
|
|
8
|
+
}
|
|
9
|
+
/** Redact secrets from a source config so it can safely reach a model context, a terminal, or a
|
|
10
|
+
* log. `list_data` and `dolex sources list` MUST pass configs through this — the registry stores
|
|
11
|
+
* passwords/URIs in plaintext (owner-only file), but they must never be echoed back out. */
|
|
12
|
+
export function redactConfig(config) {
|
|
13
|
+
const c = { ...config };
|
|
14
|
+
if (typeof c.password === 'string' && c.password)
|
|
15
|
+
c.password = SECRET_MASK;
|
|
16
|
+
if (typeof c.connectionString === 'string')
|
|
17
|
+
c.connectionString = redactUri(c.connectionString);
|
|
18
|
+
if (typeof c.uri === 'string')
|
|
19
|
+
c.uri = redactUri(c.uri);
|
|
20
|
+
return c;
|
|
21
|
+
}
|
|
22
|
+
/** Registry entry with its config secrets redacted (see redactConfig). */
|
|
23
|
+
export function redactEntry(entry) {
|
|
24
|
+
return { ...entry, config: redactConfig(entry.config) };
|
|
25
|
+
}
|
|
4
26
|
/**
|
|
5
27
|
* Reflect a session-derived column in a connector's cached schema, so downstream consumers
|
|
6
28
|
* (schemaText, describe_data) see it. Shared by the live connectors' applyDerivation
|
package/dist/src/mcp/index.js
CHANGED
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
*/
|
|
29
29
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
30
30
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
31
|
-
import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE, } from '@modelcontextprotocol/ext-apps/server';
|
|
31
|
+
import { registerAppTool, registerAppResource, getUiCapability, RESOURCE_MIME_TYPE, } from '@modelcontextprotocol/ext-apps/server';
|
|
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';
|
|
@@ -65,6 +65,7 @@ const dolexDir = join(homedir(), '.dolex');
|
|
|
65
65
|
mkdirSync(dolexDir, { recursive: true });
|
|
66
66
|
const sourceManager = new SourceManager(join(dolexDir, 'sources.json'));
|
|
67
67
|
const serverStartTime = Date.now();
|
|
68
|
+
const { version } = JSON.parse(readFileSync(packagePath(import.meta.url, 'package.json'), 'utf-8'));
|
|
68
69
|
const iconPath = packagePath(import.meta.url, 'assets', 'icon.svg');
|
|
69
70
|
let serverIcons;
|
|
70
71
|
try {
|
|
@@ -75,7 +76,7 @@ catch { }
|
|
|
75
76
|
// ─── CREATE SERVER ──────────────────────────────────────────────────────────
|
|
76
77
|
const server = new McpServer({
|
|
77
78
|
name: 'dolex',
|
|
78
|
-
version
|
|
79
|
+
version,
|
|
79
80
|
...(serverIcons && { icons: serverIcons }),
|
|
80
81
|
}, {
|
|
81
82
|
instructions: [
|
|
@@ -117,6 +118,20 @@ const server = new McpServer({
|
|
|
117
118
|
].join('\n'),
|
|
118
119
|
});
|
|
119
120
|
// ─── REGISTER TOOLS ─────────────────────────────────────────────────────────
|
|
121
|
+
// The chart HTML rides in structuredContent. A host that renders MCP Apps (it says so at
|
|
122
|
+
// initialize) hands that to the chart view and keeps it out of the model's context. Other
|
|
123
|
+
// clients (Claude Code, Cursor) give structuredContent to the model instead, and a chart of
|
|
124
|
+
// a thousand-odd rows is past their tool-output limit, so they get the text result alone.
|
|
125
|
+
function chartForHost(handler) {
|
|
126
|
+
return async (args) => {
|
|
127
|
+
const result = await handler(args);
|
|
128
|
+
if (getUiCapability(server.server.getClientCapabilities())?.mimeTypes?.includes(RESOURCE_MIME_TYPE))
|
|
129
|
+
return result;
|
|
130
|
+
const text = { ...result };
|
|
131
|
+
delete text.structuredContent;
|
|
132
|
+
return text;
|
|
133
|
+
};
|
|
134
|
+
}
|
|
120
135
|
// Inline data visualization tool
|
|
121
136
|
registerAppTool(server, 'visualize', {
|
|
122
137
|
title: 'Visualize Data',
|
|
@@ -130,7 +145,7 @@ registerAppTool(server, 'visualize', {
|
|
|
130
145
|
},
|
|
131
146
|
},
|
|
132
147
|
},
|
|
133
|
-
}, handleVisualize(selectPatternCallback, { sourceManager }));
|
|
148
|
+
}, chartForHost(handleVisualize(selectPatternCallback, { sourceManager })));
|
|
134
149
|
server.registerTool('list_patterns', {
|
|
135
150
|
title: 'List Visualization Patterns',
|
|
136
151
|
description: 'Browse all 43 chart types with data requirements, capabilities, and config options.',
|
|
@@ -147,7 +162,7 @@ registerAppTool(server, 'refine_visualization', {
|
|
|
147
162
|
},
|
|
148
163
|
},
|
|
149
164
|
},
|
|
150
|
-
}, handleRefine());
|
|
165
|
+
}, chartForHost(handleRefine()));
|
|
151
166
|
// CSV data management tools
|
|
152
167
|
server.registerTool('load_source', {
|
|
153
168
|
title: 'Load a data source',
|
|
@@ -286,6 +301,10 @@ async function main() {
|
|
|
286
301
|
};
|
|
287
302
|
process.on('SIGINT', shutdown);
|
|
288
303
|
process.on('SIGTERM', shutdown);
|
|
304
|
+
// A client stops a stdio server by closing its stdin, and a client (or the npx in front of
|
|
305
|
+
// this process) that dies leaves only that behind. Without this the purge interval keeps
|
|
306
|
+
// the process running forever.
|
|
307
|
+
process.stdin.on('end', shutdown);
|
|
289
308
|
}
|
|
290
309
|
main().catch((error) => {
|
|
291
310
|
console.error('Fatal error:', error);
|
|
@@ -7,7 +7,7 @@ import { buildAnalysisPlan } from '../../analysis/planner.js';
|
|
|
7
7
|
import { plannerDialectForSource, PlannerUnsupportedSourceError } from '../../analysis/rules.js';
|
|
8
8
|
import { errorResponse, jsonResponse } from './shared.js';
|
|
9
9
|
export const analyzeSourceInputSchema = z.object({
|
|
10
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
10
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
11
11
|
table: z.string().optional().describe('Table to analyze (defaults to first table)'),
|
|
12
12
|
maxSteps: z.number().min(1).max(10).optional().describe('Maximum analysis steps (default: 6)'),
|
|
13
13
|
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
export const cleanColumnSchema = z.object({
|
|
3
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
3
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
4
4
|
table: z.string().describe('Table name within the source'),
|
|
5
5
|
column: z.string().describe('The column to clean'),
|
|
6
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,8 +7,8 @@ import { saveResult } from './result-cache.js';
|
|
|
7
7
|
import { errorResponse, jsonResponse } from './shared.js';
|
|
8
8
|
import { logOperation } from './operation-log.js';
|
|
9
9
|
export const querySourceInputSchema = z.object({
|
|
10
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
11
|
-
sql: z.string().describe('SQL SELECT query. Use table and column names from
|
|
10
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
11
|
+
sql: z.string().describe('SQL SELECT query. Use table and column names from load_source/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) {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* MCP Tools: list_data,
|
|
2
|
+
* MCP Tools: list_data, load_source, remove_data, describe_data, test_source
|
|
3
3
|
* Manage CSV datasets.
|
|
4
4
|
*/
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { errorResponse, jsonResponse } from './shared.js';
|
|
7
7
|
import { resolveSourceConfig } from '../../connectors/source-factory.js';
|
|
8
|
+
import { redactEntry } from '../../connectors/types.js';
|
|
8
9
|
const SANDBOX_PATH_PATTERNS = [
|
|
9
10
|
/^\/mnt\/user-data\//,
|
|
10
11
|
/^\/home\/claude\//,
|
|
@@ -29,10 +30,10 @@ export const addSourceInputSchema = z.object({
|
|
|
29
30
|
collections: z.array(z.string()).optional().describe('MongoDB: restrict to these collections'),
|
|
30
31
|
});
|
|
31
32
|
export const removeSourceInputSchema = z.object({
|
|
32
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
33
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
33
34
|
});
|
|
34
35
|
export const describeSourceInputSchema = z.object({
|
|
35
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
36
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
36
37
|
table: z.string().optional().describe('Table name (optional — if omitted, returns all tables)'),
|
|
37
38
|
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'),
|
|
38
39
|
});
|
|
@@ -64,7 +65,7 @@ async function buildTableProfile(t, connectedSource, detail = 'full') {
|
|
|
64
65
|
};
|
|
65
66
|
}
|
|
66
67
|
/**
|
|
67
|
-
* Build a smart summary for
|
|
68
|
+
* Build a smart summary for load_source — minimal tokens but enough to write SQL.
|
|
68
69
|
* - Categorical columns (≤20 unique): list the values
|
|
69
70
|
* - Categorical columns (>20 unique): just show count
|
|
70
71
|
* - Numeric columns: show min/max range
|
|
@@ -118,7 +119,8 @@ function buildSmartSummary(t) {
|
|
|
118
119
|
return lines.join('\n');
|
|
119
120
|
}
|
|
120
121
|
export function handleListSources(deps) {
|
|
121
|
-
|
|
122
|
+
// Redact credentials — this response flows straight into the model's context / transcript.
|
|
123
|
+
return async () => jsonResponse(deps.sourceManager.list().map(redactEntry));
|
|
122
124
|
}
|
|
123
125
|
export const testSourceInputSchema = z.object({
|
|
124
126
|
sourceId: z.string().describe('Source id or name to health-check'),
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
import { rowFilterSchema } from './sql-schemas.js';
|
|
6
6
|
export const transformDataBaseSchema = z.object({
|
|
7
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
7
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
8
8
|
table: z.string().describe('Table name within the source'),
|
|
9
9
|
create: z.string().optional().describe('Column name to create (single-column mode)'),
|
|
10
10
|
expr: z.string().optional().describe('Expression to evaluate (single-column mode). Examples: "score * 2", "zscore(score)", "if_else(age > 18, \"adult\", \"minor\")".'),
|
|
@@ -18,16 +18,16 @@ export const transformDataBaseSchema = z.object({
|
|
|
18
18
|
});
|
|
19
19
|
export const transformDataSchema = transformDataBaseSchema.refine((d) => (d.create && d.expr) || d.transforms, { message: 'Provide either (create + expr) for single-column mode, or transforms array for batch mode' }).refine((d) => !((d.create || d.expr) && d.transforms), { message: 'Cannot use both single-column and batch mode' });
|
|
20
20
|
export const promoteColumnsSchema = z.object({
|
|
21
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
21
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
22
22
|
table: z.string().describe('Table name within the source'),
|
|
23
23
|
columns: z.array(z.string()).describe('Column names to promote from working → derived. Use ["*"] to promote all working columns.'),
|
|
24
24
|
});
|
|
25
25
|
export const listTransformsSchema = z.object({
|
|
26
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
26
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
27
27
|
table: z.string().describe('Table name within the source'),
|
|
28
28
|
});
|
|
29
29
|
export const dropColumnsSchema = z.object({
|
|
30
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
30
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
31
31
|
table: z.string().describe('Table name within the source'),
|
|
32
32
|
columns: z.array(z.string()).describe('Column names to drop. Use ["*"] to drop all columns in the specified layer.'),
|
|
33
33
|
layer: z.enum(['derived', 'working']).optional().describe('Which layer to drop from. If omitted, auto-detects.'),
|