@ecubelabs/mysql-mcp 1.0.0-next.7 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +296 -448
- package/dist/index.js +377 -239
- package/dist/src/catalog/collect.js +3 -2
- package/dist/src/catalog/docs.js +14 -12
- package/dist/src/catalog/index.js +59 -99
- package/dist/src/catalog/render.js +4 -10
- package/dist/src/catalog/store.js +193 -76
- package/dist/src/catalog/types.js +0 -12
- package/dist/src/config/index.js +175 -0
- package/dist/src/db/index.js +379 -379
- package/dist/src/db/permissions.js +32 -16
- package/dist/src/db/utils.js +3 -1
- package/dist/src/ssh/config.js +34 -27
- package/dist/src/ssh/tunnel.js +238 -155
- package/dist/src/utils/index.js +4 -35
- package/package.json +4 -4
- package/dist/src/catalog/context.js +0 -187
- package/dist/src/catalog/lock.js +0 -113
- package/dist/src/config/args.js +0 -30
- package/dist/src/config/load.js +0 -169
- package/dist/src/config/schema.js +0 -351
- package/dist/src/config/secrets.js +0 -128
- package/dist/src/config/ssl.js +0 -25
- package/dist/src/db/registry.js +0 -178
- package/dist/src/init/check.js +0 -31
- package/dist/src/init/cli.js +0 -26
- package/dist/src/init/config-edit.js +0 -95
- package/dist/src/init/prompt.js +0 -82
- package/dist/src/init/wizard.js +0 -223
- package/dist/src/server/catalog-tool.js +0 -91
- package/dist/src/server/connections.js +0 -117
|
@@ -1,10 +1,123 @@
|
|
|
1
1
|
import * as fs from 'fs';
|
|
2
2
|
import * as path from 'path';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { loadedCodeBranches } from './branch.js';
|
|
4
|
+
import { normalizeDocumentPath, normalizeGithubRepo } from './docs.js';
|
|
5
|
+
import { loadedSchemaOwner, schemaOwnerOf } from './owner.js';
|
|
5
6
|
import { CATALOG_VERSION, emptyCatalog, emptyTable, normalizeName, pruneJoins } from './types.js';
|
|
6
7
|
const FLUSH_DELAY_MS = 2_000;
|
|
8
|
+
const LOCK_RETRY_MS = 25;
|
|
9
|
+
const LOCK_WAIT_MS = 15_000;
|
|
10
|
+
const LOCK_CLOSE_WAIT_MS = 2_000;
|
|
11
|
+
const LOCK_STALE_MS = 30_000;
|
|
7
12
|
const CLOSE_FLUSH_ATTEMPTS = 2;
|
|
13
|
+
class CatalogLockTimeoutError extends Error {
|
|
14
|
+
}
|
|
15
|
+
function errorCode(error) {
|
|
16
|
+
return error && typeof error === 'object' && 'code' in error ? String(error.code) : null;
|
|
17
|
+
}
|
|
18
|
+
function processIsAlive(pid) {
|
|
19
|
+
try {
|
|
20
|
+
process.kill(pid, 0);
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
return errorCode(error) !== 'ESRCH';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function delay(ms) {
|
|
28
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
29
|
+
}
|
|
30
|
+
async function acquireCatalogLock(filePath, waitMs) {
|
|
31
|
+
const lockPath = `${filePath}.lock`;
|
|
32
|
+
const deadline = Date.now() + waitMs;
|
|
33
|
+
const record = {
|
|
34
|
+
pid: process.pid,
|
|
35
|
+
token: `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
|
|
36
|
+
createdAt: Date.now(),
|
|
37
|
+
};
|
|
38
|
+
while (true) {
|
|
39
|
+
try {
|
|
40
|
+
const handle = await fs.promises.open(lockPath, 'wx', 0o600);
|
|
41
|
+
try {
|
|
42
|
+
await handle.writeFile(JSON.stringify(record), 'utf8');
|
|
43
|
+
await handle.sync();
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
await handle.close().catch(() => undefined);
|
|
47
|
+
await fs.promises.unlink(lockPath).catch(() => undefined);
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
let released = false;
|
|
51
|
+
return async () => {
|
|
52
|
+
if (released) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
released = true;
|
|
56
|
+
await handle.close();
|
|
57
|
+
try {
|
|
58
|
+
const current = JSON.parse(await fs.promises.readFile(lockPath, 'utf8'));
|
|
59
|
+
if (current.token === record.token) {
|
|
60
|
+
await fs.promises.unlink(lockPath);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (errorCode(error) !== 'ENOENT') {
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (errorCode(error) !== 'EEXIST') {
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
let lockText = null;
|
|
75
|
+
let stale = false;
|
|
76
|
+
try {
|
|
77
|
+
const [text, stat] = await Promise.all([
|
|
78
|
+
fs.promises.readFile(lockPath, 'utf8'),
|
|
79
|
+
fs.promises.stat(lockPath),
|
|
80
|
+
]);
|
|
81
|
+
lockText = text;
|
|
82
|
+
let owner = {};
|
|
83
|
+
try {
|
|
84
|
+
owner = JSON.parse(text);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
}
|
|
88
|
+
stale =
|
|
89
|
+
typeof owner.pid === 'number'
|
|
90
|
+
? !processIsAlive(owner.pid)
|
|
91
|
+
: Date.now() - stat.mtimeMs >= LOCK_STALE_MS;
|
|
92
|
+
}
|
|
93
|
+
catch (readError) {
|
|
94
|
+
if (errorCode(readError) === 'ENOENT') {
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
throw readError;
|
|
98
|
+
}
|
|
99
|
+
if (stale && lockText !== null) {
|
|
100
|
+
try {
|
|
101
|
+
if ((await fs.promises.readFile(lockPath, 'utf8')) === lockText) {
|
|
102
|
+
await fs.promises.unlink(lockPath);
|
|
103
|
+
console.error(`[catalog] removed stale lock ${lockPath}`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
catch (cleanupError) {
|
|
108
|
+
if (errorCode(cleanupError) === 'ENOENT') {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
throw cleanupError;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (Date.now() >= deadline) {
|
|
115
|
+
throw new CatalogLockTimeoutError(`timed out after ${waitMs}ms waiting for catalog lock ${lockPath}`);
|
|
116
|
+
}
|
|
117
|
+
await delay(LOCK_RETRY_MS + Math.floor(Math.random() * LOCK_RETRY_MS));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
8
121
|
const EPOCH = new Date(0).toISOString();
|
|
9
122
|
function timestamp(value) {
|
|
10
123
|
if (!value) {
|
|
@@ -13,6 +126,30 @@ function timestamp(value) {
|
|
|
13
126
|
const parsed = Date.parse(value);
|
|
14
127
|
return Number.isFinite(parsed) ? parsed : 0;
|
|
15
128
|
}
|
|
129
|
+
function mergeEditedSet(external, local, base) {
|
|
130
|
+
const merged = new Set(external);
|
|
131
|
+
for (const previous of base) {
|
|
132
|
+
if (!local.includes(previous)) {
|
|
133
|
+
merged.delete(previous);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
for (const current of local) {
|
|
137
|
+
if (!base.includes(current)) {
|
|
138
|
+
merged.add(current);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return [...merged];
|
|
142
|
+
}
|
|
143
|
+
function mergeCurated(external, local, base) {
|
|
144
|
+
const baseDoc = Object.prototype.hasOwnProperty.call(base ?? {}, 'doc') ? JSON.stringify(base?.doc) : '__missing__';
|
|
145
|
+
const localDoc = Object.prototype.hasOwnProperty.call(local, 'doc') ? JSON.stringify(local.doc) : '__missing__';
|
|
146
|
+
const chosen = localDoc !== baseDoc ? local : external;
|
|
147
|
+
return {
|
|
148
|
+
notes: mergeEditedSet(external.notes ?? [], local.notes ?? [], base?.notes ?? []),
|
|
149
|
+
aliases: mergeEditedSet(external.aliases ?? [], local.aliases ?? [], base?.aliases ?? []),
|
|
150
|
+
...(Object.prototype.hasOwnProperty.call(chosen, 'doc') ? { doc: chosen.doc } : {}),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
16
153
|
function mergedCounter(external, local, base) {
|
|
17
154
|
if (local < base) {
|
|
18
155
|
return local + Math.max(0, external - base);
|
|
@@ -61,9 +198,14 @@ function mergeTable(external, local, base) {
|
|
|
61
198
|
lastUsedAt: newerUsageTimestamp(external.usage?.lastUsedAt, local.usage?.lastUsedAt, externalUsageCount, localUsageCount, baseUsageCount),
|
|
62
199
|
columns: Object.fromEntries(columns),
|
|
63
200
|
},
|
|
64
|
-
curated:
|
|
201
|
+
curated: mergeCurated(external.curated ?? { notes: [], aliases: [] }, local.curated ?? { notes: [], aliases: [] }, base?.curated),
|
|
65
202
|
};
|
|
66
203
|
}
|
|
204
|
+
function mergeOwner(external, local, base) {
|
|
205
|
+
const localOwner = schemaOwnerOf(local);
|
|
206
|
+
const baseOwner = base ? schemaOwnerOf(base) : null;
|
|
207
|
+
return JSON.stringify(localOwner) !== JSON.stringify(baseOwner) ? localOwner : schemaOwnerOf(external);
|
|
208
|
+
}
|
|
67
209
|
function mergeSchema(external, local, base) {
|
|
68
210
|
const newerInventory = timestamp(local.scannedAt) >= timestamp(external.scannedAt) ? local : external;
|
|
69
211
|
const olderInventory = newerInventory === local ? external : local;
|
|
@@ -73,7 +215,17 @@ function mergeSchema(external, local, base) {
|
|
|
73
215
|
? mergeTable(newerInventory === local ? olderInventory.tables[name] : table, newerInventory === local ? table : olderInventory.tables[name], base?.tables[name])
|
|
74
216
|
: table;
|
|
75
217
|
}
|
|
76
|
-
return { scannedAt: newerInventory.scannedAt, tables };
|
|
218
|
+
return { ...mergeOwner(external, local, base), scannedAt: newerInventory.scannedAt, tables };
|
|
219
|
+
}
|
|
220
|
+
function mergeCodeBranches(external, local, base) {
|
|
221
|
+
const merged = {};
|
|
222
|
+
for (const repo of new Set([...Object.keys(external), ...Object.keys(local), ...Object.keys(base)])) {
|
|
223
|
+
const branch = local[repo] !== base[repo] ? local[repo] : external[repo];
|
|
224
|
+
if (branch !== undefined) {
|
|
225
|
+
merged[repo] = branch;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return merged;
|
|
77
229
|
}
|
|
78
230
|
function mergeCatalog(external, local, base) {
|
|
79
231
|
const schemas = {};
|
|
@@ -110,39 +262,32 @@ function mergeCatalog(external, local, base) {
|
|
|
110
262
|
}
|
|
111
263
|
return {
|
|
112
264
|
...local,
|
|
113
|
-
codeBranches:
|
|
265
|
+
codeBranches: mergeCodeBranches(external.codeBranches, local.codeBranches, base.codeBranches),
|
|
114
266
|
schemas,
|
|
115
267
|
joins: pruneJoins([...joins.values()]),
|
|
116
268
|
};
|
|
117
269
|
}
|
|
118
|
-
function
|
|
119
|
-
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
270
|
+
function loadedDocumentDecision(curated) {
|
|
271
|
+
if (!curated || !Object.prototype.hasOwnProperty.call(curated, 'doc')) {
|
|
272
|
+
return {};
|
|
273
|
+
}
|
|
274
|
+
const doc = curated.doc;
|
|
275
|
+
if (!doc) {
|
|
276
|
+
return { doc: null };
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
return {
|
|
280
|
+
doc: {
|
|
281
|
+
path: normalizeDocumentPath(String(doc.path ?? '')),
|
|
282
|
+
repo: normalizeGithubRepo(doc.repo),
|
|
283
|
+
linkedBy: doc.linkedBy ?? 'model',
|
|
284
|
+
linkedAt: doc.linkedAt ?? EPOCH,
|
|
130
285
|
},
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const recorded = context.schemas[schema]?.tables[table];
|
|
136
|
-
if (!recorded) {
|
|
137
|
-
return emptyCurated();
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
return {};
|
|
138
290
|
}
|
|
139
|
-
return {
|
|
140
|
-
notes: [...recorded.notes],
|
|
141
|
-
aliases: [...recorded.aliases],
|
|
142
|
-
...(Object.prototype.hasOwnProperty.call(recorded, 'doc')
|
|
143
|
-
? { doc: recorded.doc ? { ...recorded.doc } : null }
|
|
144
|
-
: {}),
|
|
145
|
-
};
|
|
146
291
|
}
|
|
147
292
|
export class CatalogStore {
|
|
148
293
|
options;
|
|
@@ -155,10 +300,8 @@ export class CatalogStore {
|
|
|
155
300
|
flushedRevision = 0;
|
|
156
301
|
closing = false;
|
|
157
302
|
nameIndex = null;
|
|
158
|
-
|
|
159
|
-
constructor(options, context) {
|
|
303
|
+
constructor(options) {
|
|
160
304
|
this.options = options;
|
|
161
|
-
this.context = context ?? { store: new ContextStore(null), env: options.profile, instance: 'default' };
|
|
162
305
|
this.enabled = options.enabled;
|
|
163
306
|
this.data = emptyCatalog(options);
|
|
164
307
|
this.baseData = structuredClone(this.data);
|
|
@@ -205,12 +348,14 @@ export class CatalogStore {
|
|
|
205
348
|
}
|
|
206
349
|
sanitizeLoaded(loaded) {
|
|
207
350
|
const fresh = emptyCatalog(this.options);
|
|
351
|
+
fresh.codeBranches = loadedCodeBranches(loaded.codeBranches);
|
|
208
352
|
const loadedSchemas = loaded.schemas && typeof loaded.schemas === 'object' ? loaded.schemas : {};
|
|
209
353
|
for (const [schemaName, cached] of Object.entries(loadedSchemas)) {
|
|
210
354
|
if (!cached || typeof cached !== 'object') {
|
|
211
355
|
continue;
|
|
212
356
|
}
|
|
213
357
|
const schema = {
|
|
358
|
+
...loadedSchemaOwner(cached),
|
|
214
359
|
scannedAt: cached.scannedAt ?? null,
|
|
215
360
|
tables: {},
|
|
216
361
|
};
|
|
@@ -231,7 +376,11 @@ export class CatalogStore {
|
|
|
231
376
|
lastUsedAt: raw.usage?.lastUsedAt ?? null,
|
|
232
377
|
columns: raw.usage?.columns ?? {},
|
|
233
378
|
},
|
|
234
|
-
curated:
|
|
379
|
+
curated: {
|
|
380
|
+
notes: raw.curated?.notes ?? [],
|
|
381
|
+
aliases: raw.curated?.aliases ?? [],
|
|
382
|
+
...loadedDocumentDecision(raw.curated),
|
|
383
|
+
},
|
|
235
384
|
};
|
|
236
385
|
schema.tables[tableName] = table;
|
|
237
386
|
}
|
|
@@ -270,35 +419,10 @@ export class CatalogStore {
|
|
|
270
419
|
return index;
|
|
271
420
|
}
|
|
272
421
|
snapshot() {
|
|
273
|
-
|
|
274
|
-
const context = this.readContext();
|
|
275
|
-
snapshot.codeBranches = { ...context.codeBranches };
|
|
276
|
-
for (const [schemaName, schema] of Object.entries(snapshot.schemas)) {
|
|
277
|
-
const recorded = context.schemas[schemaName];
|
|
278
|
-
if (recorded?.owner) {
|
|
279
|
-
schema.repo = recorded.owner.repo;
|
|
280
|
-
schema.app = recorded.owner.app;
|
|
281
|
-
}
|
|
282
|
-
if (recorded && recorded.notes.length > 0) {
|
|
283
|
-
schema.notes = [...recorded.notes];
|
|
284
|
-
}
|
|
285
|
-
for (const tableName of Object.keys(schema.tables)) {
|
|
286
|
-
schema.tables[tableName].curated = curatedFrom(context, schemaName, tableName);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
return snapshot;
|
|
290
|
-
}
|
|
291
|
-
readContext() {
|
|
292
|
-
return this.context.store.read(this.context.env, this.context.instance);
|
|
293
|
-
}
|
|
294
|
-
updateContext(mutator) {
|
|
295
|
-
return this.context.store.update(this.context.env, this.context.instance, mutator);
|
|
422
|
+
return structuredClone(this.data);
|
|
296
423
|
}
|
|
297
424
|
codeBranches() {
|
|
298
|
-
return this.
|
|
299
|
-
}
|
|
300
|
-
schemaNotes(schema) {
|
|
301
|
-
return [...(this.readContext().schemas[schema]?.notes ?? [])];
|
|
425
|
+
return this.data.codeBranches;
|
|
302
426
|
}
|
|
303
427
|
lookup(schemaHint, table) {
|
|
304
428
|
const index = this.ensureNameIndex();
|
|
@@ -316,9 +440,6 @@ export class CatalogStore {
|
|
|
316
440
|
}
|
|
317
441
|
return matches;
|
|
318
442
|
}
|
|
319
|
-
schemaNames() {
|
|
320
|
-
return Object.keys(this.data.schemas);
|
|
321
|
-
}
|
|
322
443
|
schemaScanTimes() {
|
|
323
444
|
return Object.values(this.data.schemas).map((schema) => schema.scannedAt);
|
|
324
445
|
}
|
|
@@ -327,9 +448,10 @@ export class CatalogStore {
|
|
|
327
448
|
}
|
|
328
449
|
schemaOwners() {
|
|
329
450
|
const owners = {};
|
|
330
|
-
for (const [name, schema] of Object.entries(this.
|
|
331
|
-
|
|
332
|
-
|
|
451
|
+
for (const [name, schema] of Object.entries(this.data.schemas)) {
|
|
452
|
+
const owner = schemaOwnerOf(schema);
|
|
453
|
+
if (owner) {
|
|
454
|
+
owners[name] = owner;
|
|
333
455
|
}
|
|
334
456
|
}
|
|
335
457
|
return owners;
|
|
@@ -342,7 +464,7 @@ export class CatalogStore {
|
|
|
342
464
|
return {
|
|
343
465
|
detailScannedAt: entry.detailScannedAt,
|
|
344
466
|
detailStale: entry.detailStale === true,
|
|
345
|
-
docReviewed: Object.prototype.hasOwnProperty.call(
|
|
467
|
+
docReviewed: Object.prototype.hasOwnProperty.call(entry.curated, 'doc'),
|
|
346
468
|
};
|
|
347
469
|
}
|
|
348
470
|
tableIndexes(schema, table) {
|
|
@@ -365,12 +487,7 @@ export class CatalogStore {
|
|
|
365
487
|
}
|
|
366
488
|
readTable(schema, table) {
|
|
367
489
|
const entry = this.data.schemas[schema]?.tables[table];
|
|
368
|
-
|
|
369
|
-
return null;
|
|
370
|
-
}
|
|
371
|
-
const copy = structuredClone(entry);
|
|
372
|
-
copy.curated = curatedFrom(this.readContext(), schema, table);
|
|
373
|
-
return copy;
|
|
490
|
+
return entry ? structuredClone(entry) : null;
|
|
374
491
|
}
|
|
375
492
|
hasSuccessfulUse() {
|
|
376
493
|
for (const schema of Object.values(this.data.schemas)) {
|
|
@@ -441,7 +558,7 @@ export class CatalogStore {
|
|
|
441
558
|
this.data = toWrite;
|
|
442
559
|
this.invalidateNameIndex();
|
|
443
560
|
}
|
|
444
|
-
const payload = `${JSON.stringify(
|
|
561
|
+
const payload = `${JSON.stringify(toWrite, null, 2)}\n`;
|
|
445
562
|
const persisted = structuredClone(toWrite);
|
|
446
563
|
await fs.promises.writeFile(tempPath, payload, {
|
|
447
564
|
encoding: 'utf8',
|
|
@@ -42,15 +42,3 @@ export function emptyCatalog(options) {
|
|
|
42
42
|
joins: [],
|
|
43
43
|
};
|
|
44
44
|
}
|
|
45
|
-
export function emptyInstanceContext() {
|
|
46
|
-
return { codeBranches: {}, schemas: {} };
|
|
47
|
-
}
|
|
48
|
-
export function emptySchemaContext() {
|
|
49
|
-
return { notes: [], tables: {} };
|
|
50
|
-
}
|
|
51
|
-
export function schemaContext(context, schema) {
|
|
52
|
-
return (context.schemas[schema] ??= emptySchemaContext());
|
|
53
|
-
}
|
|
54
|
-
export function tableContext(context, schema, table) {
|
|
55
|
-
return (schemaContext(context, schema).tables[table] ??= { notes: [], aliases: [] });
|
|
56
|
-
}
|
package/dist/src/config/index.js
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
import * as fs from 'fs';
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import { fileURLToPath } from 'url';
|
|
4
|
+
function parseSchemaPermissions(permissionsString) {
|
|
5
|
+
const permissions = {};
|
|
6
|
+
if (!permissionsString) {
|
|
7
|
+
return permissions;
|
|
8
|
+
}
|
|
9
|
+
for (const pair of permissionsString.split(',')) {
|
|
10
|
+
const [schema, value] = pair.split(':');
|
|
11
|
+
if (schema && value) {
|
|
12
|
+
permissions[schema.trim()] = value.trim() === 'true';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return permissions;
|
|
16
|
+
}
|
|
17
|
+
function readSSLFile(filePath, label) {
|
|
18
|
+
try {
|
|
19
|
+
if (!fs.existsSync(filePath)) {
|
|
20
|
+
throw new Error(`SSL ${label} file not found: ${filePath}`);
|
|
21
|
+
}
|
|
22
|
+
const data = fs.readFileSync(filePath);
|
|
23
|
+
if (data.length === 0) {
|
|
24
|
+
throw new Error(`SSL ${label} file is empty: ${filePath}`);
|
|
25
|
+
}
|
|
26
|
+
return data;
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error instanceof Error) {
|
|
30
|
+
if (error.message.startsWith('SSL ')) {
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
throw new Error(`Failed to read SSL ${label}: ${error.message}`);
|
|
34
|
+
}
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function readCACertificate(filePath) {
|
|
39
|
+
return readSSLFile(filePath, 'CA certificate');
|
|
40
|
+
}
|
|
4
41
|
const PACKAGE_NAME = '@ecubelabs/mysql-mcp';
|
|
5
42
|
export function readPackageVersion(startDir) {
|
|
6
43
|
let dir = startDir;
|
|
@@ -20,4 +57,142 @@ export function readPackageVersion(startDir) {
|
|
|
20
57
|
dir = parent;
|
|
21
58
|
}
|
|
22
59
|
}
|
|
60
|
+
export const MYSQL_PROFILE = (process.env.MYSQL_PROFILE ?? '').trim().toLowerCase();
|
|
61
|
+
const WRITE_FORBIDDEN_PROFILES = new Set(['prod', 'production']);
|
|
62
|
+
export const IS_WRITE_FORBIDDEN_PROFILE = WRITE_FORBIDDEN_PROFILES.has(MYSQL_PROFILE);
|
|
63
|
+
export const PROFILE_LABEL = MYSQL_PROFILE ? MYSQL_PROFILE.toUpperCase() : 'UNSPECIFIED';
|
|
64
|
+
export const MYSQL_CATALOG_ENABLED = process.env.MYSQL_CATALOG_ENABLED !== 'false';
|
|
65
|
+
export const MYSQL_CATALOG_PATH = process.env.MYSQL_CATALOG_PATH?.trim() || undefined;
|
|
66
|
+
function parseCatalogTtl(raw) {
|
|
67
|
+
if (!raw) {
|
|
68
|
+
return 24;
|
|
69
|
+
}
|
|
70
|
+
const value = Number(raw);
|
|
71
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
72
|
+
console.error(`[config] ignoring MYSQL_CATALOG_TTL_HOURS="${raw}": expected a positive number; using 24.`);
|
|
73
|
+
return 24;
|
|
74
|
+
}
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
export const MYSQL_CATALOG_TTL_HOURS = parseCatalogTtl(process.env.MYSQL_CATALOG_TTL_HOURS);
|
|
78
|
+
export const ENABLE_LOGGING = process.env.ENABLE_LOGGING === 'true' || process.env.ENABLE_LOGGING === '1';
|
|
23
79
|
export const PACKAGE_VERSION = readPackageVersion(path.dirname(fileURLToPath(import.meta.url))) ?? 'unknown';
|
|
80
|
+
export const MYSQL_DB = process.env.MYSQL_DB?.trim() || undefined;
|
|
81
|
+
const envFlag = (name) => process.env[name] === 'true';
|
|
82
|
+
const writeFlag = (name) => (IS_WRITE_FORBIDDEN_PROFILE ? false : envFlag(name));
|
|
83
|
+
if (IS_WRITE_FORBIDDEN_PROFILE) {
|
|
84
|
+
const requested = [
|
|
85
|
+
...['ALLOW_INSERT_OPERATION', 'ALLOW_UPDATE_OPERATION', 'ALLOW_DELETE_OPERATION', 'ALLOW_DDL_OPERATION'].filter(envFlag),
|
|
86
|
+
...[
|
|
87
|
+
'SCHEMA_INSERT_PERMISSIONS',
|
|
88
|
+
'SCHEMA_UPDATE_PERMISSIONS',
|
|
89
|
+
'SCHEMA_DELETE_PERMISSIONS',
|
|
90
|
+
'SCHEMA_DDL_PERMISSIONS',
|
|
91
|
+
].filter((name) => Boolean(process.env[name]?.trim())),
|
|
92
|
+
];
|
|
93
|
+
if (requested.length > 0) {
|
|
94
|
+
console.error(`[config] profile "${MYSQL_PROFILE}" is read-only by policy; ignoring ${requested.join(', ')}.`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
export const ALLOW_INSERT_OPERATION = writeFlag('ALLOW_INSERT_OPERATION');
|
|
98
|
+
export const ALLOW_UPDATE_OPERATION = writeFlag('ALLOW_UPDATE_OPERATION');
|
|
99
|
+
export const ALLOW_DELETE_OPERATION = writeFlag('ALLOW_DELETE_OPERATION');
|
|
100
|
+
export const ALLOW_DDL_OPERATION = writeFlag('ALLOW_DDL_OPERATION');
|
|
101
|
+
export const MYSQL_DISABLE_READ_ONLY_TRANSACTIONS = process.env.MYSQL_DISABLE_READ_ONLY_TRANSACTIONS === 'true';
|
|
102
|
+
function parsePositiveInt(name, raw, fallback) {
|
|
103
|
+
if (!raw) {
|
|
104
|
+
return fallback;
|
|
105
|
+
}
|
|
106
|
+
const value = Number(raw);
|
|
107
|
+
if (!Number.isFinite(value) || value < 1) {
|
|
108
|
+
console.error(`[config] ignoring ${name}="${raw}": expected a positive integer; using ${fallback}.`);
|
|
109
|
+
return fallback;
|
|
110
|
+
}
|
|
111
|
+
return Math.floor(value);
|
|
112
|
+
}
|
|
113
|
+
function parsePortEnv(name, raw) {
|
|
114
|
+
const trimmed = raw?.trim();
|
|
115
|
+
if (!trimmed) {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
const port = Number(trimmed);
|
|
119
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
120
|
+
console.error(`[config] ignoring ${name}="${raw}": expected an integer between 0 and 65535.`);
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
return port;
|
|
124
|
+
}
|
|
125
|
+
export const MYSQL_MAX_TIMEOUT_SECONDS = parsePositiveInt('MYSQL_MAX_TIMEOUT_SECONDS', process.env.MYSQL_MAX_TIMEOUT_SECONDS, 30);
|
|
126
|
+
export const MYSQL_DEFAULT_TIMEOUT_SECONDS = Math.min(10, MYSQL_MAX_TIMEOUT_SECONDS);
|
|
127
|
+
export const MYSQL_CATALOG_TIMEOUT_SECONDS = parsePositiveInt('MYSQL_CATALOG_TIMEOUT_SECONDS', process.env.MYSQL_CATALOG_TIMEOUT_SECONDS, 60);
|
|
128
|
+
export const MAX_RESPONSE_ROWS = parsePositiveInt('MYSQL_MAX_RESPONSE_ROWS', process.env.MYSQL_MAX_RESPONSE_ROWS, 5000);
|
|
129
|
+
export const MYSQL_POOL_SIZE = parsePositiveInt('MYSQL_POOL_SIZE', process.env.MYSQL_POOL_SIZE, 10);
|
|
130
|
+
export const MYSQL_QUEUE_LIMIT = parsePositiveInt('MYSQL_QUEUE_LIMIT', process.env.MYSQL_QUEUE_LIMIT, 100);
|
|
131
|
+
export const MYSQL_CONNECT_TIMEOUT = parsePositiveInt('MYSQL_CONNECT_TIMEOUT', process.env.MYSQL_CONNECT_TIMEOUT, 10000);
|
|
132
|
+
export const MYSQL_SOCKET_PATH = process.env.MYSQL_SOCKET_PATH?.trim() || undefined;
|
|
133
|
+
export const MYSQL_HOST = process.env.MYSQL_HOST?.trim() || undefined;
|
|
134
|
+
export const MYSQL_PORT = parsePortEnv('MYSQL_PORT', process.env.MYSQL_PORT) ?? 3306;
|
|
135
|
+
export const DEFAULT_MYSQL_HOST = '127.0.0.1';
|
|
136
|
+
export const MYSQL_SSL_ENABLED = process.env.MYSQL_SSL === 'true';
|
|
137
|
+
export const MYSQL_SSL_REJECT_UNAUTHORIZED = process.env.MYSQL_SSL_REJECT_UNAUTHORIZED === 'true';
|
|
138
|
+
export const MYSQL_SSL_CA_PATH = process.env.MYSQL_SSL_CA?.trim() || undefined;
|
|
139
|
+
export const MYSQL_SSL_CERT_PATH = process.env.MYSQL_SSL_CERT?.trim() || undefined;
|
|
140
|
+
export const MYSQL_SSL_KEY_PATH = process.env.MYSQL_SSL_KEY?.trim() || undefined;
|
|
141
|
+
export const MYSQL_TIMEZONE = process.env.MYSQL_TIMEZONE?.trim() || undefined;
|
|
142
|
+
export const MYSQL_DATE_STRINGS = process.env.MYSQL_DATE_STRINGS === 'true';
|
|
143
|
+
export const MYSQL_BIG_NUMBER_STRINGS = process.env.MYSQL_BIG_NUMBER_STRINGS === 'true';
|
|
144
|
+
export const SSH_REUSE_EXISTING = process.env.MYSQL_SSH_REUSE_EXISTING === 'true';
|
|
145
|
+
export const SSH_CONFIG_HOST = process.env.MYSQL_SSH_CONFIG_HOST?.trim() || undefined;
|
|
146
|
+
export const SSH_HOST = process.env.MYSQL_SSH_HOST?.trim() || undefined;
|
|
147
|
+
export const SSH_USER = process.env.MYSQL_SSH_USER?.trim() || undefined;
|
|
148
|
+
export const SSH_PORT = parsePortEnv('MYSQL_SSH_PORT', process.env.MYSQL_SSH_PORT);
|
|
149
|
+
export const SSH_PRIVATE_KEY_PATH = process.env.MYSQL_SSH_PRIVATE_KEY_PATH?.trim() || undefined;
|
|
150
|
+
export const SSH_PASSPHRASE = process.env.MYSQL_SSH_PASSPHRASE?.trim() || undefined;
|
|
151
|
+
export const SSH_LOCAL_PORT = parsePortEnv('MYSQL_SSH_LOCAL_PORT', process.env.MYSQL_SSH_LOCAL_PORT);
|
|
152
|
+
export const SSH_ENABLED = Boolean(SSH_CONFIG_HOST || SSH_HOST);
|
|
153
|
+
const schemaPermissions = (name) => IS_WRITE_FORBIDDEN_PROFILE ? {} : parseSchemaPermissions(process.env[name]);
|
|
154
|
+
export const SCHEMA_INSERT_PERMISSIONS = schemaPermissions('SCHEMA_INSERT_PERMISSIONS');
|
|
155
|
+
export const SCHEMA_UPDATE_PERMISSIONS = schemaPermissions('SCHEMA_UPDATE_PERMISSIONS');
|
|
156
|
+
export const SCHEMA_DELETE_PERMISSIONS = schemaPermissions('SCHEMA_DELETE_PERMISSIONS');
|
|
157
|
+
export const SCHEMA_DDL_PERMISSIONS = schemaPermissions('SCHEMA_DDL_PERMISSIONS');
|
|
158
|
+
export const isMultiDbMode = !MYSQL_DB;
|
|
159
|
+
const MYSQL_PASS = process.env.MYSQL_PASS ?? '';
|
|
160
|
+
export const mcpConfig = {
|
|
161
|
+
mysql: {
|
|
162
|
+
...(MYSQL_SOCKET_PATH
|
|
163
|
+
? { socketPath: MYSQL_SOCKET_PATH }
|
|
164
|
+
: {
|
|
165
|
+
host: MYSQL_HOST || DEFAULT_MYSQL_HOST,
|
|
166
|
+
port: MYSQL_PORT,
|
|
167
|
+
}),
|
|
168
|
+
user: process.env.MYSQL_USER?.trim() || 'root',
|
|
169
|
+
password: MYSQL_PASS,
|
|
170
|
+
database: MYSQL_DB,
|
|
171
|
+
connectionLimit: MYSQL_POOL_SIZE,
|
|
172
|
+
waitForConnections: true,
|
|
173
|
+
queueLimit: MYSQL_QUEUE_LIMIT,
|
|
174
|
+
enableKeepAlive: true,
|
|
175
|
+
keepAliveInitialDelay: 0,
|
|
176
|
+
connectTimeout: MYSQL_CONNECT_TIMEOUT,
|
|
177
|
+
authPlugins: {
|
|
178
|
+
mysql_clear_password: () => () => Buffer.from(MYSQL_PASS),
|
|
179
|
+
},
|
|
180
|
+
...(MYSQL_SSL_ENABLED
|
|
181
|
+
? {
|
|
182
|
+
ssl: {
|
|
183
|
+
rejectUnauthorized: MYSQL_SSL_REJECT_UNAUTHORIZED,
|
|
184
|
+
...(MYSQL_SSL_CA_PATH ? { ca: readCACertificate(MYSQL_SSL_CA_PATH) } : {}),
|
|
185
|
+
...(MYSQL_SSL_CERT_PATH ? { cert: readSSLFile(MYSQL_SSL_CERT_PATH, 'client certificate') } : {}),
|
|
186
|
+
...(MYSQL_SSL_KEY_PATH ? { key: readSSLFile(MYSQL_SSL_KEY_PATH, 'client private key') } : {}),
|
|
187
|
+
},
|
|
188
|
+
}
|
|
189
|
+
: {}),
|
|
190
|
+
...(MYSQL_TIMEZONE ? { timezone: MYSQL_TIMEZONE } : {}),
|
|
191
|
+
...(MYSQL_DATE_STRINGS ? { dateStrings: true } : {}),
|
|
192
|
+
...(MYSQL_BIG_NUMBER_STRINGS ? { supportBigNumbers: true, bigNumberStrings: true } : {}),
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
export function describeConfiguredTarget() {
|
|
196
|
+
return MYSQL_SOCKET_PATH ? `socket: ${MYSQL_SOCKET_PATH}` : `${MYSQL_HOST || DEFAULT_MYSQL_HOST}:${MYSQL_PORT}`;
|
|
197
|
+
}
|
|
198
|
+
export { readCACertificate, readSSLFile };
|