@ecubelabs/mysql-mcp 1.0.0-next.1 → 1.0.0-next.3

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,30 @@ 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
+ - 기록 전에는 `mysql_catalog` 툴 설명이 문서를 연결하기 전에 물으라고 지시하고,
241
+ `describe`·`link`·query 응답이 기록하라고 안내합니다. profile별 제안은 질문
242
+ 형태이고 저장되지 않습니다.
243
+
244
+ | Profile | 제안하는 branch |
245
+ | --------------------------------------- | --------------- |
246
+ | `stage` / `staging` / `dev` / `develop` | `develop` |
247
+ | `prod` / `production` | `main` |
248
+ | 그 밖 | 제안 없이 물음 |
247
249
 
248
250
  ## Schema catalog
249
251
 
@@ -277,17 +279,18 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
277
279
 
278
280
  **문서 연결**
279
281
 
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↔문서 연결을 배열로 한꺼번에 저장합니다.
282
+ - `link`: 모델이 찾은 table↔문서 연결을 배열로 한꺼번에 저장합니다. 하나라도 틀리면
283
+ 아무것도 저장하지 않습니다.
284
+ - `doc`: 저장소 기준 상대 경로. 절대 경로와 `..`은 거절합니다.
285
+ - `repo`: 문서가 있는 GitHub 저장소. `owner/name`,
286
+ `https://github.com/owner/name(.git)`, `git@github.com:owner/name(.git)`을 받아
287
+ `owner/name`으로 저장하고, github.com이 아닌 host는 거절합니다. 모델은
288
+ `git remote get-url origin`으로 얻습니다.
290
289
  - `unlink`: 연결을 지우거나 해당 table에 연결할 문서가 없음을 기록합니다.
