@ecubelabs/mysql-mcp 1.0.0-next.1 → 1.0.0-next.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.
@@ -1,3 +1,4 @@
1
+ import { suggestedBranch } from './branch.js';
1
2
  const UNLINKED_SAMPLE_LIMIT = 30;
2
3
  const HOT_TABLE_LIMIT = 10;
3
4
  function sampled(values) {
@@ -63,7 +64,7 @@ export function renderToolDescriptionSuffix(catalog, budget) {
63
64
  }
64
65
  return HOT_TABLES_HEADING + listed + staticGuidance;
65
66
  }
66
- export function renderMap(catalog, warning = null) {
67
+ export function renderMap(catalog) {
67
68
  const schemas = Object.entries(catalog.schemas).map(([name, schema]) => ({
68
69
  app: schema.app,
69
70
  schema: name,
@@ -85,17 +86,13 @@ export function renderMap(catalog, warning = null) {
85
86
  lastUsedAt: entry.usage.lastUsedAt,
86
87
  })),
87
88
  }));
88
- const unlinkedTables = catalog.docs.repo
89
- ? Object.entries(catalog.schemas).flatMap(([schemaName, schema]) => Object.entries(schema.tables)
90
- .filter(([, table]) => !Object.prototype.hasOwnProperty.call(table.curated, 'doc'))
91
- .map(([tableName]) => `${schemaName}.${tableName}`))
92
- : [];
89
+ const unlinkedTables = Object.entries(catalog.schemas).flatMap(([schemaName, schema]) => Object.entries(schema.tables)
90
+ .filter(([, table]) => !Object.prototype.hasOwnProperty.call(table.curated, 'doc'))
91
+ .map(([tableName]) => `${schemaName}.${tableName}`));
93
92
  return JSON.stringify({
94
93
  profile: catalog.profile,
95
94
  schemas,
96
95
  unlinkedTables: sampled(unlinkedTables),
97
- unlinkedDocuments: sampled(catalog.docs.unlinked),
98
- ...(warning ? { warning } : {}),
99
96
  }, null, 2);
100
97
  }
101
98
  function matchScore(value, query, base) {
@@ -140,31 +137,50 @@ export function searchCatalog(catalog, query, limit) {
140
137
  }
141
138
  return results.sort((a, b) => b.score - a.score || a.table.localeCompare(b.table)).slice(0, limit);
142
139
  }
