@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.
package/README.md CHANGED
@@ -16,8 +16,8 @@ Tunnel은 서버가 직접 엽니다. 이미 쓰고 있는 `~/.ssh/config` alias
16
16
  - **기본 읽기 전용, prod는 깨뜨릴 수 없음.** `prod`/`production`은 설정과
17
17
  무관하게 모든 쓰기를 거부합니다.
18
18
  - **Map은 탐색이 아니라 선언.** 각 profile이 어떤 schema가 어떤 application의
19
- 것인지, 데이터가 어느 git branch에 대응하는지를 명시하므로, 모델은 이를
20
- 뒤져서 알아내는 대신 툴 설명에서 읽습니다.
19
+ 것인지 명시하므로, 모델은 이를 뒤져서 알아내는 대신 툴 설명에서 읽습니다.
20
+ 데이터가 어느 git branch에 대응하는지는 사용자가 한 번 확인해 catalog에 기록합니다.
21
21
  - **로컬 schema catalog.** 선언된 schema의 table 목록을 저장해 두고 TTL이 지나면
22
22
  다시 읽습니다. 실제 query에 등장한 table의 column·index·foreign key는 필요할 때만
23
23
  수집합니다.
@@ -81,8 +81,6 @@ customer-tycoon-api:tycoon:Internal sales/CRM tool;
81
81
  hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
82
82
  call-analyzer:call:Call transcription and analysis output;
83
83
  simulator:simulator:HubSpot API simulator, stage only" \
84
- -e MYSQL_DOCS_REPO=/path/to/haulla \
85
- -e MYSQL_CODE_BRANCH=develop \
86
84
  -e MYSQL_USER=<user> \
87
85
  -e MYSQL_PASS=<password> \
88
86
  -- npx -y @ecubelabs/mysql-mcp
@@ -95,8 +93,6 @@ core-api:haulla-shared:Tenant-shared data, also owned by core-api;
95
93
  customer-tycoon-api:tycoon:Internal sales/CRM tool;
96
94
  hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
97
95
  call-analyzer:call:Call transcription and analysis output" \
98
- -e MYSQL_DOCS_REPO=/path/to/haulla \
99
- -e MYSQL_CODE_BRANCH=main \
100
96
  -e MYSQL_USER=<user> \
101
97
  -e MYSQL_PASS=<password> \
102
98
  -- npx -y @ecubelabs/mysql-mcp
@@ -114,8 +110,6 @@ customer-tycoon-api:tycoon:Internal sales/CRM tool;
114
110
  hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
115
111
  call-analyzer:call:Call transcription and analysis output;
116
112
  simulator:simulator:HubSpot API simulator, stage only" \
117
- --env MYSQL_DOCS_REPO=/path/to/haulla \
118
- --env MYSQL_CODE_BRANCH=develop \
119
113
  --env MYSQL_USER=<user> \
120
114
  --env MYSQL_PASS=<password> \
121
115
  -- npx -y @ecubelabs/mysql-mcp
@@ -128,8 +122,6 @@ core-api:haulla-shared:Tenant-shared data, also owned by core-api;
128
122
  customer-tycoon-api:tycoon:Internal sales/CRM tool;
129
123
  hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
130
124
  call-analyzer:call:Call transcription and analysis output" \
131
- --env MYSQL_DOCS_REPO=/path/to/haulla \
132
- --env MYSQL_CODE_BRANCH=main \
133
125
  --env MYSQL_USER=<user> \
134
126
  --env MYSQL_PASS=<password> \
135
127
  -- npx -y @ecubelabs/mysql-mcp
@@ -137,18 +129,23 @@ call-analyzer:call:Call transcription and analysis output" \
137
129
 
138
130
  ### 3. table과 문서 연결하기 (선택)
139
131
 
140
- 2단계의 `MYSQL_DOCS_REPO`에 `model.md` 문서가 있는 저장소의 절대 경로를 넣었다면,
141
- 모델이 table과 문서를 연결해 둡니다. 그 뒤로 `describe`하면 연결된 문서의 경로와
142
- 읽는 명령이 함께 옵니다. 모델에게 연결을 요청하세요:
132
+ `model.md` 문서가 있는 저장소에서 세션을 열고 모델에게 연결을 요청하세요:
143
133
 