290
+ - `branch`: 사용자가 확인한 코드 branch를 기록합니다. 처음 기록과 변경을 함께
291
+ 받고, 응답이 무엇을 기록했는지 또는 `이전 → 새` 값을 알립니다. `origin/` 접두어는
292
+ 떼고 저장합니다. git으로 확인하지 않는 대신 `git check-ref-format --branch`에 준하는
293
+ 형식만 받습니다. 공백·제어문자·`~^:?*[\`·`..`·`@{`는 거절하고, 100자까지입니다.
291
294
 
292
295
  **기록 관리**
293
296
 
@@ -297,27 +300,28 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
297
300
  - `forget`: `target` table의 `notes`, `aliases`, `usage`, `joins`, `metadata` 중 한
298
301
  범위를 지웁니다. `metadata`는 다음 `describe` 또는 정상 query 뒤에 다시 수집됩니다.
299
302
  문서 판단은 지우지 않으며, 그 작업에는 `unlink`를 사용합니다.
300
- - `refresh`: 지정한 범위를 강제로 다시 수집합니다. `target`을 생략하면 inventory와
301
- 문서를 함께 갱신합니다.
303
+ - `refresh`: 지정한 범위를 강제로 다시 수집합니다. `target`을 생략하면 inventory를
304
+ 갱신합니다.
302
305
 
303
306
  | `target` | 다시 수집하는 것 |
304
307
  | ------------------ | ----------------------------------- |
305
308
  | `schema.table` | 그 table의 column·index·foreign key |
306
309
  | 선언된 schema 이름 | table inventory |
307
- | `docs` | 문서 ref |
308
310
 
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일보다 오래됐으면 동작은 계속하되 응답에 경고를 붙입니다.
311
+ ### 문서 연결
312
+
313
+ - 서버는 문서를 색인하지도 읽지도 않고, 문서 저장소가 어디 있는지도 모릅니다.
314
+ 문서를 찾고 읽는 것은 모델이 세션의 저장소에서 합니다.
315
+ - 서버가 저장하는 것은 table별 문서 경로(저장소 기준 상대 경로), GitHub 저장소,
316
+ "문서 없음" 기록뿐입니다. 파일이 있는지, 옮겨졌는지는 확인하지 않습니다.
317
+ - `describe`의 `docs`는 `path`, `repo`, `branch`(기록된 branch), `command`,
318
+ `remoteCommand`, `guidance`입니다.
319
+ - 두 명령 모두 working tree가 아니라 그 branch를 읽습니다. checkout된 branch가 이
320
+ DB와 다를 수 있어서입니다. branch가 기록되지 않았으면 명령 대신 기록하라는
321
+ 안내가 붙습니다.
322
+ - `remoteCommand`는 경로를 세그먼트별로 URL 인코딩하므로 한글 경로도 읽습니다.
323
+ - 문서 판단이 없는 table을 읽으면 query 응답에 연결을 유도하는 안내가 한 번 붙습니다.
324
+ `link`나 `unlink`로 판단을 남기면 그 table에는 더 붙지 않습니다.
321
325
 
322
326
  ### 사용 기록과 hot table
323
327
 
@@ -383,7 +387,7 @@ Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼
383
387
  | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
384
388
  | `mysql://tables` | table 목록. 이름, schema, comment, 예상 row 수. catalog가 켜져 있으면 선언된 schema의 저장된 inventory로 답하고, 꺼져 있거나 아직 비어 있으면 `information_schema`에서 읽을 수 있는 모든 table을 읽습니다 — 이때는 크기와 생성·수정 시각도 함께 옵니다. |
385
389
  | `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`가 비어 있으면 목록에 오르지 않습니다. |
390
+ | `mysql://schemas` | 선언된 app -> schema map. `profile`, `apps`, 그리고 branch가 기록돼 있으면 `codeBranch`를 담은 JSON입니다. `MYSQL_APP_SCHEMAS`가 비어 있으면 목록에 오르지 않습니다. |
387
391
 
388
392
  ## 환경 변수
389
393
 
@@ -392,15 +396,13 @@ Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼
392
396
 
393
397
  ### Profile
394
398
 
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에서 가져오기 때문입니다. 둘 중 하나라도 비면 문서 축만 비활성입니다. |
399
+ | 변수 | 기본값 | 의미 |
400
+ | ------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
401
+ | `MYSQL_PROFILE` | _(미설정)_ | 환경 label. `prod`/`production`은 읽기 전용을 강제합니다. |
402
+ | `MYSQL_APP_SCHEMAS` | _(미설정)_ | `;`로 구분된 `app:schema[:설명]` 항목. 툴 설명과 `mysql://schemas`에 노출됩니다. |
403
+ | `MYSQL_CATALOG_ENABLED` | `true` | 로컬 schema catalog를 켭니다. `false`이거나 `MYSQL_APP_SCHEMAS`가 비어 있으면 catalog가 꺼지고 `mysql_catalog` 툴도 제공되지 않습니다. |
404
+ | `MYSQL_CATALOG_PATH` | `~/.cache/mysql-mcp/catalog` | profile·대상·user별 JSON 파일을 둘 directory입니다. |
405
+ | `MYSQL_CATALOG_TTL_HOURS` | `24` | DB metadata를 stale로 보는 시간입니다. |
404
406
 
405
407
  ### SSH tunnel
406
408
 
package/dist/index.js CHANGED
@@ -6,9 +6,10 @@ 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
+ import { missingBranchToolInstruction } from './src/catalog/branch.js';
10
11
  import { catalogIdentity, SchemaCatalog } from './src/catalog/index.js';
11
- import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
12
+ import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
12
13
  import { describeTunnel, ensureTunnel, resolveTunnelConfig, stopTunnel } from './src/ssh/tunnel.js';
13
14
  log('info', `Starting MySQL MCP server v${PACKAGE_VERSION}...`);
14
15
  const toolVersion = `MySQL MCP Server [v${PACKAGE_VERSION}]`;
@@ -42,25 +43,27 @@ baseToolDescription +=
42
43
  `${MAX_RESPONSE_ROWS.toLocaleString('en-US')} rows. Aggregate in SQL rather than pulling rows to count them. ` +
43
44
  `USE and SET are rejected; write schema.table instead of USE. ` +
44
45
  `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.`;
46
+ function codeRevisionDescription(branch) {
47
+ return branch
48
+ ? `\n\nCODE REVISION: this database matches the \`${branch}\` branch. ` +
49
+ `Read entities, migrations, and queries from that branch when correlating code with data.`
50
+ : '';
49
51
  }
52
+ let appSchemaDescription = '';
50
53
  if (APP_SCHEMAS.length > 0) {
51
- baseToolDescription +=
54
+ appSchemaDescription +=
52
55
  '\n\nAPP -> SCHEMA (authoritative — use these directly; do not run SHOW DATABASES ' +
53
56
  'or search information_schema to find a schema):';
54
57
  for (const entry of APP_SCHEMAS) {
55
- baseToolDescription +=
58
+ appSchemaDescription +=
56
59
  `\n - ${entry.app} -> ${entry.schema}` + (entry.description ? ` — ${entry.description}` : '');
57
60
  }
58
- baseToolDescription +=
61
+ appSchemaDescription +=
59
62
  '\nQualify every table with its schema (schema.table). Any schema not listed here is ' +
60
63
  'either absent from this environment or not owned by an application.';
61
64
  const needsQuoting = APP_SCHEMAS.find((entry) => !/^[A-Za-z0-9_$]+$/.test(entry.schema));
62
65
  if (needsQuoting) {
63
- baseToolDescription +=
66
+ appSchemaDescription +=
64
67
  `\nA schema name that is not a bare identifier must be backtick-quoted, ` +
65
68
  `e.g. SELECT ... FROM \`${needsQuoting.schema}\`.some_table.`;
66
69
  }
@@ -70,8 +73,11 @@ const mysqlCatalogTool = {
70
73
  name: 'mysql_catalog',
71
74
  description: 'Read the local schema catalog without rediscovering database metadata. ' +
72
75
  '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. " +
76
+ 'and describe before writing SQL. ' +
77
+ 'Use link to record the repository-relative path of the domain document (model.md) ' +
78
+ 'you found for a table, or unlink to record that none exists. ' +
79
+ 'Use branch to record the code branch that matches this database, once the user ' +
80
+ 'confirmed it. ' +
75
81
  'Use note to save a table memo or alias, and forget to clear one catalog scope. ' +
76
82
  'Use refresh when cached metadata contradicts what a query actually returned, ' +
77
83
  'or right after a migration: added columns and indexes raise no error, so ' +
@@ -81,18 +87,7 @@ const mysqlCatalogTool = {
81
87
  properties: {
82
88
  action: {
83
89
  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
- ],
90
+ enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'note', 'forget', 'refresh'],
96
91
  description: 'Catalog operation to perform',
97
92
  },
98
93
  q: {
@@ -110,22 +105,18 @@ const mysqlCatalogTool = {
110
105
  description: 'Qualified schema.table name for describe, or for unlink. note and ' +
111
106
  'forget take the same name as target instead.',
112
107
  },
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: {
108
+ branch: {
120
109
  type: 'string',
121
- description: 'Cataloged model.md path for docs_read',
110
+ maxLength: 100,
111
+ description: 'Branch name for branch, e.g. develop: the branch whose code matches this ' +
112
+ "database's data. Pass it only after the user confirmed it; it replaces the " +
113
+ 'recorded branch.',
122
114
  },
123
115
  target: {
124
116
  type: 'string',
125
117
  description: 'Qualified schema.table for note or forget. For refresh: "schema.table" for one table\'s ' +
126
118
  '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.',
119
+ 'table inventory. Omit it to refresh the inventory.',
129
120
  },
130
121
  text: {
131
122
  type: 'string',
@@ -155,10 +146,17 @@ const mysqlCatalogTool = {
155
146
  },
156
147
  doc: {
157
148
  type: 'string',
158
- description: 'Cataloged model.md path',
149
+ description: 'Document path relative to the repository root, e.g. apps/<app>/.../model.md',
150
+ },
151
+ repo: {
152
+ type: 'string',
153
+ description: 'GitHub repository holding the document, as owner/name. Take it from ' +
154
+ '`git remote get-url origin` in that repository; https and git@ URLs are ' +
155
+ 'accepted. describe uses it for a command that reads the document from ' +
156
+ 'any directory.',
159
157
  },
160
158
  },
161
- required: ['table', 'doc'],
159
+ required: ['table', 'doc', 'repo'],
162
160
  },
163
161
  },
164
162
  },
@@ -237,19 +235,19 @@ export default function createMcpServer() {
237
235
  filePath: identity.filePath,
238
236
  ttlHours: MYSQL_CATALOG_TTL_HOURS,
239
237
  appSchemas: APP_SCHEMAS,
240
- docsRepo: MYSQL_DOCS_REPO ?? null,
241
- docsRef: CODE_BRANCH ? `origin/${CODE_BRANCH}` : null,
242
238
  defaultSchema: typeof mysqlSettings.database === 'string' ? mysqlSettings.database : null,
243
239
  });
244
240
  setQueryDiagnosticsSource({
245
241
  indexFacts: (reference) => catalog.indexFacts(reference),
246
242
  });
247
- if (baseToolDescription.length > TOOL_DESCRIPTION_LIMIT) {
248
- console.error(`[warn] tool description is ${baseToolDescription.length} characters before the ` +
243
+ setCodeBranchSource(() => catalog.codeBranch());
244
+ const queryBaseDescription = baseToolDescription + codeRevisionDescription(catalog.codeBranch()) + appSchemaDescription;
245
+ if (queryBaseDescription.length > TOOL_DESCRIPTION_LIMIT) {
246
+ console.error(`[warn] tool description is ${queryBaseDescription.length} characters before the ` +
249
247
  `catalog tail; clients keep ${TOOL_DESCRIPTION_LIMIT} and silently drop the rest. ` +
250
248
  `Shorten MYSQL_APP_SCHEMAS descriptions, or the text in index.ts.`);
251
249
  }
252
- const mysqlQueryDescription = () => baseToolDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - baseToolDescription.length);
250
+ const mysqlQueryDescription = () => queryBaseDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - queryBaseDescription.length);
253
251
  const loadResourceTables = async () => {
254
252
  if (catalog.isEnabled()) {
255
253
  try {
@@ -329,6 +327,7 @@ export default function createMcpServer() {
329
327
  try {
330
328
  log('info', 'Handling ReadResourceRequest:', request.params.uri);
331
329
  if (request.params.uri === 'mysql://schemas') {
330
+ const codeBranch = catalog.codeBranch();
332
331
  return {
333
332
  contents: [
334
333
  {
@@ -336,7 +335,7 @@ export default function createMcpServer() {
336
335
  mimeType: 'application/json',
337
336
  text: JSON.stringify({
338
337
  profile: PROFILE_LABEL,
339
- ...(CODE_BRANCH ? { codeBranch: CODE_BRANCH } : {}),
338
+ ...(codeBranch ? { codeBranch } : {}),
340
339
  apps: APP_SCHEMAS,
341
340
  }, null, 2),
342
341
  },
@@ -432,25 +431,14 @@ export default function createMcpServer() {
432
431
  }
433
432
  text = await catalog.describe(args.table);
434
433
  }
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
434
  else if (action === 'link') {
448
435
  if (!Array.isArray(args.links) ||
449
436
  !args.links.every((link) => link &&
450
437
  typeof link === 'object' &&
451
438
  typeof link.table === 'string' &&
452
- typeof link.doc === 'string')) {
453
- throw new Error('mysql_catalog link requires "links" as [{table, doc}, ...].');
439
+ typeof link.doc === 'string' &&
440
+ typeof link.repo === 'string')) {
441
+ throw new Error('mysql_catalog link requires "links" as [{table, doc, repo}, ...].');
454
442
  }
455
443
  text = await catalog.link(args.links);
456
444
  }
@@ -484,6 +472,12 @@ export default function createMcpServer() {
484
472
  }
485
473
  text = await catalog.forget(args.target, args.scope);
486
474
  }
475
+ else if (action === 'branch') {
476
+ if (typeof args.branch !== 'string' || !args.branch.trim()) {
477
+ throw new Error('mysql_catalog branch requires "branch", e.g. develop.');
478
+ }
479
+ text = catalog.setCodeBranch(args.branch);
480
+ }
487
481
  else if (action === 'refresh') {
488
482
  if (args.target !== undefined && typeof args.target !== 'string') {
489
483
  throw new Error('mysql_catalog refresh takes "target" as a string.');
@@ -559,7 +553,14 @@ export default function createMcpServer() {
559
553
  title: 'MySQL Query',
560
554
  },
561
555
  },
562
- ...(catalog.isEnabled() ? [mysqlCatalogTool] : []),
556
+ ...(catalog.isEnabled()
557
+ ? [
558
+ {
559
+ ...mysqlCatalogTool,
560
+ description: mysqlCatalogTool.description + missingBranchToolInstruction(catalog.codeBranch()),
561
+ },
562
+ ]
563
+ : []),
563
564
  ],
564
565
  };
565
566
  log('info', 'ListToolsRequest response:', JSON.stringify(toolsResponse, null, 2));
@@ -0,0 +1,65 @@
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 missingBranchToolInstruction(branch) {
49
+ return branch
50
+ ? ''
51
+ : ' No code branch is recorded for this database yet (response banners show no "code:"). ' +
52
+ 'Before linking or reading documents, ask the user which branch matches this database ' +
53
+ 'and record it with branch.';
54
+ }
55
+ export function loadedBranch(value) {
56
+ if (typeof value !== 'string') {
57
+ return null;
58
+ }
59
+ try {
60
+ return normalizeBranchName(value);
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }