@ecubelabs/mysql-mcp 1.0.0-next.4 → 1.0.0-next.5

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
@@ -15,12 +15,11 @@ Tunnel은 서버가 직접 엽니다. 이미 쓰고 있는 `~/.ssh/config` alias
15
15
  온 답인지 밝힙니다.
16
16
  - **기본 읽기 전용, prod는 깨뜨릴 수 없음.** `prod`/`production`은 설정과
17
17
  무관하게 모든 쓰기를 거부합니다.
18
- - **Map은 탐색이 아니라 선언.** 각 profile이 어떤 schema가 어떤 application의
19
- 것인지 명시하므로, 모델은 이를 뒤져서 알아내는 대신 툴 설명에서 읽습니다.
20
- 데이터가 저장소마다 어느 git branch에 대응하는지는 사용자가 한 번 확인해 catalog에
21
- 기록합니다.
22
- - **로컬 schema catalog.** 선언된 schema의 table 목록을 저장해 두고 TTL이 지나면
23
- 다시 읽습니다. 실제 query에 등장한 table의 column·index·foreign key는 필요할 때만
18
+ - **DB에 물을 수 없는 사실은 사용자가 확인해 기록.** 어떤 schema가 어느 저장소의
19
+ 어느 앱 것인지(owner), 데이터가 저장소마다 어느 git branch에 대응하는지는 사용자가
20
+ 한 번 확인해 catalog에 기록합니다.
21
+ - **로컬 schema catalog.** 계정이 볼 수 있는 schema의 table 목록을 저장해 두고 TTL이
22
+ 지나면 다시 읽습니다. 실제 query에 등장한 table의 column·index·foreign key는 필요할 때만
24
23
  수집합니다.
25
24
  - **실행 상한과 타임아웃 보고서.** 읽기 쿼리는 10초·5000행에서 끊깁니다. 시간
26
25
  상한에 걸리면 실행 계획을 한 번 읽어, 플랜과 인덱스 목록과 선택지를 돌려줍니다.
@@ -67,7 +66,6 @@ ssh ecubelabs2-stage-db "echo ok"
67
66
  ### 2. MCP 클라이언트에 등록하기
68
67
 
69
68
  - `MYSQL_PROFILE`은 빼지 마세요. prod 쓰기 금지를 이 값이 정합니다.
