@ecubelabs/mysql-mcp 1.0.0-next.6 → 1.0.0-next.7

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.
@@ -39,15 +39,19 @@ function allTables(catalog) {
39
39
  })));
40
40
  }
41
41
  export const HOT_TABLES_HEADING = '\n\n카탈로그가 많이 읽은 테이블(읽은 순): ';
42
- export function renderToolDescriptionSuffix(catalog, budget) {
42
+ export function renderToolDescriptionSuffix(catalogs, budget) {
43
43
  const staticGuidance = '\n\n테이블의 도메인 규칙·상태 코드 문서가 있을 수 있다. ' +
44
44
  'SQL을 쓰기 전에 mysql_catalog describe로 확인하라.';
45
45
  if (staticGuidance.length > budget) {
46
46
  return '';
47
47
  }
48
- const hot = rankTables(allTables(catalog).filter(({ entry }) => entry.usage.successCount > 0))
48
+ const entries = Array.isArray(catalogs) ? catalogs : [{ connection: null, catalog: catalogs }];
49
+ const labelled = entries.length > 1;
50
+ const hot = rankTables(entries.flatMap(({ connection, catalog }) => allTables(catalog)
51
+ .filter(({ entry }) => entry.usage.successCount > 0)
52
+ .map((ranked) => ({ ...ranked, connection }))))
49
53
  .slice(0, HOT_TABLE_LIMIT)
50
- .map(({ schema, table }) => `${schema}.${table}`);
54
+ .map(({ schema, table, connection }) => labelled ? `${schema}.${table} (${connection})` : `${schema}.${table}`);
51
55
  if (hot.length === 0) {
52
56
  return staticGuidance;
53
57
  }
@@ -71,6 +75,7 @@ export function renderMap(catalog) {
71
75
  const schemas = Object.entries(catalog.schemas).map(([name, schema]) => ({
72
76
  schema: name,
73
77
  ...ownerField(schemaOwnerOf(schema)),
78
+ ...(schema.notes && schema.notes.length > 0 ? { notes: schema.notes } : {}),
74
79
  scannedAt: schema.scannedAt,
75
80
  tableCount: Object.keys(schema.tables).length,
76
81
  tables: rankTables(Object.entries(schema.tables).map(([table, entry]) => ({
@@ -171,7 +176,7 @@ function shellQuote(value) {
171
176
  }
172
177
  return `'${value.replace(/'/g, `'"'"'`)}'`;
173
178
  }
174
- export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile, owner = null) {
179
+ export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile, owner = null, schemaNotes = []) {
175
180
  let docs;
176
181
  const hasDocumentDecision = Object.prototype.hasOwnProperty.call(table.curated, 'doc');
177
182
  const documentLink = table.curated.doc;
@@ -208,6 +213,7 @@ export function renderDescribe(qualifiedName, table, codeBranches, observedJoins
208
213
  return JSON.stringify({
209
214
  table: qualifiedName,
210
215
  ...ownerField(owner),
216
+ ...(schemaNotes.length > 0 ? { schemaNotes } : {}),
211
217
  ...table,
212
218
  ...(observedJoins.length > 0 ? { observedJoins } : {}),
213
219
  docs,
@@ -1,123 +1,10 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { loadedCodeBranches } from './branch.js';
4
- import { normalizeDocumentPath, normalizeGithubRepo } from './docs.js';
5
- import { loadedSchemaOwner, schemaOwnerOf } from './owner.js';
3
+ import { ContextStore } from './context.js';
4
+ import { acquireCatalogLock, CatalogLockTimeoutError, LOCK_CLOSE_WAIT_MS, LOCK_WAIT_MS } from './lock.js';
6
5
  import { CATALOG_VERSION, emptyCatalog, emptyTable, normalizeName, pruneJoins } from './types.js';
7
6
  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;
12
7
  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
- }
121
8
  const EPOCH = new Date(0).toISOString();
122
9
  function timestamp(value) {
123
10
  if (!value) {
@@ -126,30 +13,6 @@ function timestamp(value) {
126
13
  const parsed = Date.parse(value);
127
14
  return Number.isFinite(parsed) ? parsed : 0;
128
15
  }
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
- }
153
16
  function mergedCounter(external, local, base) {
154
17
  if (local < base) {
155
18
  return local + Math.max(0, external - base);
@@ -198,14 +61,9 @@ function mergeTable(external, local, base) {
198
61
  lastUsedAt: newerUsageTimestamp(external.usage?.lastUsedAt, local.usage?.lastUsedAt, externalUsageCount, localUsageCount, baseUsageCount),
199
62
  columns: Object.fromEntries(columns),
200
63
  },
201
- curated: mergeCurated(external.curated ?? { notes: [], aliases: [] }, local.curated ?? { notes: [], aliases: [] }, base?.curated),
64
+ curated: emptyCurated(),
202
65
  };
203
66
  }
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
- }
209
67
  function mergeSchema(external, local, base) {
210
68
  const newerInventory = timestamp(local.scannedAt) >= timestamp(external.scannedAt) ? local : external;
211
69
  const olderInventory = newerInventory === local ? external : local;
@@ -215,17 +73,7 @@ function mergeSchema(external, local, base) {
215
73
  ? mergeTable(newerInventory === local ? olderInventory.tables[name] : table, newerInventory === local ? table : olderInventory.tables[name], base?.tables[name])
216
74
  : table;
217
75
  }
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;
76
+ return { scannedAt: newerInventory.scannedAt, tables };
229
77
  }
230
78
  function mergeCatalog(external, local, base) {
231
79
  const schemas = {};
@@ -262,32 +110,39 @@ function mergeCatalog(external, local, base) {
262
110
  }
263
111
  return {
264
112
  ...local,
265
- codeBranches: mergeCodeBranches(external.codeBranches, local.codeBranches, base.codeBranches),
113
+ codeBranches: {},
266
114
  schemas,
267
115
  joins: pruneJoins([...joins.values()]),
268
116
  };
269
117
  }
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,
118
+ function emptyCurated() {
119
+ return { notes: [], aliases: [] };
120
+ }
121
+ function persistable(data) {
122
+ const { codeBranches: _branches, schemas, ...rest } = data;
123
+ return {
124
+ ...rest,
125
+ schemas: Object.fromEntries(Object.entries(schemas).map(([name, { repo: _repo, app: _app, notes: _notes, tables, ...schema }]) => [
126
+ name,
127
+ {
128
+ ...schema,
129
+ tables: Object.fromEntries(Object.entries(tables).map(([table, { curated: _curated, ...entry }]) => [table, entry])),
285
130
  },
286
- };
287
- }
288
- catch {
289
- return {};
131
+ ])),
132
+ };
133
+ }
134
+ function curatedFrom(context, schema, table) {
135
+ const recorded = context.schemas[schema]?.tables[table];
136
+ if (!recorded) {
137
+ return emptyCurated();
290
138
  }
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
+ };
291
146
  }
292
147
  export class CatalogStore {
293
148
  options;
@@ -300,8 +155,10 @@ export class CatalogStore {
300
155
  flushedRevision = 0;
301
156
  closing = false;
302
157
  nameIndex = null;
303
- constructor(options) {
158
+ context;
159
+ constructor(options, context) {
304
160
  this.options = options;
161
+ this.context = context ?? { store: new ContextStore(null), env: options.profile, instance: 'default' };
305
162
  this.enabled = options.enabled;
306
163
  this.data = emptyCatalog(options);
307
164
  this.baseData = structuredClone(this.data);
@@ -348,14 +205,12 @@ export class CatalogStore {
348
205
  }
349
206
  sanitizeLoaded(loaded) {
350
207
  const fresh = emptyCatalog(this.options);
351
- fresh.codeBranches = loadedCodeBranches(loaded.codeBranches);
352
208
  const loadedSchemas = loaded.schemas && typeof loaded.schemas === 'object' ? loaded.schemas : {};
353
209
  for (const [schemaName, cached] of Object.entries(loadedSchemas)) {
354
210
  if (!cached || typeof cached !== 'object') {
355
211
  continue;
356
212
  }
357
213
  const schema = {
358
- ...loadedSchemaOwner(cached),
359
214
  scannedAt: cached.scannedAt ?? null,
360
215
  tables: {},
361
216
  };
@@ -376,11 +231,7 @@ export class CatalogStore {
376
231
  lastUsedAt: raw.usage?.lastUsedAt ?? null,
377
232
  columns: raw.usage?.columns ?? {},
378
233
  },
379
- curated: {
380
- notes: raw.curated?.notes ?? [],
381
- aliases: raw.curated?.aliases ?? [],
382
- ...loadedDocumentDecision(raw.curated),
383
- },
234
+ curated: emptyCurated(),
384
235
  };
385
236
  schema.tables[tableName] = table;
386
237
  }
@@ -419,10 +270,35 @@ export class CatalogStore {
419
270
  return index;
420
271
  }
421
272
  snapshot() {
422
- return structuredClone(this.data);
273
+ const snapshot = structuredClone(this.data);
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);
423
296
  }
424
297
  codeBranches() {
425
- return this.data.codeBranches;
298
+ return this.readContext().codeBranches;
299
+ }
300
+ schemaNotes(schema) {
301
+ return [...(this.readContext().schemas[schema]?.notes ?? [])];
426
302
  }
427
303
  lookup(schemaHint, table) {
428
304
  const index = this.ensureNameIndex();
@@ -440,6 +316,9 @@ export class CatalogStore {
440
316
  }
441
317
  return matches;
442
318
  }
319
+ schemaNames() {
320
+ return Object.keys(this.data.schemas);
321
+ }
443
322
  schemaScanTimes() {
444
323
  return Object.values(this.data.schemas).map((schema) => schema.scannedAt);
445
324
  }
@@ -448,10 +327,9 @@ export class CatalogStore {
448
327
  }
449
328
  schemaOwners() {
450
329
  const owners = {};
451
- for (const [name, schema] of Object.entries(this.data.schemas)) {
452
- const owner = schemaOwnerOf(schema);
453
- if (owner) {
454
- owners[name] = owner;
330
+ for (const [name, schema] of Object.entries(this.readContext().schemas)) {
331
+ if (schema.owner) {
332
+ owners[name] = { ...schema.owner };
455
333
  }
456
334
  }
457
335
  return owners;
@@ -464,7 +342,7 @@ export class CatalogStore {
464
342
  return {
465
343
  detailScannedAt: entry.detailScannedAt,
466
344
  detailStale: entry.detailStale === true,
467
- docReviewed: Object.prototype.hasOwnProperty.call(entry.curated, 'doc'),
345
+ docReviewed: Object.prototype.hasOwnProperty.call(this.readContext().schemas[schema]?.tables[table] ?? {}, 'doc'),
468
346
  };
469
347
  }
470
348
  tableIndexes(schema, table) {
@@ -487,7 +365,12 @@ export class CatalogStore {
487
365
  }
488
366
  readTable(schema, table) {
489
367
  const entry = this.data.schemas[schema]?.tables[table];
490
- return entry ? structuredClone(entry) : null;
368
+ if (!entry) {
369
+ return null;
370
+ }
371
+ const copy = structuredClone(entry);
372
+ copy.curated = curatedFrom(this.readContext(), schema, table);
373
+ return copy;
491
374
  }
492
375
  hasSuccessfulUse() {
493
376
  for (const schema of Object.values(this.data.schemas)) {
@@ -558,7 +441,7 @@ export class CatalogStore {
558
441
  this.data = toWrite;
559
442
  this.invalidateNameIndex();
560
443
  }
561
- const payload = `${JSON.stringify(toWrite, null, 2)}\n`;
444
+ const payload = `${JSON.stringify(persistable(toWrite), null, 2)}\n`;
562
445
  const persisted = structuredClone(toWrite);
563
446
  await fs.promises.writeFile(tempPath, payload, {
564
447
  encoding: 'utf8',
@@ -42,3 +42,15 @@ 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
+ }
@@ -0,0 +1,30 @@
1
+ export class UsageError extends Error {
2
+ constructor(message) {
3
+ super(message);
4
+ this.name = 'UsageError';
5
+ }
6
+ }
7
+ export const SERVER_USAGE = 'usage: mysql-mcp --env <name> [--config <path>]\n mysql-mcp init [--config <path>]';
8
+ export function parseFlags(argv, allowed) {
9
+ const flags = {};
10
+ for (let i = 0; i < argv.length; i++) {
11
+ const arg = argv[i];
12
+ const match = /^--([a-z-]+)(?:=(.*))?$/.exec(arg);
13
+ if (!match || !allowed.includes(match[1])) {
14
+ throw new UsageError(`unknown argument "${arg}"\n${SERVER_USAGE}`);
15
+ }
16
+ const value = match[2] ?? argv[++i];
17
+ if (value === undefined || value.trim() === '' || (match[2] === undefined && value.startsWith('--'))) {
18
+ throw new UsageError(`--${match[1]} needs a value\n${SERVER_USAGE}`);
19
+ }
20
+ flags[match[1]] = value.trim();
21
+ }
22
+ return flags;
23
+ }
24
+ export function parseServerArgs(argv) {
25
+ const flags = parseFlags(argv, ['env', 'config']);
26
+ if (!flags.env) {
27
+ throw new UsageError(`--env is required\n${SERVER_USAGE}`);
28
+ }
29
+ return { envName: flags.env, ...(flags.config ? { configPath: flags.config } : {}) };
30
+ }
@@ -1,43 +1,6 @@
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
- }
41
4
  const PACKAGE_NAME = '@ecubelabs/mysql-mcp';
42
5
  export function readPackageVersion(startDir) {
43
6
  let dir = startDir;
@@ -57,142 +20,4 @@ export function readPackageVersion(startDir) {
57
20
  dir = parent;
58
21
  }
59
22
  }
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';
79
23
  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 };