144
134
  ```text
145
135
  mysql-stage catalog의 table을 model.md 문서와 모두 연결해줘
146
136
  ```
147
137
 
148
- - 서버는 그 저장소의 `origin/<MYSQL_CODE_BRANCH>`를 읽고 `fetch`하지 않습니다.
149
- 최신 문서를 반영하려면 저장소에서 `git fetch`하세요.
150
- - `docs_list`는 후보를 `apps/<앱 이름>/` 아래의 `model.md`로 좁힙니다. 앱 이름은
151
- `MYSQL_APP_SCHEMAS`에 적은 이름이고, 그 아래에 문서가 없으면 전체 목록을 보여 줍니다.
138
+ - 모델이 저장소에서 문서를 찾아 저장소 기준 상대 경로와 GitHub 저장소(`owner/name`)로
139
+ 기록합니다. 서버는 파일이 있는지 확인하지 않습니다.
140
+ - 이 DB가 어느 branch에 대응하는지 처음 한 번 모델이 묻습니다. stage profile이면
141
+ `develop`, prod profile이면 `main`이 맞는지 확인합니다. 답은 catalog에 기록되어
142
+ 다음 세션에도 씁니다.
143
+ - 그 뒤로 `describe`하면 문서를 읽는 명령 두 개가 옵니다.
144
+ - `command`: 문서 저장소 안의 세션에서 `git show origin/<branch>:<경로>`
145
+ - `remoteCommand`: 어느 디렉터리에서든 `gh api`. 저장소 밖의 세션은 `gh auth login`이
146
+ 되어 있어야 합니다.
147
+ - `command`로 최신 문서를 읽으려면 저장소에서 `git fetch`하세요. 서버는 git을 실행하지
148
+ 않습니다.
152
149
 
153
150
  ## 사용법
154
151
 