70
- - `MYSQL_APP_SCHEMAS` 형식은 [아래 절](#mysql_app_schemas--어떤-schema가-어떤-앱의-것인가)에 있습니다.
71
69
  - 나머지 변수는 [환경 변수](#환경-변수) 절에 있습니다.
72
70
 
73
71
  #### Claude Code
@@ -76,12 +74,6 @@ ssh ecubelabs2-stage-db "echo ok"
76
74
  claude mcp add mysql-stage -s user \
77
75
  -e MYSQL_PROFILE=stage \
78
76
  -e MYSQL_SSH_CONFIG_HOST=ecubelabs2-stage-db \
79
- -e "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
80
- core-api:haulla-shared:Tenant-shared data, also owned by core-api;
81
- customer-tycoon-api:tycoon:Internal sales/CRM tool;
82
- hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
83
- call-analyzer:call:Call transcription and analysis output;
84
- simulator:simulator:HubSpot API simulator, stage only" \
85
77
  -e MYSQL_USER=<user> \
86
78
  -e MYSQL_PASS=<password> \
87
79
  -- npx -y @ecubelabs/mysql-mcp
@@ -89,11 +81,6 @@ simulator:simulator:HubSpot API simulator, stage only" \
89
81
  claude mcp add mysql-prod -s user \
90
82
  -e MYSQL_PROFILE=prod \
91
83
  -e MYSQL_SSH_CONFIG_HOST=ecubelabs2-prod-db \
92
- -e "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
93
- core-api:haulla-shared:Tenant-shared data, also owned by core-api;
94
- customer-tycoon-api:tycoon:Internal sales/CRM tool;
95
- hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
96
- call-analyzer:call:Call transcription and analysis output" \
97
84
  -e MYSQL_USER=<user> \
98
85
  -e MYSQL_PASS=<password> \
99
86
  -- npx -y @ecubelabs/mysql-mcp
@@ -105,12 +92,6 @@ call-analyzer:call:Call transcription and analysis output" \
105
92
  codex mcp add mysql-stage \
106
93
  --env MYSQL_PROFILE=stage \
107
94
  --env MYSQL_SSH_CONFIG_HOST=ecubelabs2-stage-db \
108
- --env "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
109
- core-api:haulla-shared:Tenant-shared data, also owned by core-api;
110
- customer-tycoon-api:tycoon:Internal sales/CRM tool;
111
- hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
112
- call-analyzer:call:Call transcription and analysis output;
113
- simulator:simulator:HubSpot API simulator, stage only" \
114
95
  --env MYSQL_USER=<user> \
115
96
  --env MYSQL_PASS=<password> \
116
97
  -- npx -y @ecubelabs/mysql-mcp
@@ -118,11 +99,6 @@ simulator:simulator:HubSpot API simulator, stage only" \
118
99
  codex mcp add mysql-prod \
119
100
  --env MYSQL_PROFILE=prod \
120
101
  --env MYSQL_SSH_CONFIG_HOST=ecubelabs2-prod-db \
121
- --env "MYSQL_APP_SCHEMAS=core-api:haulla:Main product service - the primary schema;
122
- core-api:haulla-shared:Tenant-shared data, also owned by core-api;
123
- customer-tycoon-api:tycoon:Internal sales/CRM tool;
124
- hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
125
- call-analyzer:call:Call transcription and analysis output" \
126
102
  --env MYSQL_USER=<user> \
127
103
  --env MYSQL_PASS=<password> \
128
104
  -- npx -y @ecubelabs/mysql-mcp
@@ -141,6 +117,8 @@ mysql-stage catalog의 table을 model.md 문서와 모두 연결해줘
141
117
  - Branch가 기록되지 않은 저장소를 연결하면 `link` 응답이 그 저장소의 branch를 묻게
142
118
  합니다. stage profile이면 `develop`, prod profile이면 `main`이 맞는지 확인합니다.
143
119
  답은 저장소별로 catalog에 기록되어 다음 세션에도 씁니다.
120
+ - Owner가 기록되지 않은 schema의 table을 연결하면 `link` 응답이 그 schema의 저장소와
121
+ 앱을 묻게 합니다. 답은 schema별로 catalog에 기록됩니다.
144
122
  - 그 뒤로 `describe`하면 문서를 읽는 명령 두 개가 옵니다.
145
123
  - `command`: 문서 저장소 안의 세션에서 `git show origin/<branch>:<경로>`
146
124
  - `remoteCommand`: 어느 디렉터리에서든 `gh api`. 저장소 밖의 세션은 `gh auth login`이
@@ -174,54 +152,36 @@ stage db에 Active Account가 몇 개 있는지 알려줘
174
152
 
175
153
  내버려 두면 모델은 "lead는 어느 schema에 있지?"라는 질문에 `SHOW DATABASES`와
176
154
  `information_schema` 쿼리 몇 번, 그리고 추측으로 답합니다. 하나하나가 왕복
177
- 비용이고, 추측은 가끔 틀립니다. 모델에게 없는 아래 두 가지 사실은 운영자가 이미
178
- 알고 있는 것이므로, profile이 이를 명시합니다.
155
+ 비용이고, 추측은 가끔 틀립니다. table이 어느 schema에 있는지는
156
+ [schema catalog](#schema-catalog)가 DB에서 모아 둡니다. DB에 물어볼 수 없는 아래 두
157
+ 사실은 사용자가 한 번 확인해 catalog에 기록합니다.
179
158
 
180
- ### `MYSQL_APP_SCHEMAS` — 어떤 schema가 어떤 앱의 것인가
159
+ ### Schema owner — 어떤 schema가 어느 저장소의 어느 앱 것인가
181
160
 
182
- 각 항목은 `app:schema`, 또는 `app:schema:설명` 형식입니다. 항목 구분자는 `;` 또는
183
- 개행입니다. 쉼표가 아니므로 설명을 문장처럼 쓸 수 있습니다:
184
-
185
- ```dotenv
186
- MYSQL_APP_SCHEMAS="core-api:haulla:Main product service - the primary schema;
187
- core-api:haulla-shared:Tenant-shared data, also owned by core-api;
188
- customer-tycoon-api:tycoon:Internal sales/CRM tool;
189
- hubspot-adapter:hubspot:HubSpot integration - mirrored CRM objects;
190
- call-analyzer:call:Call transcription and analysis output;
191
- simulator:simulator:HubSpot API simulator, stage only"
192
- ```
193
-
194
- - 한 앱이 여러 번 나올 수 있습니다. 테넌트별 schema와 공용 schema를 함께 갖는
195
- 서비스는 둘 다 적으세요. 뒤엣것만 남기면 모델에게 필요한 schema가 사라집니다.
196
- - 같은 `app:schema` 쌍이 반복될 때만 실수로 보고 첫 항목만 남깁니다. 대소문자는
197
- 가리지 않습니다.
198
- - 설명에는 `;`를 쓸 수 없습니다. 항목이 쪼개집니다.
199
- - 이 map은 쿼리 범위를 제한하지 않습니다. map에 없는 schema도 쿼리할 수 있습니다.
200
-
201
- 이 map은 `mysql_query` 툴 설명에 붙습니다. 모델이 첫 호출 전에 읽는 것이 툴
202
- 설명입니다:
203
-
204
- ```text
205
- APP -> SCHEMA (authoritative — use these directly; do not run SHOW DATABASES or search information_schema to find a schema):
206
- - core-api -> haulla — Main product service - the primary schema
207
- - core-api -> haulla-shared — Tenant-shared data, also owned by core-api
208
- - customer-tycoon-api -> tycoon — Internal sales/CRM tool
209
- - hubspot-adapter -> hubspot — HubSpot integration - mirrored CRM objects
210
- - call-analyzer -> call — Call transcription and analysis output
211
- - simulator -> simulator — HubSpot API simulator, stage only
212
- Qualify every table with its schema (schema.table). Any schema not listed here is either absent from this environment or not owned by an application.
213
- A schema name that is not a bare identifier must be backtick-quoted, e.g. SELECT ... FROM `haulla-shared`.some_table.
214
- ```
215
-
216
- **여기에는 migration을 넘겨서도 살아남는 사실만 적으세요.**
217
-
218
- - schema의 테이블 목록을 나열하면 `SHOW TABLES` 한 번을 아끼는 대신 조용히
219
- 낡습니다.
220
- - 이 map은 authoritative하다고 선언되므로, **틀린 목록은 없는 목록보다
221
- 나쁩니다.** 모델이 "그런 테이블은 없다"고 단정해 버립니다.
222
- - 어떤 앱이 어떤 schema를 쓰는지는 사람만 알고 데이터베이스에 물어볼 수 없는
223
- 사실입니다. 그 schema에 어떤 테이블이 있는지는 [schema catalog](#schema-catalog)가
224
- 데이터베이스에서 자동으로 갱신합니다.
161
+ - 사용자가 확인한 값을
162
+ `mysql_catalog {action:"owner", target:"haulla", repo:"Ecube-Labs/haulla", app:"core-api"}`로
163
+ catalog에 기록합니다. 서버는 문서 경로, 이름, 앱 설정으로 추측하지 않습니다
164
+ ([이유](#schema-owner를-추론하지-않는-이유)).
165
+ - 모델이 묻는 자리는 `link` 응답 하나입니다. 연결한 table의 schema에 owner가 없으면
166
+ `guidance`가 묻게 합니다. 이미 기록된 schema는 묻지 않습니다.
167
+
168
+ ```text
169
+ [카탈로그] haulla schema를 가진 저장소와 앱이 기록되지 않았습니다. 방금 연결한 문서는 Ecube-Labs/haulla의 apps/core-api/src/services/accounts/domain/model.md입니다.
170
+ haulla schema가 어느 저장소의 어느 앱 것인지 사용자에게 물으세요.
171
+ 확인받은 값을 mysql_catalog {action:"owner", target:"haulla", repo:"<owner/name>", app:"<앱 이름>"} 로 기록하세요.
172
+ ```
173
+
174
+ - 문서 연결 없이 바로 기록하려면 모델에게 알려 주세요:
175
+
176
+ ```text
177
+ mysql-stage의 haulla schema는 Ecube-Labs/haulla의 core-api 것이야. owner로 기록해줘
178
+ ```
179
+
180
+ - 기록된 owner는 `map`의 schema마다, `search` 결과의 table마다, `describe`,
181
+ `mysql://schemas`에 `{repo, app}`으로 나옵니다. 기록 전에는 그 키가 없습니다.
182
+ - Query 응답, banner, 툴 설명은 owner를 싣지도 묻지도 않습니다.
183
+ - 예전 버전이 env에서 옮겨 적은 앱 이름은 저장소가 없어 버립니다. 다음 `link` 때 다시
184
+ 묻습니다.
225
185
 
226
186
  ### 코드 branch — 데이터가 어느 branch에 대응하는가
227
187
 
@@ -244,8 +204,8 @@ migration이 빠진 것처럼 보이기 때문입니다.
244
204
  - `mysql_query` 툴 설명은 서버 시작 때 한 번 만들어집니다. 세션 중에 바꾸면 banner와
245
205
  `branch` 응답이 새 값을 알립니다. `mysql_catalog` 툴 설명은 툴 목록을 받을 때마다
246
206
  다시 만듭니다.
247
- - Catalog가 꺼진 profile(`MYSQL_CATALOG_ENABLED=false` 또는 `MYSQL_APP_SCHEMAS` 없음)은
248
- branch를 기록할 곳이 없어 표시하지 않습니다.
207
+ - Catalog가 꺼진 profile(`MYSQL_CATALOG_ENABLED=false`)은 branch를 기록할 곳이 없어
208
+ 표시하지 않습니다.
249
209
  - 예전 버전이 DB 하나에 기록한 branch(`codeBranch`)는 어느 저장소의 것인지 몰라
250
210
  버립니다. 필요한 곳에서 다시 묻습니다.
251
211
  - Branch는 실제로 쓰이는 곳에서만 묻습니다. profile별 제안은 질문 형태이고 저장되지
@@ -266,13 +226,15 @@ migration이 빠진 것처럼 보이기 때문입니다.
266
226
 
267
227
  ## Schema catalog
268
228
 
269
- 이미 알아낸 구조를 다시 찾지 않도록, 서버는 `MYSQL_APP_SCHEMAS`에 선언된 schema만
270
- 로컬 JSON catalog에 기록합니다.
229
+ 이미 알아낸 구조를 다시 찾지 않도록, 서버는 계정이 볼 수 있는 schema를 모두 로컬 JSON
230
+ catalog에 기록합니다. `information_schema`, `mysql`, `performance_schema`, `sys`만
231
+ 뺍니다.
271
232
 
272
233
  ### 수집 시점
273
234
 
274
- - **table 이름·comment·예상 row 수**는 시작할 때 갱신합니다. catalog가 비어 있거나
275
- `MYSQL_CATALOG_TTL_HOURS`(기본 24시간)가 지났을 때만입니다.
235
+ - **schema 목록과 table 이름·comment·예상 row 수**는 시작할 때 갱신합니다. catalog가
236
+ 비어 있거나 `MYSQL_CATALOG_TTL_HOURS`(기본 24시간)가 지났을 때만입니다. DB에서
237
+ 사라진 schema는 그 owner와 함께 지웁니다.
276
238
  - **column, primary key, index, foreign key**는 table이 실제 SQL에 처음 등장한 뒤
277
239
  비동기로 수집합니다. 이 작업은 `mysql_query`의 실행 시간에 포함되지 않습니다.
278
240
  - Query가 없는 column이나 table을 참조해 실패하면 서버가 그 항목을 즉시 다시
@@ -289,7 +251,7 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
289
251
 
290
252
  **구조 읽기**
291
253
 
292
- - `map`: application, schema, 자주 쓰는 table의 개요를 봅니다.
254
+ - `map`: schema와 그 owner, 자주 쓰는 table의 개요를 봅니다.
293
255
  - `search`: table 이름·comment, 수집된 column, memo, alias를 keyword로 찾습니다.
294
256
  - `describe`: 한 table의 column, key, index, foreign key를 봅니다. 상세 정보가
295
257
  아직 없거나 TTL이 지났다면 이 호출이 갱신을 기다립니다.
@@ -315,6 +277,13 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
315
277
  `git check-ref-format --branch`에 준하는 형식만 받습니다.
316
278
  공백·제어문자·`~^:?*[\`·`..`·`@{`는 거절하고, 100자까지입니다.
317
279
  - 둘 중 하나라도 틀리면 아무것도 기록하지 않습니다.
280
+ - `owner`: 사용자가 확인한 schema의 저장소와 앱을 기록합니다. `target`(schema 이름),
281
+ `repo`, `app`이 모두 필요합니다. 처음 기록과 변경을 함께 받고, 응답이 무엇을
282
+ 기록했는지 또는 `이전 → 새` 값을 알립니다.
283
+ - `target`: 수집된 schema만 받습니다. 대소문자는 가리지 않고 DB의 철자로 저장합니다.
284
+ - `repo`: `link`와 같은 형태를 받아 `owner/name`으로 저장합니다.
285
+ - `app`: 그 저장소 안의 앱 이름. 빈 값·공백·제어문자는 거절하고, 100자까지입니다.
286
+ - 셋 중 하나라도 틀리면 아무것도 기록하지 않습니다.
318
287
 
319
288
  **기록 관리**
320
289
 
@@ -327,10 +296,10 @@ column·index·foreign key가 **추가**되면 오류가 나지 않으므로, ca
327
296
  - `refresh`: 지정한 범위를 강제로 다시 수집합니다. `target`을 생략하면 inventory를
328
297
  갱신합니다.
329
298
 
330
- | `target` | 다시 수집하는 것 |
331
- | ------------------ | ----------------------------------- |
332
- | `schema.table` | 그 table의 column·index·foreign key |
333
- | 선언된 schema 이름 | table inventory |
299
+ | `target` | 다시 수집하는 것 |
300
+ | -------------- | ----------------------------------- |
301
+ | `schema.table` | 그 table의 column·index·foreign key |
302
+ | schema 이름 | schema 목록과 table inventory |
334
303
 
335
304
  ### 문서 연결
336
305
 
@@ -397,21 +366,20 @@ Catalog에는 schema metadata와 사용 기록만 들어갑니다.
397
366
 
398
367
  ### Catalog를 끄면
399
368
 
400
- `MYSQL_CATALOG_ENABLED=false`로 끄거나 `MYSQL_APP_SCHEMAS`가 비어 있으면
401
- `mysql_catalog` 툴이 사라지고, resource는 `information_schema`를 직접 읽습니다.
402
- Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼지고 stderr에 이유를
403
- 남깁니다.
369
+ `MYSQL_CATALOG_ENABLED=false`로 끄거나 디스크에 쓸 수 없으면 `mysql_catalog` 툴과
370
+ `mysql://schemas` resource가 사라지고, 나머지 resource는 `information_schema`를 직접
371
+ 읽습니다. Owner와 code branch는 기록할 곳이 없어 표시하지 않습니다.
404
372
 
405
373
  ## Resource
406
374
 
407
375
  툴만 읽는 클라이언트라면 이 절은 건너뛰어도 됩니다. Resource를 읽는 클라이언트를
408
376
  위해 세 가지를 제공합니다.
409
377
 
410
- | URI | 내용 |
411
- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
412
- | `mysql://tables` | table 목록. 이름, schema, comment, 예상 row 수. catalog가 켜져 있으면 선언된 schema의 저장된 inventory로 답하고, 꺼져 있거나 아직 비어 있으면 `information_schema`에서 읽을 수 있는 모든 table을 읽습니다 — 이때는 크기와 생성·수정 시각도 함께 옵니다. |
413
- | `mysql://tables/<schema>/<table>` | 한 table의 구조. catalog가 켜져 있으면 `mysql_catalog describe`와 같은 내용이고, 실패하면 `information_schema`의 column 목록으로 물러납니다. catalog가 꺼져 있으면 `information_schema`의 column 목록을 바로 돌려줍니다. |
414
- | `mysql://schemas` | 선언된 app -> schema map. `profile`, `apps`, 그리고 branch가 기록돼 있으면 저장소별 `codeBranches`를 담은 JSON입니다. `MYSQL_APP_SCHEMAS`가 비어 있으면 목록에 오르지 않습니다. |
378
+ | URI | 내용 |
379
+ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
380
+ | `mysql://tables` | table 목록. 이름, schema, comment, 예상 row 수. catalog가 켜져 있으면 저장된 inventory로 답하고, 꺼져 있거나 아직 비어 있으면 `information_schema`에서 읽을 수 있는 모든 table을 읽습니다 — 이때는 크기와 생성·수정 시각도 함께 옵니다. |
381
+ | `mysql://tables/<schema>/<table>` | 한 table의 구조. catalog가 켜져 있으면 `mysql_catalog describe`와 같은 내용이고, 실패하면 `information_schema`의 column 목록으로 물러납니다. catalog가 꺼져 있으면 `information_schema`의 column 목록을 바로 돌려줍니다. |
382
+ | `mysql://schemas` | 사용자가 기록한 schema owner. `profile`, `schemas`(owner가 기록된 schema만, schema → `{repo, app}`), 그리고 branch가 기록돼 있으면 저장소별 `codeBranches`를 담은 JSON입니다. catalog가 꺼져 있으면 목록에 오르지 않습니다. |
415
383
 
416
384
  ## 환경 변수
417
385
 
@@ -420,13 +388,12 @@ Catalog는 선언된 schema만 훑으므로, 선언이 없으면 스스로 꺼
420
388
 
421
389
  ### Profile
422
390
 
423
- | 변수 | 기본값 | 의미 |
424
- | ------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
425
- | `MYSQL_PROFILE` | _(미설정)_ | 환경 label. `prod`/`production`은 읽기 전용을 강제합니다. |
426
- | `MYSQL_APP_SCHEMAS` | _(미설정)_ | `;`로 구분된 `app:schema[:설명]` 항목. 툴 설명과 `mysql://schemas`에 노출됩니다. |
427
- | `MYSQL_CATALOG_ENABLED` | `true` | 로컬 schema catalog를 켭니다. `false`이거나 `MYSQL_APP_SCHEMAS`가 비어 있으면 catalog가 꺼지고 `mysql_catalog` 툴도 제공되지 않습니다. |
428
- | `MYSQL_CATALOG_PATH` | `~/.cache/mysql-mcp/catalog` | profile·대상·user별 JSON 파일을 둘 directory입니다. |
429
- | `MYSQL_CATALOG_TTL_HOURS` | `24` | DB metadata를 stale로 보는 시간입니다. |
391
+ | 변수 | 기본값 | 의미 |
392
+ | ------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
393
+ | `MYSQL_PROFILE` | _(미설정)_ | 환경 label. `prod`/`production`은 읽기 전용을 강제합니다. |
394
+ | `MYSQL_CATALOG_ENABLED` | `true` | 로컬 schema catalog를 켭니다. `false`이면 `mysql_catalog` 툴과 `mysql://schemas`가 제공되지 않습니다. |
395
+ | `MYSQL_CATALOG_PATH` | `~/.cache/mysql-mcp/catalog` | profile·대상·user별 JSON 파일을 둘 directory입니다. |
396
+ | `MYSQL_CATALOG_TTL_HOURS` | `24` | DB metadata를 stale로 보는 시간입니다. |
430
397
 
431
398
  ### SSH tunnel
432
399
 
@@ -555,6 +522,28 @@ redaction이 아니라 그 앞단에 있습니다 — read-only 강제, profile
555
522
  tunnel, 그리고 애초에 어떤 계정으로 접속하는지입니다. Column 이름 목록을 손으로
556
523
  관리해서 얻는 masking 한 겹은 그 위에 얹을 값이 없었습니다.
557
524
 
525
+ ## Schema owner를 추론하지 않는 이유
526
+
527
+ Owner는 사용자가 확인한 값만 기록합니다. 서버는 문서 경로, 이름 일치, 앱 설정의
528
+ `DB_NAME`, git 어느 것으로도 owner를 정하지 않습니다.
529
+
530
+ - 코드에는 schema 이름이 없습니다. haulla의 엔티티는 `@Entity()`만 쓰고, schema
531
+ 이름은 env `DB_NAME`에서 옵니다.
532
+ - 저장소에 남은 단서는 로컬 값이라 환경과 다릅니다.
533
+ - core-api 공용 데이터: 로컬 `docker-compose.yml`은 `haulla`, stage는 `haulla-shared`
534
+ - hubspot-adapter: `.env.example`은 `hubspot-adapter`, stage는 `hubspot`
535
+ - 틀린 schema를 골라도 쿼리는 성공합니다. stage에는 여러 schema에 걸친 같은 이름
536
+ table이 12개 있고(`account`, `user`, `contract`, `deal`, `notification` 등), 숫자도
537
+ 그럴듯합니다.
538
+
539
+ 예전에는 app → schema map을 env로 받아 툴 설명에 실었습니다. 이 방식은 버렸습니다.
540
+
541
+ - 사용자마다 같은 map을 MCP 설정에 적어야 했습니다.
542
+ - Map에는 table 목록이 없어서, map이 있어도 모델은 table 위치를 찾으려고
543
+ `information_schema`를 조회했습니다.
544
+ - 그래서 owner는 같은 이름 table이 함께 드러나는 catalog 응답(`map`·`search`·
545
+ `describe`)에 둡니다. 묻는 자리는 모델이 table과 코드를 맞대 본 `link` 응답입니다.
546
+
558
547
  ## Tunnel이 동작하는 방식
559
548
 
560
549
  Forwarding은 `ssh -N -L`을 spawn 하는 대신 `ssh2`를 통해 프로세스 내부에서
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, 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';
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, 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 { codeBranchToolInstruction, codeRevisionDescription } from './src/catalog/branch.js';
11
11
  import { catalogIdentity, SchemaCatalog } from './src/catalog/index.js';
12
+ import { renderSchemasResource } from './src/catalog/render.js';
12
13
  import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
13
14
  import { describeTunnel, ensureTunnel, resolveTunnelConfig, stopTunnel } from './src/ssh/tunnel.js';
14
15
  log('info', `Starting MySQL MCP server v${PACKAGE_VERSION}...`);
@@ -43,25 +44,9 @@ baseToolDescription +=
43
44
  `${MAX_RESPONSE_ROWS.toLocaleString('en-US')} rows. Aggregate in SQL rather than pulling rows to count them. ` +
44
45
  `USE and SET are rejected; write schema.table instead of USE. ` +
45
46
  `Executable comments (/*! ... */) and MAX_EXECUTION_TIME or SET_VAR hints are rejected; use timeout_seconds instead.`;
46
- let appSchemaDescription = '';
47
- if (APP_SCHEMAS.length > 0) {
48
- appSchemaDescription +=
49
- '\n\nAPP -> SCHEMA (authoritative — use these directly; do not run SHOW DATABASES ' +
50
- 'or search information_schema to find a schema):';
51
- for (const entry of APP_SCHEMAS) {
52
- appSchemaDescription +=
53
- `\n - ${entry.app} -> ${entry.schema}` + (entry.description ? ` — ${entry.description}` : '');
54
- }
55
- appSchemaDescription +=
56
- '\nQualify every table with its schema (schema.table). Any schema not listed here is ' +
57
- 'either absent from this environment or not owned by an application.';
58
- const needsQuoting = APP_SCHEMAS.find((entry) => !/^[A-Za-z0-9_$]+$/.test(entry.schema));
59
- if (needsQuoting) {
60
- appSchemaDescription +=
61
- `\nA schema name that is not a bare identifier must be backtick-quoted, ` +
62
- `e.g. SELECT ... FROM \`${needsQuoting.schema}\`.some_table.`;
63
- }
64
- }
47
+ baseToolDescription +=
48
+ '\n\nQualify every table with its schema (schema.table). ' +
49
+ 'A schema name that is not a bare identifier must be backtick-quoted, e.g. SELECT ... FROM `my-schema`.some_table.';
65
50
  const isReadOnly = writes.length === 0;
66
51
  const mysqlCatalogTool = {
67
52
  name: 'mysql_catalog',
@@ -73,6 +58,7 @@ const mysqlCatalogTool = {
73
58
  'in a session inside the document repository; never unlink from a session outside it. ' +
74
59
  'Use branch to record which branch of a GitHub repository matches this database, once ' +
75
60
  'the user confirmed it. ' +
61
+ 'Use owner to record which repository and app own a schema, once the user confirmed it. ' +
76
62
  'Use note to save a table memo or alias, and forget to clear one catalog scope. ' +
77
63
  'Use refresh when cached metadata contradicts what a query actually returned, ' +
78
64
  'or right after a migration: added columns and indexes raise no error, so ' +
@@ -82,7 +68,7 @@ const mysqlCatalogTool = {
82
68
  properties: {
83
69
  action: {
84
70
  type: 'string',
85
- enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'note', 'forget', 'refresh'],
71
+ enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'owner', 'note', 'forget', 'refresh'],
86
72
  description: 'Catalog operation to perform',
87
73
  },
88
74
  q: {
@@ -102,9 +88,15 @@ const mysqlCatalogTool = {
102
88
  },
103
89
  repo: {
104
90
  type: 'string',
105
- description: 'GitHub repository for branch, as owner/name. Take it from `git remote get-url origin`; ' +
91
+ description: 'GitHub repository for branch or owner, as owner/name. Take it from `git remote get-url origin`; ' +
106
92
  'https and git@ URLs are accepted.',
107
93
  },
94
+ app: {
95
+ type: 'string',
96
+ maxLength: 100,
97
+ description: 'App inside repo that owns the schema given as target, e.g. core-api. ' +
98
+ 'Pass it only after the user confirmed it.',
99
+ },
108
100
  branch: {
109
101
  type: 'string',
110
102
  maxLength: 100,
@@ -114,8 +106,8 @@ const mysqlCatalogTool = {
114
106
  },
115
107
  target: {
116
108
  type: 'string',
117
- description: 'Qualified schema.table for note or forget. For refresh: "schema.table" for one table\'s ' +
118
- 'columns, indexes and foreign keys; a declared schema name for the ' +
109
+ description: 'Qualified schema.table for note or forget. Schema name for owner. For refresh: ' +
110
+ '"schema.table" for one table\'s columns, indexes and foreign keys; a schema name for the ' +
119
111
  'table inventory. Omit it to refresh the inventory.',
120
112
  },
121
113
  text: {
@@ -223,29 +215,23 @@ export default function createMcpServer() {
223
215
  user: String(mysqlSettings.user ?? ''),
224
216
  customPath: MYSQL_CATALOG_PATH,
225
217
  });
226
- const noDeclaredSchemas = APP_SCHEMAS.length === 0;
227
- if (noDeclaredSchemas && MYSQL_CATALOG_ENABLED) {
228
- console.error('[catalog] disabled: MYSQL_APP_SCHEMAS declares no schema, so there is ' +
229
- 'nothing to catalog. Declare the app -> schema map to enable it.');
230
- }
231
218
  const catalog = new SchemaCatalog({
232
- enabled: MYSQL_CATALOG_ENABLED && !noDeclaredSchemas,
219
+ enabled: MYSQL_CATALOG_ENABLED,
233
220
  profile: MYSQL_PROFILE || 'default',
234
221
  fingerprint: identity.fingerprint,
235
222
  filePath: identity.filePath,
236
223
  ttlHours: MYSQL_CATALOG_TTL_HOURS,
237
- appSchemas: APP_SCHEMAS,
238
224
  defaultSchema: typeof mysqlSettings.database === 'string' ? mysqlSettings.database : null,
239
225
  });
240
226
  setQueryDiagnosticsSource({
241
227
  indexFacts: (reference) => catalog.indexFacts(reference),
242
228
  });
243
229
  setCodeBranchSource(() => catalog.codeBranchSummary());
244
- const queryBaseDescription = baseToolDescription + codeRevisionDescription(catalog.codeBranches()) + appSchemaDescription;
230
+ const queryBaseDescription = baseToolDescription + codeRevisionDescription(catalog.codeBranches());
245
231
  if (queryBaseDescription.length > TOOL_DESCRIPTION_LIMIT) {
246
232
  console.error(`[warn] tool description is ${queryBaseDescription.length} characters before the ` +
247
233
  `catalog tail; clients keep ${TOOL_DESCRIPTION_LIMIT} and silently drop the rest. ` +
248
- `Shorten MYSQL_APP_SCHEMAS descriptions, or the text in index.ts.`);
234
+ `Record fewer code branches, or shorten the text in index.ts.`);
249
235
  }
250
236
  const mysqlQueryDescription = () => queryBaseDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - queryBaseDescription.length);
251
237
  const loadResourceTables = async () => {
@@ -307,12 +293,12 @@ export default function createMcpServer() {
307
293
  description: 'List of all MySQL tables',
308
294
  mimeType: 'application/json',
309
295
  });
310
- if (APP_SCHEMAS.length > 0) {
296
+ if (catalog.isEnabled()) {
311
297
  resources.push({
312
298
  uri: 'mysql://schemas',
313
- name: 'App schemas',
314
- title: 'Application to schema map',
315
- description: `Which schema each application owns in ${PROFILE_LABEL}`,
299
+ name: 'Schema owners',
300
+ title: 'Schema to repository and app map',
301
+ description: `Which repository and app own each schema in ${PROFILE_LABEL}, as confirmed by users`,
316
302
  mimeType: 'application/json',
317
303
  });
318
304
  }
@@ -327,17 +313,12 @@ export default function createMcpServer() {
327
313
  try {
328
314
  log('info', 'Handling ReadResourceRequest:', request.params.uri);
329
315
  if (request.params.uri === 'mysql://schemas') {
330
- const codeBranches = catalog.codeBranches();
331
316
  return {
332
317
  contents: [
333
318
  {
334
319
  uri: request.params.uri,
335
320
  mimeType: 'application/json',
336
- text: JSON.stringify({
337
- profile: PROFILE_LABEL,
338
- ...(Object.keys(codeBranches).length > 0 ? { codeBranches } : {}),
339
- apps: APP_SCHEMAS,
340
- }, null, 2),
321
+ text: renderSchemasResource(PROFILE_LABEL, catalog.codeBranches(), catalog.schemaOwners()),
341
322
  },
342
323
  ],
343
324
  };
@@ -481,6 +462,17 @@ export default function createMcpServer() {
481
462
  }
482
463
  text = catalog.setCodeBranch(args.repo, args.branch);
483
464
  }
465
+ else if (action === 'owner') {
466
+ if (typeof args.target !== 'string' ||
467
+ !args.target.trim() ||
468
+ typeof args.repo !== 'string' ||
469
+ !args.repo.trim() ||
470
+ typeof args.app !== 'string' ||
471
+ !args.app.trim()) {
472
+ throw new Error('mysql_catalog owner requires "target", "repo" and "app", e.g. {target: "haulla", repo: "owner/name", app: "core-api"}.');
473
+ }
474
+ text = await catalog.setSchemaOwner(args.target, args.repo, args.app);
475
+ }
484
476
  else if (action === 'refresh') {
485
477
  if (args.target !== undefined && typeof args.target !== 'string') {
486
478
  throw new Error('mysql_catalog refresh takes "target" as a string.');
@@ -1,5 +1,5 @@
1
1
  import { executeQuery } from '../db/index.js';
2
- import { emptyTable, normalizeName } from './types.js';
2
+ import { emptyTable, normalizeName, SYSTEM_SCHEMAS } from './types.js';
3
3
  function chainAfter(pending, run) {
4
4
  if (!pending) {
5
5
  return run();
@@ -26,13 +26,11 @@ export class CatalogCollector {
26
26
  this.options = options;
27
27
  }
28
28
  inventoryNeedsRefresh() {
29
- return this.options.schemas.some((name) => {
30
- const state = this.store.schemaState(name);
31
- return !state || isExpired(state.scannedAt, this.options.ttlHours);
32
- });
29
+ const scannedAt = this.store.schemaScanTimes();
30
+ return scannedAt.length === 0 || scannedAt.some((value) => isExpired(value, this.options.ttlHours));
33
31
  }
34
32
  async collectInventory(force = false) {
35
- if (!this.store.isEnabled() || this.options.schemas.length === 0) {
33
+ if (!this.store.isEnabled()) {
36
34
  return;
37
35
  }
38
36
  if (!force && !this.inventoryNeedsRefresh()) {
@@ -51,42 +49,41 @@ export class CatalogCollector {
51
49
  return promise;
52
50
  }
53
51
  async runInventory() {
54
- const placeholders = this.options.schemas.map(() => '?').join(', ');
52
+ const placeholders = SYSTEM_SCHEMAS.map(() => '?').join(', ');
55
53
  const rows = await executeQuery(`SELECT
56
- table_schema AS \`table_schema\`,
57
- table_name AS \`table_name\`,
58
- table_comment AS \`table_comment\`,
59
- table_rows AS \`table_rows\`
60
- FROM information_schema.tables
61
- WHERE table_schema IN (${placeholders})
62
- ORDER BY table_schema, table_name`, [...this.options.schemas]);
63
- const declaredBySchema = new Map(this.options.schemas.map((name) => [normalizeName(name), name]));
54
+ s.schema_name AS \`table_schema\`,
55
+ t.table_name AS \`table_name\`,
56
+ t.table_comment AS \`table_comment\`,
57
+ t.table_rows AS \`table_rows\`
58
+ FROM information_schema.schemata s
59
+ LEFT JOIN information_schema.tables t ON t.table_schema = s.schema_name
60
+ WHERE s.schema_name NOT IN (${placeholders})
61
+ ORDER BY s.schema_name, t.table_name`, [...SYSTEM_SCHEMAS]);
64
62
  const rowsBySchema = new Map();
65
63
  for (const row of rows) {
66
- const declared = declaredBySchema.get(normalizeName(String(row.table_schema)));
67
- if (!declared) {
68
- continue;
69
- }
70
- const bucket = rowsBySchema.get(declared);
71
- if (bucket) {
64
+ const schemaName = String(row.table_schema);
65
+ const bucket = rowsBySchema.get(schemaName) ?? [];
66
+ if (row.table_name !== null && row.table_name !== undefined) {
72
67
  bucket.push(row);
73
68
  }
74
- else {
75
- rowsBySchema.set(declared, [row]);
76
- }
69
+ rowsBySchema.set(schemaName, bucket);
77
70
  }
78
71
  const now = new Date().toISOString();
72
+ let tableCount = 0;
79
73
  this.store.update((catalog) => {
80
- for (const schemaName of this.options.schemas) {
81
- const schema = catalog.schemas[schemaName];
82
- if (!schema) {
83
- continue;
84
- }
85
- const nextTables = Object.fromEntries((rowsBySchema.get(schemaName) ?? []).map((row) => {
86
- const existing = schema.tables[row.table_name] ?? emptyTable();
74
+ const previousByName = new Map(Object.keys(catalog.schemas).map((name) => [normalizeName(name), name]));
75
+ const schemas = {};
76
+ for (const [schemaName, schemaRows] of rowsBySchema) {
77
+ const previousName = catalog.schemas[schemaName]
78
+ ? schemaName
79
+ : previousByName.get(normalizeName(schemaName));
80
+ const previous = previousName ? catalog.schemas[previousName] : undefined;
81
+ const tables = Object.fromEntries(schemaRows.map((row) => {
82
+ const tableName = row.table_name;
83
+ const existing = previous?.tables[tableName] ?? emptyTable();
87
84
  const numericRows = Number(row.table_rows);
88
85
  return [
89
- row.table_name,
86
+ tableName,
90
87
  {
91
88
  ...existing,
92
89
  comment: row.table_comment ?? '',
@@ -94,16 +91,12 @@ export class CatalogCollector {
94
91
  },
95
92
  ];
96
93
  }));
97
- schema.tables = nextTables;
98
- schema.scannedAt = now;
94
+ tableCount += schemaRows.length;
95
+ schemas[schemaName] = { ...previous, scannedAt: now, tables };
99
96
  }
97
+ catalog.schemas = schemas;
100
98
  });
101
- for (const schemaName of this.options.schemas) {
102
- if (!rowsBySchema.has(schemaName)) {
103
- console.error(`[catalog] declared schema "${schemaName}" returned no tables; check MYSQL_APP_SCHEMAS and the account's grants.`);
104
- }
105
- }
106
- console.error(`[catalog] inventory scan complete: ${this.options.schemas.length} schemas, ${rows.length} tables`);
99
+ console.error(`[catalog] inventory scan complete: ${rowsBySchema.size} schemas, ${tableCount} tables`);
107
100
  }
108
101
  detailNeedsRefresh(schemaName, tableName) {
109
102
  const meta = this.store.tableMeta(schemaName, tableName);
@@ -42,7 +42,7 @@ export class CatalogDocuments {
42
42
  constructor(store) {
43
43
  this.store = store;
44
44
  }
45
- link(links, guidanceFor = () => null) {
45
+ link(links, guidanceFor = () => []) {
46
46
  const resolved = links.map((link) => ({
47
47
  ...link,
48
48
  doc: normalizeDocumentPath(link.doc),
@@ -68,9 +68,7 @@ export class CatalogDocuments {
68
68
  }
69
69
  }
70
70
  });
71
- const guidance = [...new Set(resolved.map((link) => link.repo))]
72
- .map(guidanceFor)
73
- .filter((entry) => entry !== null);
71
+ const guidance = guidanceFor(resolved);
74
72
  return JSON.stringify({
75
73
  linked: resolved.map((link) => ({
76
74
  table: `${link.schema}.${link.table}`,
@@ -4,9 +4,10 @@ import * as path from 'path';
4
4
  import { CatalogCollector } from './collect.js';
5
5
  import { CatalogDocuments, normalizeGithubRepo } from './docs.js';
6
6
  import { formatCodeBranches, normalizeBranchName } from './branch.js';
7
- import { missingBranchNotice, renderDescribe, renderMap, renderToolDescriptionSuffix, searchCatalog, } from './render.js';
7
+ import { normalizeSchemaOwner } from './owner.js';
8
+ import { missingBranchNotice, missingOwnerNotice, renderDescribe, renderMap, renderToolDescriptionSuffix, searchCatalog, } from './render.js';
8
9
  import { CatalogStore } from './store.js';
9
- import { emptyUsage, normalizeName, pruneJoins } 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;
@@ -56,7 +57,6 @@ export class SchemaCatalog {
56
57
  this.options = options;
57
58
  this.store = new CatalogStore(options);
58
59
  this.collector = new CatalogCollector(this.store, {
59
- schemas: options.appSchemas.map((entry) => entry.schema),
60
60
  ttlHours: options.ttlHours,
61
61
  });
62
62
  this.documents = new CatalogDocuments(this.store);
@@ -97,6 +97,55 @@ export class SchemaCatalog {
97
97
  note: 'banner와 describe는 바로 이 값을 씁니다. mysql_query 툴 설명의 CODE REVISION은 서버를 다시 띄우면 바뀝니다.',
98
98
  }, null, 2);
99
99
  }
100
+ schemaOwners() {
101
+ return this.isEnabled() ? this.store.schemaOwners() : {};
102
+ }
103
+ async setSchemaOwner(target, repoInput, appInput) {
104
+ if (!this.isEnabled()) {
105
+ throw new Error('The schema catalog is disabled.');
106
+ }
107
+ const requested = target.replace(/`/g, '').trim();
108
+ const owner = normalizeSchemaOwner(repoInput, appInput);
109
+ let schema = this.store.schemaName(requested);
110
+ if (!schema) {
111
+ await this.collector.collectInventory(false);
112
+ schema = this.store.schemaName(requested);
113
+ }
114
+ if (!schema) {
115
+ throw new Error(`Unknown schema "${requested}". owner takes a schema name from mysql_catalog {action:"map"}, not schema.table.`);
116
+ }
117
+ const name = schema;
118
+ const previous = this.store.schemaOwners()[name] ?? null;
119
+ const label = `${owner.repo}의 ${owner.app}`;
120
+ if (previous && previous.repo === owner.repo && previous.app === owner.app) {
121
+ return JSON.stringify({ schema: name, ...owner, changed: false, status: `${name} schema의 owner는 이미 ${label}입니다.` }, null, 2);
122
+ }
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;
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
+ }
139
+ return JSON.stringify({
140
+ schema: name,
141
+ ...owner,
142
+ ...(previous ? { previous } : {}),
143
+ changed: true,
144
+ status: previous
145
+ ? `${name} schema의 owner를 바꿨습니다: ${previous.repo}의 ${previous.app} → ${label}`
146
+ : `${name} schema의 owner를 ${label}(으)로 기록했습니다. 다음 세션에도 이어 씁니다.`,
147
+ }, null, 2);
148
+ }
100
149
  startInventory() {
101
150
  if (!this.isEnabled() || this.closing) {
102
151
  return;
@@ -147,11 +196,10 @@ export class SchemaCatalog {
147
196
  }
148
197
  catalogKeyForReference(reference) {
149
198
  const requestedSchema = reference.schema ?? this.options.defaultSchema;
150
- if (!requestedSchema) {
199
+ if (!requestedSchema || SYSTEM_SCHEMAS.some((name) => sameName(name, requestedSchema))) {
151
200
  return null;
152
201
  }
153
- const declared = this.options.appSchemas.find((entry) => sameName(entry.schema, requestedSchema));
154
- return declared ? `${declared.schema}.${reference.table}`.toLowerCase() : null;
202
+ return `${requestedSchema}.${reference.table}`.toLowerCase();
155
203
  }
156
204
  resolveReferences(references) {
157
205
  return references
@@ -165,7 +213,7 @@ export class SchemaCatalog {
165
213
  resolved = this.resolveTable(input);
166
214
  }
167
215
  if (!resolved) {
168
- throw new Error(`Unknown or ambiguous table "${input}". Use a declared schema.table name.`);
216
+ throw new Error(`Unknown or ambiguous table "${input}". Use a qualified schema.table name.`);
169
217
  }
170
218
  return resolved;
171
219
  }
@@ -198,7 +246,7 @@ export class SchemaCatalog {
198
246
  if (!entry) {
199
247
  throw new Error(`Table disappeared during refresh: ${input}`);
200
248
  }
201
- return renderDescribe(`${resolved.schema}.${resolved.table}`, entry, this.store.codeBranches(), this.store.readJoins(resolved.schema, resolved.table), this.options.profile);
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);
202
250
  }
203
251
  async refresh(target) {
204
252
  if (!this.isEnabled()) {
@@ -214,15 +262,13 @@ export class SchemaCatalog {
214
262
  at,
215
263
  }, null, 2);
216
264
  }
217
- const declared = requested.includes('.')
218
- ? undefined
219
- : this.options.appSchemas.find((entry) => sameName(entry.schema, requested));
220
- if (declared) {
265
+ const schema = requested.includes('.') ? null : this.store.schemaName(requested);
266
+ if (schema) {
221
267
  await this.collector.collectInventory(true);
222
268
  return JSON.stringify({
223
269
  refreshed: 'inventory',
224
- requestedSchema: declared.schema,
225
- note: '인벤토리는 선언된 모든 스키마를 쿼리 한 번으로 함께 갱신합니다.',
270
+ requestedSchema: schema,
271
+ note: '인벤토리는 모든 스키마를 쿼리 한 번으로 함께 갱신합니다.',
226
272
  ...this.inventoryReport(),
227
273
  at,
228
274
  }, null, 2);
@@ -246,7 +292,7 @@ export class SchemaCatalog {
246
292
  }, null, 2);
247
293
  }
248
294
  throw new Error(`Unknown refresh target "${requested}". Use schema.table for one table's ` +
249
- 'columns, a declared schema name for the table inventory, or omit target ' +
295
+ 'columns, a schema name for the table inventory, or omit target ' +
250
296
  'for the inventory.');
251
297
  }
252
298
  inventoryReport() {
@@ -275,7 +321,25 @@ export class SchemaCatalog {
275
321
  repo: link.repo,
276
322
  });
277
323
  }
278
- return this.documents.link(resolvedLinks, (repo) => this.store.codeBranches()[repo] ? null : missingBranchNotice(this.options.profile, repo));
324
+ return this.documents.link(resolvedLinks, (linked) => {
325
+ const branchNotices = [...new Set(linked.map((link) => link.repo))]
326
+ .filter((repo) => !this.store.codeBranches()[repo])
327
+ .map((repo) => missingBranchNotice(this.options.profile, repo));
328
+ const owners = this.store.schemaOwners();
329
+ const docsBySchema = new Map();
330
+ for (const link of linked) {
331
+ if (owners[link.schema]) {
332
+ continue;
333
+ }
334
+ const docs = docsBySchema.get(link.schema) ?? [];
335
+ if (!docs.some((entry) => entry.repo === link.repo && entry.doc === link.doc)) {
336
+ docs.push({ repo: link.repo, doc: link.doc });
337
+ }
338
+ docsBySchema.set(link.schema, docs);
339
+ }
340
+ const ownerNotices = [...docsBySchema].map(([schema, docs]) => missingOwnerNotice(schema, docs));
341
+ return [...branchNotices, ...ownerNotices];
342
+ });
279
343
  }
280
344
  async unlink(input) {
281
345
  if (!this.isEnabled()) {
@@ -0,0 +1,35 @@
1
+ import { normalizeGithubRepo } from './docs.js';
2
+ const APP_MAX_LENGTH = 100;
3
+ export function normalizeAppName(input) {
4
+ const app = typeof input === 'string' ? input.trim() : '';
5
+ const reject = (reason) => {
6
+ throw new Error(`Invalid app name ${JSON.stringify(input)}: ${reason}.`);
7
+ };
8
+ if (!app) {
9
+ reject('it is empty');
10
+ }
11
+ if (app.length > APP_MAX_LENGTH) {
12
+ reject(`it is longer than ${APP_MAX_LENGTH} characters`);
13
+ }
14
+ if (/[\u0000- \u007f]/.test(app)) {
15
+ reject('it contains whitespace or a control character');
16
+ }
17
+ return app;
18
+ }
19
+ export function normalizeSchemaOwner(repo, app) {
20
+ return { repo: normalizeGithubRepo(repo), app: normalizeAppName(app) };
21
+ }
22
+ export function schemaOwnerOf(schema) {
23
+ return typeof schema.repo === 'string' && typeof schema.app === 'string'
24
+ ? { repo: schema.repo, app: schema.app }
25
+ : null;
26
+ }
27
+ export function loadedSchemaOwner(schema) {
28
+ try {
29
+ const owner = normalizeSchemaOwner(schema.repo, schema.app);
30
+ return owner.repo === schema.repo && owner.app === schema.app ? owner : {};
31
+ }
32
+ catch {
33
+ return {};
34
+ }
35
+ }
@@ -1,4 +1,5 @@
1
1
  import { suggestedBranch } from './branch.js';
2
+ import { schemaOwnerOf } from './owner.js';
2
3
  const UNLINKED_SAMPLE_LIMIT = 30;
3
4
  const HOT_TABLE_LIMIT = 10;
4
5
  function sampled(values) {
@@ -32,7 +33,6 @@ function rankTables(tables) {
32
33
  }
33
34
  function allTables(catalog) {
34
35
  return Object.entries(catalog.schemas).flatMap(([schema, entry]) => Object.entries(entry.tables).map(([table, tableEntry]) => ({
35
- app: entry.app,
36
36
  schema,
37
37
  table,
38
38
  entry: tableEntry,
@@ -64,15 +64,16 @@ export function renderToolDescriptionSuffix(catalog, budget) {
64
64
  }
65
65
  return HOT_TABLES_HEADING + listed + staticGuidance;
66
66
  }
67
+ function ownerField(owner) {
68
+ return owner ? { owner } : {};
69
+ }
67
70
  export function renderMap(catalog) {
68
71
  const schemas = Object.entries(catalog.schemas).map(([name, schema]) => ({
69
- app: schema.app,
70
72
  schema: name,
71
- description: schema.description ?? '',
73
+ ...ownerField(schemaOwnerOf(schema)),
72
74
  scannedAt: schema.scannedAt,
73
75
  tableCount: Object.keys(schema.tables).length,
74
76
  tables: rankTables(Object.entries(schema.tables).map(([table, entry]) => ({
75
- app: schema.app,
76
77
  schema: name,
77
78
  table,
78
79
  entry,
@@ -115,6 +116,7 @@ export function searchCatalog(catalog, query, limit) {
115
116
  }
116
117
  const results = [];
117
118
  for (const [schemaName, schema] of Object.entries(catalog.schemas)) {
119
+ const owner = ownerField(schemaOwnerOf(schema));
118
120
  for (const [tableName, table] of Object.entries(schema.tables)) {
119
121
  const qualified = `${schemaName}.${tableName}`;
120
122
  const matchedColumns = table.columns
@@ -127,6 +129,7 @@ export function searchCatalog(catalog, query, limit) {
127
129
  score += Math.min(9, Math.floor(Math.log2(table.usage.successCount + 1)));
128
130
  results.push({
129
131
  table: qualified,
132
+ ...owner,
130
133
  score,
131
134
  comment: table.comment,
132
135
  matchedColumns,
@@ -148,13 +151,27 @@ function branchQuestion(profile, repo) {
148
151
  export function missingBranchNotice(profile, repo) {
149
152
  return (`[카탈로그] ${repo}에서 이 DB에 대응하는 코드 브랜치가 기록되지 않았습니다. ` + branchQuestion(profile, repo));
150
153
  }
154
+ export function missingOwnerNotice(schema, linkedDocs) {
155
+ const docs = linkedDocs.map(({ repo, doc }) => `${repo}의 ${doc}`).join(', ');
156
+ return (`[카탈로그] ${schema} schema를 가진 저장소와 앱이 기록되지 않았습니다. ` +
157
+ `방금 연결한 문서는 ${docs}입니다.\n` +
158
+ `${schema} schema가 어느 저장소의 어느 앱 것인지 사용자에게 물으세요.\n` +
159
+ `확인받은 값을 mysql_catalog {action:"owner", target:"${schema}", repo:"<owner/name>", app:"<앱 이름>"} 로 기록하세요.`);
160
+ }
161
+ export function renderSchemasResource(profile, codeBranches, owners) {
162
+ return JSON.stringify({
163
+ profile,
164
+ ...(Object.keys(codeBranches).length > 0 ? { codeBranches } : {}),
165
+ schemas: owners,
166
+ }, null, 2);
167
+ }
151
168
  function shellQuote(value) {
152
169
  if (/^[A-Za-z0-9_./:@+-]+$/.test(value)) {
153
170
  return value;
154
171
  }
155
172
  return `'${value.replace(/'/g, `'"'"'`)}'`;
156
173
  }
157
- export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile) {
174
+ export function renderDescribe(qualifiedName, table, codeBranches, observedJoins, profile, owner = null) {
158
175
  let docs;
159
176
  const hasDocumentDecision = Object.prototype.hasOwnProperty.call(table.curated, 'doc');
160
177
  const documentLink = table.curated.doc;
@@ -190,6 +207,7 @@ export function renderDescribe(qualifiedName, table, codeBranches, observedJoins
190
207
  }
191
208
  return JSON.stringify({
192
209
  table: qualifiedName,
210
+ ...ownerField(owner),
193
211
  ...table,
194
212
  ...(observedJoins.length > 0 ? { observedJoins } : {}),
195
213
  docs,
@@ -2,6 +2,7 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { loadedCodeBranches } from './branch.js';
4
4
  import { normalizeDocumentPath, normalizeGithubRepo } from './docs.js';
5
+ import { loadedSchemaOwner, schemaOwnerOf } from './owner.js';
5
6
  import { CATALOG_VERSION, emptyCatalog, emptyTable, normalizeName, pruneJoins } from './types.js';
6
7
  const FLUSH_DELAY_MS = 2_000;
7
8
  const LOCK_RETRY_MS = 25;
@@ -200,6 +201,11 @@ function mergeTable(external, local, base) {
200
201
  curated: mergeCurated(external.curated ?? { notes: [], aliases: [] }, local.curated ?? { notes: [], aliases: [] }, base?.curated),
201
202
  };
202
203
  }
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
+ }
203
209
  function mergeSchema(external, local, base) {
204
210
  const newerInventory = timestamp(local.scannedAt) >= timestamp(external.scannedAt) ? local : external;
205
211
  const olderInventory = newerInventory === local ? external : local;
@@ -209,7 +215,7 @@ function mergeSchema(external, local, base) {
209
215
  ? mergeTable(newerInventory === local ? olderInventory.tables[name] : table, newerInventory === local ? table : olderInventory.tables[name], base?.tables[name])
210
216
  : table;
211
217
  }
212
- return { ...newerInventory, tables };
218
+ return { ...mergeOwner(external, local, base), scannedAt: newerInventory.scannedAt, tables };
213
219
  }
214
220
  function mergeCodeBranches(external, local, base) {
215
221
  const merged = {};
@@ -227,7 +233,7 @@ function mergeCatalog(external, local, base) {
227
233
  if (external.schemas[name] && local.schemas[name]) {
228
234
  schemas[name] = mergeSchema(external.schemas[name], local.schemas[name], base.schemas[name]);
229
235
  }
230
- else {
236
+ else if (!base.schemas[name]) {
231
237
  schemas[name] = external.schemas[name] ?? local.schemas[name];
232
238
  }
233
239
  }
@@ -343,12 +349,17 @@ export class CatalogStore {
343
349
  sanitizeLoaded(loaded) {
344
350
  const fresh = emptyCatalog(this.options);
345
351
  fresh.codeBranches = loadedCodeBranches(loaded.codeBranches);
346
- for (const [schemaName, schema] of Object.entries(fresh.schemas)) {
347
- const cached = loaded.schemas?.[schemaName];
348
- if (!cached) {
352
+ const loadedSchemas = loaded.schemas && typeof loaded.schemas === 'object' ? loaded.schemas : {};
353
+ for (const [schemaName, cached] of Object.entries(loadedSchemas)) {
354
+ if (!cached || typeof cached !== 'object') {
349
355
  continue;
350
356
  }
351
- schema.scannedAt = cached.scannedAt ?? null;
357
+ const schema = {
358
+ ...loadedSchemaOwner(cached),
359
+ scannedAt: cached.scannedAt ?? null,
360
+ tables: {},
361
+ };
362
+ fresh.schemas[schemaName] = schema;
352
363
  for (const [tableName, raw] of Object.entries(cached.tables ?? {})) {
353
364
  const base = emptyTable();
354
365
  const table = {
@@ -429,9 +440,21 @@ export class CatalogStore {
429
440
  }
430
441
  return matches;
431
442
  }
432
- schemaState(schema) {
433
- const entry = this.data.schemas[schema];
434
- return entry ? { scannedAt: entry.scannedAt } : null;
443
+ schemaScanTimes() {
444
+ return Object.values(this.data.schemas).map((schema) => schema.scannedAt);
445
+ }
446
+ schemaName(input) {
447
+ return this.ensureNameIndex().get(normalizeName(input))?.schema ?? null;
448
+ }
449
+ schemaOwners() {
450
+ 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;
455
+ }
456
+ }
457
+ return owners;
435
458
  }
436
459
  tableMeta(schema, table) {
437
460
  const entry = this.data.schemas[schema]?.tables[table];
@@ -6,6 +6,7 @@ export function pruneJoins(joins) {
6
6
  }
7
7
  return [...joins].sort((a, b) => b.lastUsedAt.localeCompare(a.lastUsedAt)).slice(0, JOIN_EDGE_LIMIT);
8
8
  }
9
+ export const SYSTEM_SCHEMAS = ['information_schema', 'mysql', 'performance_schema', 'sys'];
9
10
  export function normalizeName(value) {
10
11
  return value.trim().toLowerCase();
11
12
  }
@@ -32,21 +33,12 @@ export function emptyUsage() {
32
33
  };
33
34
  }
34
35
  export function emptyCatalog(options) {
35
- const schemas = {};
36
- for (const entry of options.appSchemas) {
37
- schemas[entry.schema] = {
38
- app: entry.app,
39
- ...(entry.description ? { description: entry.description } : {}),
40
- scannedAt: null,
41
- tables: {},
42
- };
43
- }
44
36
  return {
45
37
  version: CATALOG_VERSION,
46
38
  profile: options.profile,
47
39
  fingerprint: options.fingerprint,
48
40
  codeBranches: {},
49
- schemas,
41
+ schemas: {},
50
42
  joins: [],
51
43
  };
52
44
  }
@@ -61,42 +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
- function parseAppSchemas(raw) {
65
- if (!raw) {
66
- return [];
67
- }
68
- const entries = [];
69
- const seen = new Set();
70
- for (const entry of raw.split(/[;\n]/)) {
71
- const trimmed = entry.trim();
72
- if (!trimmed || trimmed.startsWith('#')) {
73
- continue;
74
- }
75
- const firstColon = trimmed.indexOf(':');
76
- if (firstColon === -1) {
77
- console.error(`[config] ignoring MYSQL_APP_SCHEMAS entry "${trimmed}": expected "app:schema" or "app:schema:description".`);
78
- continue;
79
- }
80
- const app = trimmed.slice(0, firstColon).trim();
81
- const rest = trimmed.slice(firstColon + 1);
82
- const secondColon = rest.indexOf(':');
83
- const schema = (secondColon === -1 ? rest : rest.slice(0, secondColon)).trim();
84
- const description = secondColon === -1 ? undefined : rest.slice(secondColon + 1).trim() || undefined;
85
- if (!app || !schema) {
86
- console.error(`[config] ignoring MYSQL_APP_SCHEMAS entry "${trimmed}": app and schema must both be non-empty.`);
87
- continue;
88
- }
89
- const pair = `${app.toLowerCase()}\u0000${schema.toLowerCase()}`;
90
- if (seen.has(pair)) {
91
- console.error(`[config] MYSQL_APP_SCHEMAS repeats "${app}:${schema}"; keeping the first.`);
92
- continue;
93
- }
94
- seen.add(pair);
95
- entries.push({ app, schema, description });
96
- }
97
- return entries;
98
- }
99
- export const APP_SCHEMAS = parseAppSchemas(process.env.MYSQL_APP_SCHEMAS);
100
64
  export const MYSQL_CATALOG_ENABLED = process.env.MYSQL_CATALOG_ENABLED !== 'false';
101
65
  export const MYSQL_CATALOG_PATH = process.env.MYSQL_CATALOG_PATH?.trim() || undefined;
102
66
  function parseCatalogTtl(raw) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecubelabs/mysql-mcp",
3
- "version": "1.0.0-next.4",
3
+ "version": "1.0.0-next.5",
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": {