143
- export function renderDescribe(qualifiedName, table, documents, observedJoins) {
140
+ export function missingBranchNotice(profile) {
141
+ const suggestion = suggestedBranch(profile);
142
+ const question = suggestion
143
+ ? `${profile} profile은 보통 ${suggestion} 브랜치에 대응합니다. ${suggestion}이 맞는지 사용자에게 물으세요.`
144
+ : `이 profile(${profile})이 어느 브랜치에 대응하는지 사용자에게 물으세요.`;
145
+ return (`[카탈로그] 이 DB에 대응하는 코드 브랜치가 기록되지 않았습니다. ${question}\n` +
146
+ '확인받은 값을 mysql_catalog {action:"branch", branch:"<브랜치 이름>"} 로 기록하세요.');
147
+ }
148
+ function shellQuote(value) {
149
+ if (/^[A-Za-z0-9_./:@+-]+$/.test(value)) {
150
+ return value;
151
+ }
152
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
153
+ }
154
+ export function renderDescribe(qualifiedName, table, codeBranch, observedJoins, profile) {
144
155
  let docs;
145
156
  const hasDocumentDecision = Object.prototype.hasOwnProperty.call(table.curated, 'doc');
146
157
  const documentLink = table.curated.doc;
147
- if (!documents.configured) {
148
- docs = '문서 축 비활성 (MYSQL_DOCS_REPO 미설정)';
149
- }
150
- else if (!documents.available) {
151
- docs = '문서 축 비활성';
152
- }
153
- else if (!hasDocumentDecision) {
158
+ if (!hasDocumentDecision) {
154
159
  docs =
155
160
  '연결 안 됨\n' +
156
- `후보를 보려면 mysql_catalog {action:"docs_list", schema:"${documents.schema}"}\n` +
157
- 'status 같은 코드 컬럼의 의미는 도메인 문서에만 있습니다.';
161
+ `도메인 문서(model.md)를 찾으면 mysql_catalog {action:"link", links:[{table:"${qualifiedName}", doc:"<저장소 기준 상대 경로>", repo:"<owner/name>"}]} 로 연결하세요.\n` +
162
+ 'status 같은 코드 컬럼의 의미는 도메인 문서에만 있습니다.' +
163
+ (codeBranch ? '' : `\n${missingBranchNotice(profile)}`);
158
164
  }
159
165
  else if (documentLink == null) {
160
166
  docs = '문서 없음 확인됨';
161
167
  }
162
168
  else {
169
+ const { repo } = documentLink;
163
170
  docs = {
164
171
  path: documentLink.path,
165
- ref: documents.ref,
166
- command: documents.command,
167
- guidance: '상태 코드·도메인 규칙은 이 문서를 먼저 읽어라.',
172
+ repo,
173
+ branch: codeBranch,
174
+ command: codeBranch ? `git show ${shellQuote(`origin/${codeBranch}:${documentLink.path}`)}` : null,
175
+ remoteCommand: codeBranch
176
+ ? `gh api -H 'Accept: application/vnd.github.raw' ${shellQuote(`repos/${repo}/contents/${documentLink.path
177
+ .split('/')
178
+ .map(encodeURIComponent)
179
+ .join('/')}?ref=${encodeURIComponent(codeBranch)}`)}`
180
+ : null,
181
+ guidance: '상태 코드·도메인 규칙은 이 문서를 먼저 읽어라. ' +
182
+ 'command는 문서가 있는 저장소 안에서, remoteCommand는 어디서든(gh 인증 필요) 실행한다.' +
183
+ (codeBranch ? '' : `\n${missingBranchNotice(profile)}`),
168
184
  };
169
185
  }
170
186
  return JSON.stringify({
@@ -172,6 +188,5 @@ export function renderDescribe(qualifiedName, table, documents, observedJoins) {
172
188
  ...table,
173
189
  ...(observedJoins.length > 0 ? { observedJoins } : {}),
174
190
  docs,
175
- ...(documents.warning ? { warning: documents.warning } : {}),
176
191
  }, null, 2);
177
192
  }
@@ -1,5 +1,7 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
+ import { loadedBranch } from './branch.js';
4
+ import { normalizeDocumentPath, normalizeGithubRepo } from './docs.js';
3
5
  import { CATALOG_VERSION, emptyCatalog, emptyTable, normalizeName, pruneJoins } from './types.js';
4
6
  const FLUSH_DELAY_MS = 2_000;
5
7
  const LOCK_RETRY_MS = 25;
@@ -242,40 +244,34 @@ function mergeCatalog(external, local, base) {
242
244
  lastUsedAt: newerUsageTimestamp(outside?.lastUsedAt, inside?.lastUsedAt, outside?.count ?? 0, inside?.count ?? 0, ancestor?.count ?? 0) ?? EPOCH,
243
245
  });
244
246
  }
245
- const localDocsChanged = local.docs.refCommit !== base.docs.refCommit;
246
- const externalDocsChanged = external.docs.refCommit !== base.docs.refCommit;
247
- const chosenDocs = localDocsChanged && externalDocsChanged
248
- ? timestamp(local.docs.refUpdatedAt) >= timestamp(external.docs.refUpdatedAt)
249
- ? local.docs
250
- : external.docs
251
- : localDocsChanged
252
- ? local.docs
253
- : external.docs;
254
- const merged = {
247
+ return {
255
248
  ...local,
256
- docs: {
257
- ...chosenDocs,
258
- repo: local.docs.repo,
259
- ref: local.docs.ref,
260
- paths: chosenDocs.paths ?? [],
261
- unlinked: [],
262
- },
249
+ codeBranch: local.codeBranch !== base.codeBranch ? local.codeBranch : external.codeBranch,
263
250
  schemas,
264
251
  joins: pruneJoins([...joins.values()]),
265
252
  };
266
- const linked = new Set();
267
- for (const schema of Object.values(merged.schemas)) {
268
- for (const table of Object.values(schema.tables)) {
269
- if (table.curated.doc && !merged.docs.paths.includes(table.curated.doc.path)) {
270
- delete table.curated.doc;
271
- }
272
- if (table.curated.doc) {
273
- linked.add(table.curated.doc.path);
274
- }
275
- }
253
+ }
254
+ function loadedDocumentDecision(curated) {
255
+ if (!curated || !Object.prototype.hasOwnProperty.call(curated, 'doc')) {
256
+ return {};
257
+ }
258
+ const doc = curated.doc;
259
+ if (!doc) {
260
+ return { doc: null };
261
+ }
262
+ try {
263
+ return {
264
+ doc: {
265
+ path: normalizeDocumentPath(String(doc.path ?? '')),
266
+ repo: normalizeGithubRepo(doc.repo),
267
+ linkedBy: doc.linkedBy ?? 'model',
268
+ linkedAt: doc.linkedAt ?? EPOCH,
269
+ },
270
+ };
271
+ }
272
+ catch {
273
+ return {};
276
274
  }
277
- merged.docs.unlinked = merged.docs.paths.filter((path) => !linked.has(path));
278
- return merged;
279
275
  }
280
276
  export class CatalogStore {
281
277
  options;
@@ -336,7 +332,7 @@ export class CatalogStore {
336
332
  }
337
333
  sanitizeLoaded(loaded) {
338
334
  const fresh = emptyCatalog(this.options);
339
- const docsCompatible = loaded.docs?.repo === this.options.docsRepo && loaded.docs?.ref === this.options.docsRef;
335
+ fresh.codeBranch = loadedBranch(loaded.codeBranch);
340
336
  for (const [schemaName, schema] of Object.entries(fresh.schemas)) {
341
337
  const cached = loaded.schemas?.[schemaName];
342
338
  if (!cached) {
@@ -362,23 +358,12 @@ export class CatalogStore {
362
358
  curated: {
363
359
  notes: raw.curated?.notes ?? [],
364
360
  aliases: raw.curated?.aliases ?? [],
365
- ...(docsCompatible && Object.prototype.hasOwnProperty.call(raw.curated ?? {}, 'doc')
366
- ? { doc: raw.curated.doc }
367
- : {}),
361
+ ...loadedDocumentDecision(raw.curated),
368
362
  },
369
363
  };
370
364
  schema.tables[tableName] = table;
371
365
  }
372
366
  }
373
- if (docsCompatible) {
374
- fresh.docs = {
375
- ...fresh.docs,
376
- refCommit: loaded.docs.refCommit ?? null,
377
- refUpdatedAt: loaded.docs.refUpdatedAt ?? null,
378
- paths: loaded.docs.paths ?? [],
379
- unlinked: loaded.docs.unlinked ?? [],
380
- };
381
- }
382
367
  fresh.joins = pruneJoins((loaded.joins ?? [])
383
368
  .map((edge) => ({ ...edge, lastUsedAt: edge.lastUsedAt ?? EPOCH })));
384
369
  return fresh;
@@ -415,8 +400,8 @@ export class CatalogStore {
415
400
  snapshot() {
416
401
  return structuredClone(this.data);
417
402
  }
418
- docsView() {
419
- return structuredClone(this.data.docs);
403
+ codeBranch() {
404
+ return this.data.codeBranch;
420
405
  }
421
406
  lookup(schemaHint, table) {
422
407
  const index = this.ensureNameIndex();
@@ -45,14 +45,7 @@ export function emptyCatalog(options) {
45
45
  version: CATALOG_VERSION,
46
46
  profile: options.profile,
47
47
  fingerprint: options.fingerprint,
48
- docs: {
49
- repo: options.docsRepo,
50
- ref: options.docsRef,
51
- refCommit: null,
52
- refUpdatedAt: null,
53
- paths: [],
54
- unlinked: [],
55
- },
48
+ codeBranch: null,
56
49
  schemas,
57
50
  joins: [],
58
51
  };
@@ -61,15 +61,6 @@ export const MYSQL_PROFILE = (process.env.MYSQL_PROFILE ?? '').trim().toLowerCas
61
61
  const WRITE_FORBIDDEN_PROFILES = new Set(['prod', 'production']);
62
62
  export const IS_WRITE_FORBIDDEN_PROFILE = WRITE_FORBIDDEN_PROFILES.has(MYSQL_PROFILE);
63
63
  export const PROFILE_LABEL = MYSQL_PROFILE ? MYSQL_PROFILE.toUpperCase() : 'UNSPECIFIED';
64
- const DEFAULT_CODE_BRANCH = {
65
- stage: 'develop',
66
- staging: 'develop',
67
- dev: 'develop',
68
- develop: 'develop',
69
- prod: 'main',
70
- production: 'main',
71
- };
72
- export const CODE_BRANCH = process.env.MYSQL_CODE_BRANCH?.trim() || DEFAULT_CODE_BRANCH[MYSQL_PROFILE] || '';
73
64
  function parseAppSchemas(raw) {
74
65
  if (!raw) {
75
66
  return [];
@@ -120,7 +111,6 @@ function parseCatalogTtl(raw) {
120
111
  return value;
121
112
  }
122
113
  export const MYSQL_CATALOG_TTL_HOURS = parseCatalogTtl(process.env.MYSQL_CATALOG_TTL_HOURS);
123
- export const MYSQL_DOCS_REPO = process.env.MYSQL_DOCS_REPO?.trim() || undefined;
124
114
  export const ENABLE_LOGGING = process.env.ENABLE_LOGGING === 'true' || process.env.ENABLE_LOGGING === '1';
125
115
  export const PACKAGE_VERSION = readPackageVersion(path.dirname(fileURLToPath(import.meta.url))) ?? 'unknown';
126
116
  export const MYSQL_DB = process.env.MYSQL_DB?.trim() || undefined;
@@ -1,6 +1,6 @@
1
1
  import { performance } from 'perf_hooks';
2
2
  import * as mysql2 from 'mysql2/promise';
3
- import { mcpConfig as config, describeConfiguredTarget, SSH_ENABLED, MYSQL_PROFILE, PROFILE_LABEL, CODE_BRANCH, IS_WRITE_FORBIDDEN_PROFILE, MYSQL_DISABLE_READ_ONLY_TRANSACTIONS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MYSQL_CATALOG_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, } from './../config/index.js';
3
+ import { mcpConfig as config, describeConfiguredTarget, SSH_ENABLED, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, MYSQL_DISABLE_READ_ONLY_TRANSACTIONS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MYSQL_CATALOG_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, } from './../config/index.js';
4
4
  import { isDDLAllowedForSchema, isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, } from './permissions.js';
5
5
  import { DDL_STATEMENT_TYPES, extractReferencedSchemas, findFileExport, findLimitOverrideHint, findUnsupportedStatementType, getQueryTypes, hasExecutableComment, isUnparseableIntrospection, extractQualifiers, } from './utils.js';
6
6
  import { isQueryTimeoutError, parseExplainPayload, renderTimeoutDiagnostic } from './diagnose.js';
@@ -111,13 +111,18 @@ function describeConnection() {
111
111
  const target = describeConfiguredTarget();
112
112
  return SSH_ENABLED ? `${target} (via ssh tunnel, not yet established)` : target;
113
113
  }
114
+ let codeBranchSource = null;
115
+ function setCodeBranchSource(source) {
116
+ codeBranchSource = source;
117
+ }
114
118
  function profileBanner() {
115
119
  const parts = [`profile: ${PROFILE_LABEL}`];
116
120
  parts.push(IS_WRITE_FORBIDDEN_PROFILE ? 'READ-ONLY (enforced)' : 'read-only');
117
121
  const db = config.mysql.database || 'multi-db';
118
122
  parts.push(`database: ${db}`);
119
- if (CODE_BRANCH) {
120
- parts.push(`code: ${CODE_BRANCH} branch`);
123
+ const branch = codeBranchSource?.();
124
+ if (branch) {
125
+ parts.push(`code: ${branch} branch`);
121
126
  }
122
127
  const tunnel = describeTunnel();
123
128
  if (tunnel) {
@@ -495,4 +500,4 @@ async function executeReadOnlyQuery(sql, options = {}) {
495
500
  }
496
501
  }
497
502
  }
498
- export { profileBanner, describeConnection, executeQuery, getPool, executeWriteQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, clampTimeoutSeconds, describeQueryError, rollbackQuietly, poolPromise, };
503
+ export { profileBanner, describeConnection, executeQuery, getPool, executeWriteQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, rollbackQuietly, poolPromise, };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecubelabs/mysql-mcp",
3
- "version": "1.0.0-next.1",
3
+ "version": "1.0.0-next.2",
4
4
  "description": "Read-only MySQL MCP server that reaches its database through an SSH bastion, with per-environment profiles",
5
5
  "license": "MIT",
6
6
  "repository": {