@@ -225,25 +222,29 @@ A schema name that is not a bare identifier must be backtick-quoted, e.g. SELECT
225
222
  사실입니다. 그 schema에 어떤 테이블이 있는지는 [schema catalog](#schema-catalog)가
226
223
  데이터베이스에서 자동으로 갱신합니다.
227
224
 
228
- ### `MYSQL_CODE_BRANCH` — 데이터가 어느 branch에 대응하는가
225
+ ### 코드 branch — 데이터가 어느 branch에 대응하는가
229
226
 
230
227
  행과 코드를 대조하는 모델에게는 올바른 checkout이 필요한데, 틀렸을 때 조용히
231
228
  실패합니다. stage column을 `main` 기준으로 읽으면 branch가 잘못된 것이 아니라
232
- migration이 빠진 것처럼 보이기 때문입니다. 그래서 각 profile이 자기 branch를
233
- 명시하며, 이 값은 툴 설명과 응답 banner 양쪽에 나타납니다:
234
-
235
- ```dotenv
236
- MYSQL_CODE_BRANCH=develop # stage profile
237
- MYSQL_CODE_BRANCH=main # prod profile
238
- ```
239
-
240
- 설정하지 않으면 profile에 따라 기본값이 정해집니다.
241
-
242
- | Profile | 기본 branch |
243
- | --------------------------------------- | ----------- |
244
- | `stage` / `staging` / `dev` / `develop` | `develop` |
245
- | `prod` / `production` | `main` |
246
- | 그 밖 | 말하지 않음 |
229
+ migration이 빠진 것처럼 보이기 때문입니다.
230
+
231
+ - Branch는 사용자가 확인한 값을 `mysql_catalog {action:"branch", branch:"develop"}`로
232
+ catalog에 기록합니다. 서버는 env나 profile로 정하지 않습니다.
233
+ - 기록된 branch는 툴 설명의 `CODE REVISION`, 응답 banner의 `code: <branch> branch`,
234
+ `mysql://schemas`의 `codeBranch`, `describe`의 문서 읽기 명령에 나타납니다. 기록
235
+ 전에는 어디에도 나오지 않습니다.
236
+ - 툴 설명은 서버 시작 때 한 번 만들어집니다. 세션 중에 바꾸면 banner와 `branch`
237
+ 응답이 새 값을 알립니다.
238
+ - Catalog가 꺼진 profile(`MYSQL_CATALOG_ENABLED=false` 또는 `MYSQL_APP_SCHEMAS` 없음)은
239
+ branch를 기록할 곳이 없어 표시하지 않습니다.
240
+ - 기록 전에는 `describe`와 query 응답이 기록하라고 안내합니다. profile별 제안은 질문
241
+ 형태이고 저장되지 않습니다.
242
+
243
+ | Profile | 제안하는 branch |
244
+ | --------------------------------------- | --------------- |
245
+ | `stage` / `staging` / `dev` / `develop` | `develop` |
246
+ | `prod` / `production` | `main` |
247
+ | 그 밖 | 제안 없이 물음 |
247
248
 
248
249
  ## Schema catalog
249
250
 
@@ -277,17 +278,18 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
277
278
 
278
279
  **문서 연결**
279
280
 
280
- - `docs_list`: schema를 소유한 application 아래의 `model.md` 후보만 봅니다.
281
- - 범위는 `MYSQL_APP_SCHEMAS`의 application 이름을 저장소의 `apps/<application>/`
282
- directory로 보고 좁힙니다.
283
- - 응답의 `scopedToApp`이 이 규약이 적용됐는지 알려주고, 범위 밖 문서 수를 함께
284
- 보고합니다.
285
- - 규약에 맞는 문서가 없으면 전체 목록을 반환하고 그 이유를 `notice`에 적습니다.
286
- - 범위 밖 경로도 `docs_read`로 읽을 수 있습니다.
287
- - `docs_read`: shell을 쓸 수 없는 클라이언트에서도 선택한 문서의 최신 내용을
288
- 읽습니다.
289
- - `link`: 모델이 판단한 table↔문서 연결을 배열로 한꺼번에 저장합니다.
281
+ - `link`: 모델이 찾은 table↔문서 연결을 배열로 한꺼번에 저장합니다. 하나라도 틀리면
282
+ 아무것도 저장하지 않습니다.
283
+ - `doc`: 저장소 기준 상대 경로. 절대 경로와 `..`은 거절합니다.
284
+ - `repo`: 문서가 있는 GitHub 저장소. `owner/name`,
285
+ `https://github.com/owner/name(.git)`, `git@github.com:owner/name(.git)`을 받아
286
+ `owner/name`으로 저장하고, github.com이 아닌 host는 거절합니다. 모델은
287
+ `git remote get-url origin`으로 얻습니다.
290
288
  - `unlink`: 연결을 지우거나 해당 table에 연결할 문서가 없음을 기록합니다.
289
+ - `branch`: 사용자가 확인한 코드 branch를 기록합니다. 처음 기록과 변경을 함께
290
+ 받고, 응답이 무엇을 기록했는지 또는 `이전 → 새` 값을 알립니다. `origin/` 접두어는
291
+ 떼고 저장합니다. git으로 확인하지 않는 대신 `git check-ref-format --branch`에 준하는
292
+ 형식만 받습니다. 공백·제어문자·`~^:?*[\`·`..`·`@{`는 거절하고, 100자까지입니다.
291
293
 
292
294
  **기록 관리**
293
295
 
@@ -297,27 +299,28 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
297
299
  - `forget`: `target` table의 `notes`, `aliases`, `usage`, `joins`, `metadata` 중 한
298
300
  범위를 지웁니다. `metadata`는 다음 `describe` 또는 정상 query 뒤에 다시 수집됩니다.
299
301
  문서 판단은 지우지 않으며, 그 작업에는 `unlink`를 사용합니다.
300
- - `refresh`: 지정한 범위를 강제로 다시 수집합니다. `target`을 생략하면 inventory와
301
- 문서를 함께 갱신합니다.
302
+ - `refresh`: 지정한 범위를 강제로 다시 수집합니다. `target`을 생략하면 inventory를
303
+ 갱신합니다.
302
304
 
303
305
  | `target` | 다시 수집하는 것 |
304
306
  | ------------------ | ----------------------------------- |
305
307
  | `schema.table` | 그 table의 column·index·foreign key |
306
308
  | 선언된 schema 이름 | table inventory |
307
- | `docs` | 문서 ref |
308
309
 
309
- ### 문서 catalog
310
-
311
- - 서버 시작 시 git을 실행하지 않고, 문서가 처음 필요해질 때 깨어납니다.
312
- - 항상 local working tree가 아니라 `origin/<MYSQL_CODE_BRANCH>`를 읽습니다. 서버가
313
- `fetch`, `checkout`, `pull`을 실행하는 일은 없습니다.
314
- - 문서 내용이 아니라 경로와 ref commit만 저장합니다.
315
- - Ref가 바뀌면 추가와 삭제를 반영하고, git이 보고한 rename은 기존 table 연결에도
316
- 그대로 적용합니다. 내용 수정은 경로를 낡게 만들지 않으므로 별도 작업을 하지
317
- 않습니다.
318
- - 연결된 문서는 `describe` 응답에서 경로, ref, 바로 실행할 수 있는 `git show`
319
- 명령을 함께 제공합니다.
320
- - 마지막 ref commit이 30일보다 오래됐으면 동작은 계속하되 응답에 경고를 붙입니다.
310
+ ### 문서 연결
311
+
312
+ - 서버는 문서를 색인하지도 읽지도 않고, 문서 저장소가 어디 있는지도 모릅니다.
313
+ 문서를 찾고 읽는 것은 모델이 세션의 저장소에서 합니다.
314
+ - 서버가 저장하는 것은 table별 문서 경로(저장소 기준 상대 경로), GitHub 저장소,
315
+ "문서 없음" 기록뿐입니다. 파일이 있는지, 옮겨졌는지는 확인하지 않습니다.
316
+ - `describe`의 `docs`는 `path`, `repo`, `branch`(기록된 branch), `command`,
317
+ `remoteCommand`, `guidance`입니다.
318
+ - 두 명령 모두 working tree가 아니라 그 branch를 읽습니다. checkout된 branch가 이
319
+ DB와 다를 수 있어서입니다. branch가 기록되지 않았으면 명령 대신 기록하라는
320
+ 안내가 붙습니다.
321
+ - `remoteCommand`는 경로를 세그먼트별로 URL 인코딩하므로 한글 경로도 읽습니다.
322
+ - 문서 판단이 없는 table을 읽으면 query 응답에 연결을 유도하는 안내가 한 번 붙습니다.
323
+ `link`나 `unlink`로 판단을 남기면 그 table에는 더 붙지 않습니다.
321
324
 
322
325
  ### 사용 기록과 hot table
323
326
 
@@ -383,7 +386,7 @@ Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼
383
386
  | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
384
387
  | `mysql://tables` | table 목록. 이름, schema, comment, 예상 row 수. catalog가 켜져 있으면 선언된 schema의 저장된 inventory로 답하고, 꺼져 있거나 아직 비어 있으면 `information_schema`에서 읽을 수 있는 모든 table을 읽습니다 — 이때는 크기와 생성·수정 시각도 함께 옵니다. |
385
388
  | `mysql://tables/<schema>/<table>` | 한 table의 구조. catalog가 켜져 있으면 `mysql_catalog describe`와 같은 내용이고, 실패하면 `information_schema`의 column 목록으로 물러납니다. catalog가 꺼져 있으면 `information_schema`의 column 목록을 바로 돌려줍니다. |
386
- | `mysql://schemas` | 선언된 app -> schema map. `profile`, `apps`, 그리고 branch가 정해져 있으면 `codeBranch`를 담은 JSON입니다. `MYSQL_APP_SCHEMAS`가 비어 있으면 목록에 오르지 않습니다. |
389
+ | `mysql://schemas` | 선언된 app -> schema map. `profile`, `apps`, 그리고 branch가 기록돼 있으면 `codeBranch`를 담은 JSON입니다. `MYSQL_APP_SCHEMAS`가 비어 있으면 목록에 오르지 않습니다. |
387
390
 
388
391
  ## 환경 변수
389
392
 
@@ -392,15 +395,13 @@ Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼
392
395
 
393
396
  ### Profile
394
397
 
395
- | 변수 | 기본값 | 의미 |
396
- | ------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
397
- | `MYSQL_PROFILE` | _(미설정)_ | 환경 label. `prod`/`production`은 읽기 전용을 강제합니다. |
398
- | `MYSQL_APP_SCHEMAS` | _(미설정)_ | `;`로 구분된 `app:schema[:설명]` 항목. 툴 설명과 `mysql://schemas`에 노출됩니다. |
399
- | `MYSQL_CODE_BRANCH` | profile별 | 이 환경의 데이터가 대응하는 git branch. `stage`→`develop`, `prod`→`main`. |
400
- | `MYSQL_CATALOG_ENABLED` | `true` | 로컬 schema catalog를 켭니다. `false`이거나 `MYSQL_APP_SCHEMAS`가 비어 있으면 catalog가 꺼지고 `mysql_catalog` 툴도 제공되지 않습니다. |
401
- | `MYSQL_CATALOG_PATH` | `~/.cache/mysql-mcp/catalog` | profile·대상·user별 JSON 파일을 둘 directory입니다. |
402
- | `MYSQL_CATALOG_TTL_HOURS` | `24` | DB metadata를 stale로 보는 시간입니다. |
403
- | `MYSQL_DOCS_REPO` | _(미설정)_ | `model.md`가 있는 git 저장소. 문서 catalog는 이 값과 `MYSQL_CODE_BRANCH`가 **둘 다** 있어야 켜집니다 — ref를 branch에서 가져오기 때문입니다. 둘 중 하나라도 비면 문서 축만 비활성입니다. |
398
+ | 변수 | 기본값 | 의미 |
399
+ | ------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
400
+ | `MYSQL_PROFILE` | _(미설정)_ | 환경 label. `prod`/`production`은 읽기 전용을 강제합니다. |
401
+ | `MYSQL_APP_SCHEMAS` | _(미설정)_ | `;`로 구분된 `app:schema[:설명]` 항목. 툴 설명과 `mysql://schemas`에 노출됩니다. |
402
+ | `MYSQL_CATALOG_ENABLED` | `true` | 로컬 schema catalog를 켭니다. `false`이거나 `MYSQL_APP_SCHEMAS`가 비어 있으면 catalog가 꺼지고 `mysql_catalog` 툴도 제공되지 않습니다. |
403
+ | `MYSQL_CATALOG_PATH` | `~/.cache/mysql-mcp/catalog` | profile·대상·user별 JSON 파일을 둘 directory입니다. |
404
+ | `MYSQL_CATALOG_TTL_HOURS` | `24` | DB metadata를 stale로 보는 시간입니다. |
404
405
 
405
406
  ### SSH tunnel
406
407
 
package/dist/index.js CHANGED
@@ -6,9 +6,9 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
6
6
  import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
7
7
  import { log, sharedOnce, tableResourceUri } from './src/utils/index.js';
8
8
  import { writeCapabilities } from './src/db/permissions.js';
9
- import { SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, isMultiDbMode, mcpConfig as config, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, APP_SCHEMAS, CODE_BRANCH, MYSQL_CATALOG_ENABLED, MYSQL_CATALOG_PATH, MYSQL_CATALOG_TTL_HOURS, MYSQL_DOCS_REPO, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, MYSQL_SSL_ENABLED, MYSQL_SSL_CA_PATH, MYSQL_SSL_CERT_PATH, MYSQL_SSL_KEY_PATH, PACKAGE_VERSION, SSH_ENABLED, } from './src/config/index.js';
9
+ import { SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, isMultiDbMode, mcpConfig as config, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, APP_SCHEMAS, MYSQL_CATALOG_ENABLED, MYSQL_CATALOG_PATH, MYSQL_CATALOG_TTL_HOURS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, MYSQL_SSL_ENABLED, MYSQL_SSL_CA_PATH, MYSQL_SSL_CERT_PATH, MYSQL_SSL_KEY_PATH, PACKAGE_VERSION, SSH_ENABLED, } from './src/config/index.js';
10
10
  import { catalogIdentity, SchemaCatalog } from './src/catalog/index.js';
11
- import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
11
+ import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
12
12
  import { describeTunnel, ensureTunnel, resolveTunnelConfig, stopTunnel } from './src/ssh/tunnel.js';
13
13
  log('info', `Starting MySQL MCP server v${PACKAGE_VERSION}...`);
14
14
  const toolVersion = `MySQL MCP Server [v${PACKAGE_VERSION}]`;
@@ -42,25 +42,27 @@ baseToolDescription +=
42
42
  `${MAX_RESPONSE_ROWS.toLocaleString('en-US')} rows. Aggregate in SQL rather than pulling rows to count them. ` +
43
43
  `USE and SET are rejected; write schema.table instead of USE. ` +
44
44
  `Executable comments (/*! ... */) and MAX_EXECUTION_TIME or SET_VAR hints are rejected; use timeout_seconds instead.`;
45
- if (CODE_BRANCH) {
46
- baseToolDescription +=
47
- `\n\nCODE REVISION: this database matches the \`${CODE_BRANCH}\` branch. ` +
48
- `Read entities, migrations, and queries from that branch when correlating code with data.`;
45
+ function codeRevisionDescription(branch) {
46
+ return branch
47
+ ? `\n\nCODE REVISION: this database matches the \`${branch}\` branch. ` +
48
+ `Read entities, migrations, and queries from that branch when correlating code with data.`
49
+ : '';
49
50
  }
51
+ let appSchemaDescription = '';
50
52
  if (APP_SCHEMAS.length > 0) {
51
- baseToolDescription +=
53
+ appSchemaDescription +=
52
54
  '\n\nAPP -> SCHEMA (authoritative — use these directly; do not run SHOW DATABASES ' +
53
55
  'or search information_schema to find a schema):';
54
56
  for (const entry of APP_SCHEMAS) {
55
- baseToolDescription +=
57
+ appSchemaDescription +=
56
58
  `\n - ${entry.app} -> ${entry.schema}` + (entry.description ? ` — ${entry.description}` : '');
57
59
  }
58
- baseToolDescription +=
60
+ appSchemaDescription +=
59
61
  '\nQualify every table with its schema (schema.table). Any schema not listed here is ' +
60
62
  'either absent from this environment or not owned by an application.';
61
63
  const needsQuoting = APP_SCHEMAS.find((entry) => !/^[A-Za-z0-9_$]+$/.test(entry.schema));
62
64
  if (needsQuoting) {
63
- baseToolDescription +=
65
+ appSchemaDescription +=
64
66
  `\nA schema name that is not a bare identifier must be backtick-quoted, ` +
65
67
  `e.g. SELECT ... FROM \`${needsQuoting.schema}\`.some_table.`;
66
68
  }
@@ -70,8 +72,11 @@ const mysqlCatalogTool = {
70
72
  name: 'mysql_catalog',
71
73
  description: 'Read the local schema catalog without rediscovering database metadata. ' +
72
74
  'Use map for the app/schema overview, search to find tables or known columns, ' +
73
- 'describe before writing SQL, and docs_list/docs_read to inspect domain documents. ' +
74
- "Use link or unlink to record the model's document decision. " +
75
+ 'and describe before writing SQL. ' +
76
+ 'Use link to record the repository-relative path of the domain document (model.md) ' +
77
+ 'you found for a table, or unlink to record that none exists. ' +
78
+ 'Use branch to record the code branch that matches this database, once the user ' +
79
+ 'confirmed it. ' +
75
80
  'Use note to save a table memo or alias, and forget to clear one catalog scope. ' +
76
81
  'Use refresh when cached metadata contradicts what a query actually returned, ' +
77
82
  'or right after a migration: added columns and indexes raise no error, so ' +
@@ -81,18 +86,7 @@ const mysqlCatalogTool = {
81
86
  properties: {
82
87
  action: {
83
88
  type: 'string',
84
- enum: [
85
- 'map',
86
- 'search',
87
- 'describe',
88
- 'docs_list',
89
- 'docs_read',
90
- 'link',
91
- 'unlink',
92
- 'note',
93
- 'forget',
94
- 'refresh',
95
- ],
89
+ enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'note', 'forget', 'refresh'],
96
90
  description: 'Catalog operation to perform',
97
91
  },
98
92
  q: {
@@ -110,22 +104,18 @@ const mysqlCatalogTool = {
110
104
  description: 'Qualified schema.table name for describe, or for unlink. note and ' +
111
105
  'forget take the same name as target instead.',
112
106
  },
113
- schema: {
114
- type: 'string',
115
- description: 'Declared schema name for docs_list. Results are narrowed to the ' +
116
- 'documents under the app directory declared for that schema; the ' +
117
- 'response says so and reports how many were left out.',
118
- },
119
- path: {
107
+ branch: {
120
108
  type: 'string',
121
- description: 'Cataloged model.md path for docs_read',
109
+ maxLength: 100,
110
+ description: 'Branch name for branch, e.g. develop: the branch whose code matches this ' +
111
+ "database's data. Pass it only after the user confirmed it; it replaces the " +
112
+ 'recorded branch.',
122
113
  },
123
114
  target: {
124
115
  type: 'string',
125
116
  description: 'Qualified schema.table for note or forget. For refresh: "schema.table" for one table\'s ' +
126
117
  'columns, indexes and foreign keys; a declared schema name for the ' +
127
- 'table inventory; "docs" to re-read the document ref after a git ' +
128
- 'fetch. Omit it to refresh the inventory and the documents together.',
118
+ 'table inventory. Omit it to refresh the inventory.',
129
119
  },
130
120
  text: {
131
121
  type: 'string',
@@ -155,10 +145,17 @@ const mysqlCatalogTool = {
155
145
  },
156
146
  doc: {
157
147
  type: 'string',
158
- description: 'Cataloged model.md path',
148
+ description: 'Document path relative to the repository root, e.g. apps/<app>/.../model.md',
149
+ },
150
+ repo: {
151
+ type: 'string',
152
+ description: 'GitHub repository holding the document, as owner/name. Take it from ' +
153
+ '`git remote get-url origin` in that repository; https and git@ URLs are ' +
154
+ 'accepted. describe uses it for a command that reads the document from ' +
155
+ 'any directory.',
159
156
  },
160
157
  },
161
- required: ['table', 'doc'],
158
+ required: ['table', 'doc', 'repo'],
162
159
  },
163
160
  },
164
161
  },
@@ -237,19 +234,19 @@ export default function createMcpServer() {
237
234
  filePath: identity.filePath,
238
235
  ttlHours: MYSQL_CATALOG_TTL_HOURS,
239
236
  appSchemas: APP_SCHEMAS,
240
- docsRepo: MYSQL_DOCS_REPO ?? null,
241
- docsRef: CODE_BRANCH ? `origin/${CODE_BRANCH}` : null,
242
237
  defaultSchema: typeof mysqlSettings.database === 'string' ? mysqlSettings.database : null,
243
238
  });
244
239
  setQueryDiagnosticsSource({
245
240
  indexFacts: (reference) => catalog.indexFacts(reference),
246
241
  });
247
- if (baseToolDescription.length > TOOL_DESCRIPTION_LIMIT) {
248
- console.error(`[warn] tool description is ${baseToolDescription.length} characters before the ` +
242
+ setCodeBranchSource(() => catalog.codeBranch());
243
+ const queryBaseDescription = baseToolDescription + codeRevisionDescription(catalog.codeBranch()) + appSchemaDescription;
244
+ if (queryBaseDescription.length > TOOL_DESCRIPTION_LIMIT) {
245
+ console.error(`[warn] tool description is ${queryBaseDescription.length} characters before the ` +
249
246
  `catalog tail; clients keep ${TOOL_DESCRIPTION_LIMIT} and silently drop the rest. ` +
250
247
  `Shorten MYSQL_APP_SCHEMAS descriptions, or the text in index.ts.`);
251
248
  }
252
- const mysqlQueryDescription = () => baseToolDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - baseToolDescription.length);
249
+ const mysqlQueryDescription = () => queryBaseDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - queryBaseDescription.length);
253
250
  const loadResourceTables = async () => {
254
251
  if (catalog.isEnabled()) {
255
252
  try {
@@ -329,6 +326,7 @@ export default function createMcpServer() {
329
326
  try {
330
327
  log('info', 'Handling ReadResourceRequest:', request.params.uri);
331
328
  if (request.params.uri === 'mysql://schemas') {
329
+ const codeBranch = catalog.codeBranch();
332
330
  return {
333
331
  contents: [
334
332
  {
@@ -336,7 +334,7 @@ export default function createMcpServer() {
336
334
  mimeType: 'application/json',
337
335
  text: JSON.stringify({
338
336
  profile: PROFILE_LABEL,
339
- ...(CODE_BRANCH ? { codeBranch: CODE_BRANCH } : {}),
337
+ ...(codeBranch ? { codeBranch } : {}),
340
338
  apps: APP_SCHEMAS,
341
339
  }, null, 2),
342
340
  },
@@ -432,25 +430,14 @@ export default function createMcpServer() {
432
430
  }
433
431
  text = await catalog.describe(args.table);
434
432
  }
435
- else if (action === 'docs_list') {
436
- if (typeof args.schema !== 'string' || !args.schema.trim()) {
437
- throw new Error('mysql_catalog docs_list requires "schema".');
438
- }
439
- text = await catalog.docsList(args.schema);
440
- }
441
- else if (action === 'docs_read') {
442
- if (typeof args.path !== 'string' || !args.path.trim()) {
443
- throw new Error('mysql_catalog docs_read requires "path".');
444
- }
445
- text = await catalog.docsRead(args.path);
446
- }
447
433
  else if (action === 'link') {
448
434
  if (!Array.isArray(args.links) ||
449
435
  !args.links.every((link) => link &&
450
436
  typeof link === 'object' &&
451
437
  typeof link.table === 'string' &&
452
- typeof link.doc === 'string')) {
453
- throw new Error('mysql_catalog link requires "links" as [{table, doc}, ...].');
438
+ typeof link.doc === 'string' &&
439
+ typeof link.repo === 'string')) {
440
+ throw new Error('mysql_catalog link requires "links" as [{table, doc, repo}, ...].');
454
441
  }
455
442
  text = await catalog.link(args.links);
456
443
  }
@@ -484,6 +471,12 @@ export default function createMcpServer() {
484
471
  }
485
472
  text = await catalog.forget(args.target, args.scope);
486
473
  }
474
+ else if (action === 'branch') {
475
+ if (typeof args.branch !== 'string' || !args.branch.trim()) {
476
+ throw new Error('mysql_catalog branch requires "branch", e.g. develop.');
477
+ }
478
+ text = catalog.setCodeBranch(args.branch);
479
+ }
487
480
  else if (action === 'refresh') {
488
481
  if (args.target !== undefined && typeof args.target !== 'string') {
489
482
  throw new Error('mysql_catalog refresh takes "target" as a string.');
@@ -0,0 +1,58 @@
1
+ const REMOTE_PREFIX = 'origin/';
2
+ const BRANCH_MAX_LENGTH = 100;
3
+ const SUGGESTED_BRANCH = {
4
+ stage: 'develop',
5
+ staging: 'develop',
6
+ dev: 'develop',
7
+ develop: 'develop',
8
+ prod: 'main',
9
+ production: 'main',
10
+ };
11
+ export function suggestedBranch(profile) {
12
+ return SUGGESTED_BRANCH[profile.toLowerCase()] ?? null;
13
+ }
14
+ export function normalizeBranchName(input) {
15
+ const trimmed = input.trim();
16
+ const branch = trimmed.startsWith(REMOTE_PREFIX) ? trimmed.slice(REMOTE_PREFIX.length) : trimmed;
17
+ const reject = (reason) => {
18
+ throw new Error(`Invalid branch name ${JSON.stringify(input)}: ${reason}.`);
19
+ };
20
+ if (!branch) {
21
+ reject('it is empty');
22
+ }
23
+ if (branch.length > BRANCH_MAX_LENGTH) {
24
+ reject(`it is longer than ${BRANCH_MAX_LENGTH} characters`);
25
+ }
26
+ if (/[\u0000-\u0020\u007f]/.test(branch)) {
27
+ reject('it contains whitespace or a control character');
28
+ }
29
+ if (/[~^:?*[\\]/.test(branch)) {
30
+ reject('it contains one of ~ ^ : ? * [ \\');
31
+ }
32
+ if (branch.includes('..') || branch.includes('@{') || branch === '@') {
33
+ reject('it contains "..", "@{", or is "@"');
34
+ }
35
+ if (branch.startsWith('-') || branch.startsWith('/') || branch.endsWith('/') || branch.includes('//')) {
36
+ reject('it starts with "-" or has an empty path component');
37
+ }
38
+ if (branch.endsWith('.')) {
39
+ reject('it ends with "."');
40
+ }
41
+ for (const component of branch.split('/')) {
42
+ if (component.startsWith('.') || component.endsWith('.lock')) {
43
+ reject('a component starts with "." or ends with ".lock"');
44
+ }
45
+ }
46
+ return branch;
47
+ }
48
+ export function loadedBranch(value) {
49
+ if (typeof value !== 'string') {
50
+ return null;
51
+ }
52
+ try {
53
+ return normalizeBranchName(value);
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }