@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.
@@ -1,3 +1,4 @@
1
+ import { executeQuery } from '../db/index.js';
1
2
  import { emptyTable, normalizeName, SYSTEM_SCHEMAS } from './types.js';
2
3
  function chainAfter(pending, run) {
3
4
  if (!pending) {
@@ -49,7 +50,7 @@ export class CatalogCollector {
49
50
  }
50
51
  async runInventory() {
51
52
  const placeholders = SYSTEM_SCHEMAS.map(() => '?').join(', ');
52
- const rows = await this.options.query(`SELECT
53
+ const rows = await executeQuery(`SELECT
53
54
  s.schema_name AS \`table_schema\`,
54
55
  t.table_name AS \`table_name\`,
55
56
  t.table_comment AS \`table_comment\`,
@@ -122,7 +123,7 @@ export class CatalogCollector {
122
123
  return promise;
123
124
  }
124
125
  async runTableDetail(schemaName, tableName) {
125
- const rows = await this.options.query(`SELECT
126
+ const rows = await executeQuery(`SELECT
126
127
  'column' AS kind,
127
128
  c.column_name AS name,
128
129
  c.data_type AS \`data_type\`,
@@ -1,5 +1,4 @@
1
1
  import * as path from 'path';
2
- import { tableContext } from './types.js';
3
2
  const GITHUB_REPO_FORMS = [
4
3
  /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i,
5
4
  /^git@github\.com:([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i,
@@ -43,7 +42,7 @@ export class CatalogDocuments {
43
42
  constructor(store) {
44
43
  this.store = store;
45
44
  }
46
- async link(links, guidanceFor = () => []) {
45
+ link(links, guidanceFor = () => []) {
47
46
  const resolved = links.map((link) => ({
48
47
  ...link,
49
48
  doc: normalizeDocumentPath(link.doc),
@@ -56,14 +55,17 @@ export class CatalogDocuments {
56
55
  }
57
56
  }
58
57
  const now = new Date().toISOString();
59
- await this.store.updateContext((context) => {
58
+ this.store.update((catalog) => {
60
59
  for (const link of resolved) {
61
- tableContext(context, link.schema, link.table).doc = {
62
- path: link.doc,
63
- repo: link.repo,
64
- linkedBy: 'model',
65
- linkedAt: now,
66
- };
60
+ const table = catalog.schemas[link.schema]?.tables[link.table];
61
+ if (table) {
62
+ table.curated.doc = {
63
+ path: link.doc,
64
+ repo: link.repo,
65
+ linkedBy: 'model',
66
+ linkedAt: now,
67
+ };
68
+ }
67
69
  }
68
70
  });
69
71
  const guidance = guidanceFor(resolved);
@@ -76,13 +78,13 @@ export class CatalogDocuments {
76
78
  ...(guidance.length > 0 ? { guidance } : {}),
77
79
  }, null, 2);
78
80
  }
79
- async unlink(schemaName, tableName) {
81
+ unlink(schemaName, tableName) {
80
82
  const snapshot = this.store.snapshot();
81
83
  if (!snapshot.schemas[schemaName]?.tables[tableName]) {
82
84
  throw new Error(`Unknown table "${schemaName}.${tableName}".`);
83
85
  }
84
- await this.store.updateContext((context) => {
85
- tableContext(context, schemaName, tableName).doc = null;
86
+ this.store.update((catalog) => {
87
+ catalog.schemas[schemaName].tables[tableName].curated.doc = null;
86
88
  });
87
89
  return JSON.stringify({
88
90
  table: `${schemaName}.${tableName}`,
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'crypto';
2
+ import * as os from 'os';
2
3
  import * as path from 'path';
3
4
  import { CatalogCollector } from './collect.js';
4
5
  import { CatalogDocuments, normalizeGithubRepo } from './docs.js';
@@ -6,7 +7,7 @@ import { formatCodeBranches, normalizeBranchName } from './branch.js';
6
7
  import { normalizeSchemaOwner } from './owner.js';
7
8
  import { missingBranchNotice, missingOwnerNotice, renderDescribe, renderMap, renderToolDescriptionSuffix, searchCatalog, } from './render.js';
8
9
  import { CatalogStore } from './store.js';
9
- import { emptyUsage, normalizeName, pruneJoins, schemaContext, SYSTEM_SCHEMAS, tableContext } from './types.js';
10
+ import { emptyUsage, normalizeName, pruneJoins, SYSTEM_SCHEMAS } from './types.js';
10
11
  import { prepareCatalogQuery, resultColumnNames } from './usage.js';
11
12
  const UNKNOWN_REFERENCE_REFRESH_COOLDOWN_MS = 60_000;
12
13
  const UNKNOWN_REFERENCE_MEMORY_LIMIT = 256;
@@ -29,14 +30,12 @@ export function catalogIdentity(identity) {
29
30
  const profile = identity.profile || 'default';
30
31
  const safeProfile = profile.replace(/[^A-Za-z0-9_.-]/g, '_');
31
32
  const endpointHash = shortHash(`${identity.target}\u0000${identity.user}`);
33
+ const directory = identity.customPath ?? path.join(os.homedir(), '.cache', 'mysql-mcp', 'catalog');
32
34
  return {
33
- filePath: path.join(identity.directory, `${safeProfile}-${endpointHash}.json`),
35
+ filePath: path.join(directory, `${safeProfile}-${endpointHash}.json`),
34
36
  fingerprint: endpointHash,
35
37
  };
36
38
  }
37
- function isSchemaTarget(input) {
38
- return !input.replace(/`/g, '').includes('.');
39
- }
40
39
  function sameName(a, b) {
41
40
  return normalizeName(a) === normalizeName(b);
42
41
  }
@@ -56,10 +55,9 @@ export class SchemaCatalog {
56
55
  toolDescriptionAnnounced = false;
57
56
  constructor(options) {
58
57
  this.options = options;
59
- this.store = new CatalogStore(options, options.context);
58
+ this.store = new CatalogStore(options);
60
59
  this.collector = new CatalogCollector(this.store, {
61
60
  ttlHours: options.ttlHours,
62
- query: options.query,
63
61
  });
64
62
  this.documents = new CatalogDocuments(this.store);
65
63
  }
@@ -72,7 +70,7 @@ export class SchemaCatalog {
72
70
  codeBranchSummary() {
73
71
  return this.isEnabled() ? formatCodeBranches(this.store.codeBranches()) || null : null;
74
72
  }
75
- async setCodeBranch(repoInput, branchInput) {
73
+ setCodeBranch(repoInput, branchInput) {
76
74
  if (!this.isEnabled()) {
77
75
  throw new Error('The schema catalog is disabled.');
78
76
  }
@@ -82,9 +80,12 @@ export class SchemaCatalog {
82
80
  if (previous === branch) {
83
81
  return JSON.stringify({ repo, branch, changed: false, status: `${repo}에는 이미 ${branch} 브랜치가 기록돼 있습니다.` }, null, 2);
84
82
  }
85
- await this.store.updateContext((context) => {
86
- context.codeBranches[repo] = branch;
83
+ this.store.update((catalog) => {
84
+ catalog.codeBranches[repo] = branch;
87
85
  });
86
+ if (this.store.codeBranches()[repo] !== branch) {
87
+ throw new Error('The catalog cache is disabled, so the branch was not recorded.');
88
+ }
88
89
  return JSON.stringify({
89
90
  repo,
90
91
  branch,
@@ -93,7 +94,7 @@ export class SchemaCatalog {
93
94
  status: previous
94
95
  ? `${repo}의 브랜치를 바꿨습니다: ${previous} → ${branch}`
95
96
  : `${repo}에 ${branch} 브랜치를 기록했습니다. 다음 세션에도 이어 씁니다.`,
96
- note: 'banner와 describe는 바로 이 값을 씁니다. mysql_query 툴 설명의 CODE REVISION은 다음 도구 목록 요청부터 바뀝니다.',
97
+ note: 'banner와 describe는 바로 이 값을 씁니다. mysql_query 툴 설명의 CODE REVISION은 서버를 다시 띄우면 바뀝니다.',
97
98
  }, null, 2);
98
99
  }
99
100
  schemaOwners() {
@@ -119,9 +120,22 @@ export class SchemaCatalog {
119
120
  if (previous && previous.repo === owner.repo && previous.app === owner.app) {
120
121
  return JSON.stringify({ schema: name, ...owner, changed: false, status: `${name} schema의 owner는 이미 ${label}입니다.` }, null, 2);
121
122
  }
122
- await this.store.updateContext((context) => {
123
- schemaContext(context, name).owner = owner;
123
+ let missing = false;
124
+ this.store.update((catalog) => {
125
+ const entry = catalog.schemas[name];
126
+ if (!entry) {
127
+ missing = true;
128
+ return;
129
+ }
130
+ entry.repo = owner.repo;
131
+ entry.app = owner.app;
124
132
  });
133
+ if (missing) {
134
+ throw new Error(`${name} is no longer in the catalog. Run mysql_catalog {action:"map"} to see what remains.`);
135
+ }
136
+ if (!this.isEnabled()) {
137
+ throw new Error('The catalog cache is disabled, so the owner was not recorded.');
138
+ }
125
139
  return JSON.stringify({
126
140
  schema: name,
127
141
  ...owner,
@@ -134,17 +148,11 @@ export class SchemaCatalog {
134
148
  }
135
149
  startInventory() {
136
150
  if (!this.isEnabled() || this.closing) {
137
- return Promise.resolve();
151
+ return;
138
152
  }
139
- const task = this.collector.collectInventory(false).catch((error) => {
140
- const where = this.options.connection ? ` for connection ${this.options.connection}` : '';
141
- console.error(`[catalog] inventory scan failed${where}: ${error instanceof Error ? error.message : String(error)}`);
142
- });
143
- this.trackBackgroundTask(task);
144
- return task;
145
- }
146
- schemaNames() {
147
- return this.isEnabled() ? this.store.schemaNames() : [];
153
+ this.trackBackgroundTask(this.collector.collectInventory(false).catch((error) => {
154
+ console.error(`[catalog] inventory scan failed: ${error instanceof Error ? error.message : String(error)}`);
155
+ }));
148
156
  }
149
157
  toolDescriptionSuffix(budget) {
150
158
  if (!this.isEnabled()) {
@@ -152,9 +160,6 @@ export class SchemaCatalog {
152
160
  }
153
161
  return renderToolDescriptionSuffix(this.store.snapshot(), budget);
154
162
  }
155
- descriptionSnapshot() {
156
- return this.isEnabled() ? this.store.snapshot() : null;
157
- }
158
163
  onToolDescriptionFilled(listener) {
159
164
  this.toolDescriptionListener = listener;
160
165
  }
@@ -241,7 +246,7 @@ export class SchemaCatalog {
241
246
  if (!entry) {
242
247
  throw new Error(`Table disappeared during refresh: ${input}`);
243
248
  }
244
- return renderDescribe(`${resolved.schema}.${resolved.table}`, entry, this.store.codeBranches(), this.store.readJoins(resolved.schema, resolved.table), this.options.profile, this.store.schemaOwners()[resolved.schema] ?? null, this.store.schemaNotes(resolved.schema));
249
+ return renderDescribe(`${resolved.schema}.${resolved.table}`, entry, this.store.codeBranches(), this.store.readJoins(resolved.schema, resolved.table), this.options.profile, this.store.schemaOwners()[resolved.schema] ?? null);
245
250
  }
246
251
  async refresh(target) {
247
252
  if (!this.isEnabled()) {
@@ -352,42 +357,46 @@ export class SchemaCatalog {
352
357
  if (hasText === hasAlias) {
353
358
  throw new Error('mysql_catalog note requires exactly one of "text" or "alias".');
354
359
  }
360
+ const resolved = await this.ensureKnownTable(input);
355
361
  const kind = hasText ? 'note' : 'alias';
356
362
  const content = (hasText ? value.text : value.alias)?.trim();
357
363
  const limit = hasText ? NOTE_MAX_LENGTH : ALIAS_MAX_LENGTH;
358
364
  if (content.length > limit) {
359
365
  throw new Error(`${kind} exceeds the ${limit}-character limit.`);
360
366
  }
361
- if (isSchemaTarget(input)) {
362
- if (!hasText) {
363
- throw new Error('An alias names a table. Pass target as schema.table, or use text for a schema note.');
364
- }
365
- return this.noteSchema(await this.ensureKnownSchema(input), content);
366
- }
367
- const resolved = await this.ensureKnownTable(input);
368
367
  const qualified = `${resolved.schema}.${resolved.table}`;
369
- const full = await this.store.updateContext((context) => {
370
- const curated = tableContext(context, resolved.schema, resolved.table);
368
+ let full = false;
369
+ let missing = false;
370
+ this.store.update((catalog) => {
371
+ const curated = catalog.schemas[resolved.schema]?.tables[resolved.table]?.curated;
372
+ if (!curated) {
373
+ missing = true;
374
+ return;
375
+ }
371
376
  if (hasText) {
372
377
  if (curated.notes.includes(content)) {
373
- return false;
378
+ return;
374
379
  }
375
380
  if (curated.notes.length >= NOTE_COUNT_LIMIT) {
376
- return true;
381
+ full = true;
382
+ return;
377
383
  }
378
384
  curated.notes.push(content);
379
385
  }
380
386
  else {
381
387
  if (curated.aliases.some((alias) => normalizeName(alias) === normalizeName(content))) {
382
- return false;
388
+ return;
383
389
  }
384
390
  if (curated.aliases.length >= ALIAS_COUNT_LIMIT) {
385
- return true;
391
+ full = true;
392
+ return;
386
393
  }
387
394
  curated.aliases.push(content);
388
395
  }
389
- return false;
390
396
  });
397
+ if (missing) {
398
+ throw new Error(tableVanished(qualified));
399
+ }
391
400
  if (full) {
392
401
  throw new Error(`${qualified} already holds the maximum of ${hasText ? NOTE_COUNT_LIMIT : ALIAS_COUNT_LIMIT} ${kind}s. Clear them with mysql_catalog {action:"forget", target:"${qualified}", scope:"${kind}s"} first.`);
393
402
  }
@@ -399,68 +408,11 @@ export class SchemaCatalog {
399
408
  aliases: table?.curated.aliases ?? [],
400
409
  }, null, 2);
401
410
  }
402
- async noteSchema(schema, content) {
403
- const full = await this.store.updateContext((context) => {
404
- const notes = schemaContext(context, schema).notes;
405
- if (notes.includes(content)) {
406
- return false;
407
- }
408
- if (notes.length >= NOTE_COUNT_LIMIT) {
409
- return true;
410
- }
411
- notes.push(content);
412
- return false;
413
- });
414
- if (full) {
415
- throw new Error(`${schema} already holds the maximum of ${NOTE_COUNT_LIMIT} notes. ` +
416
- `Clear them with mysql_catalog {action:"forget", target:"${schema}", scope:"notes"} first.`);
417
- }
418
- return JSON.stringify({ target: schema, added: { note: content }, notes: this.store.schemaNotes(schema) }, null, 2);
419
- }
420
- async ensureKnownSchema(input) {
421
- const requested = input.replace(/`/g, '').trim();
422
- let schema = this.store.schemaName(requested);
423
- if (!schema) {
424
- await this.collector.collectInventory(false);
425
- schema = this.store.schemaName(requested);
426
- }
427
- if (!schema) {
428
- throw new Error(`Unknown schema "${requested}". Run mysql_catalog {action:"map"} to see the schemas.`);
429
- }
430
- return schema;
431
- }
432
411
  async forget(input, scope) {
433
412
  if (!this.isEnabled()) {
434
413
  throw new Error('The schema catalog is disabled.');
435
414
  }
436
- if (isSchemaTarget(input)) {
437
- if (scope !== 'notes') {
438
- throw new Error(`A schema holds only notes. Pass target as schema.table to forget ${scope}.`);
439
- }
440
- const schema = await this.ensureKnownSchema(input);
441
- const removed = await this.store.updateContext((context) => {
442
- const notes = context.schemas[schema]?.notes ?? [];
443
- const count = notes.length;
444
- if (context.schemas[schema]) {
445
- context.schemas[schema].notes = [];
446
- }
447
- return count;
448
- });
449
- return JSON.stringify({ target: schema, scope, removed }, null, 2);
450
- }
451
415
  const resolved = await this.ensureKnownTable(input);
452
- if (scope === 'notes' || scope === 'aliases') {
453
- const qualified = `${resolved.schema}.${resolved.table}`;
454
- const removed = await this.store.updateContext((context) => {
455
- const curated = context.schemas[resolved.schema]?.tables[resolved.table];
456
- const count = curated?.[scope].length ?? 0;
457
- if (curated) {
458
- curated[scope] = [];
459
- }
460
- return count;
461
- });
462
- return JSON.stringify({ target: qualified, scope, removed }, null, 2);
463
- }
464
416
  const qualified = `${resolved.schema}.${resolved.table}`;
465
417
  let removed = 0;
466
418
  let missing = false;
@@ -470,7 +422,15 @@ export class SchemaCatalog {
470
422
  missing = true;
471
423
  return;
472
424
  }
473
- if (scope === 'usage') {
425
+ if (scope === 'notes') {
426
+ removed = table.curated.notes.length;
427
+ table.curated.notes = [];
428
+ }
429
+ else if (scope === 'aliases') {
430
+ removed = table.curated.aliases.length;
431
+ table.curated.aliases = [];
432
+ }
433
+ else if (scope === 'usage') {
474
434
  removed = table.usage.count;
475
435
  table.usage = emptyUsage();
476
436
  }
@@ -39,19 +39,15 @@ function allTables(catalog) {
39
39
  })));
40
40
  }
41
41
  export const HOT_TABLES_HEADING = '\n\n카탈로그가 많이 읽은 테이블(읽은 순): ';
42
- export function renderToolDescriptionSuffix(catalogs, budget) {
42
+ export function renderToolDescriptionSuffix(catalog, 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 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 }))))
48
+ const hot = rankTables(allTables(catalog).filter(({ entry }) => entry.usage.successCount > 0))
53
49
  .slice(0, HOT_TABLE_LIMIT)
54
- .map(({ schema, table, connection }) => labelled ? `${schema}.${table} (${connection})` : `${schema}.${table}`);
50
+ .map(({ schema, table }) => `${schema}.${table}`);
55
51
  if (hot.length === 0) {
56
52
  return staticGuidance;
57
53
  }
@@ -75,7 +71,6 @@ export function renderMap(catalog) {
75
71
  const schemas = Object.entries(catalog.schemas).map(([name, schema]) => ({
76
72
  schema: name,
77
73
  ...ownerField(schemaOwnerOf(schema)),
78
- ...(schema.notes && schema.notes.length > 0 ? { notes: schema.notes } : {}),
79
74
  scannedAt: schema.scannedAt,
80
75
  tableCount: Object.keys(schema.tables).length,
81
76
  tables: rankTables(Object.entries(schema.tables).map(([table, entry]) => ({
@@ -176,7 +171,7 @@ function shellQuote(value) {
176
171
  }
177
172
  return `'${value.replace(/'/g, `'"'"'`)}'`;
178
173
  }
179
- export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile, owner = null, schemaNotes = []) {
174
+ export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile, owner = null) {
180
175
  let docs;
181
176
  const hasDocumentDecision = Object.prototype.hasOwnProperty.call(table.curated, 'doc');
182
177
  const documentLink = table.curated.doc;
@@ -213,7 +208,6 @@ export function renderDescribe(qualifiedName, table, codeBranches, observedJoins
213
208
  return JSON.stringify({
214
209
  table: qualifiedName,
215
210
  ...ownerField(owner),
216
- ...(schemaNotes.length > 0 ? { schemaNotes } : {}),
217
211
  ...table,
218
212
  ...(observedJoins.length > 0 ? { observedJoins } : {}),
219
213
  docs,