@ecubelabs/mysql-mcp 0.0.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/dist/index.js CHANGED
@@ -4,10 +4,11 @@ import { realpathSync } from 'fs';
4
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
6
  import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
7
- import { log, tableResourceUri } from './src/utils/index.js';
8
- import { ALLOW_DELETE_OPERATION, ALLOW_DDL_OPERATION, ALLOW_INSERT_OPERATION, ALLOW_UPDATE_OPERATION, 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';
7
+ import { log, sharedOnce, tableResourceUri } from './src/utils/index.js';
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
10
  import { catalogIdentity, SchemaCatalog } from './src/catalog/index.js';
10
- import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, clampTimeoutSeconds, poolPromise, profileBanner, } from './src/db/index.js';
11
+ import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
11
12
  import { describeTunnel, ensureTunnel, resolveTunnelConfig, stopTunnel } from './src/ssh/tunnel.js';
12
13
  log('info', `Starting MySQL MCP server v${PACKAGE_VERSION}...`);
13
14
  const toolVersion = `MySQL MCP Server [v${PACKAGE_VERSION}]`;
@@ -21,21 +22,10 @@ if (MYSQL_PROFILE) {
21
22
  if (isMultiDbMode) {
22
23
  baseToolDescription += ' (Multi-DB mode enabled)';
23
24
  }
24
- if (ALLOW_INSERT_OPERATION || ALLOW_UPDATE_OPERATION || ALLOW_DELETE_OPERATION || ALLOW_DDL_OPERATION) {
25
- baseToolDescription += ' with support for:';
26
- if (ALLOW_INSERT_OPERATION) {
27
- baseToolDescription += ' INSERT,';
28
- }
29
- if (ALLOW_UPDATE_OPERATION) {
30
- baseToolDescription += ' UPDATE,';
31
- }
32
- if (ALLOW_DELETE_OPERATION) {
33
- baseToolDescription += ' DELETE,';
34
- }
35
- if (ALLOW_DDL_OPERATION) {
36
- baseToolDescription += ' DDL,';
37
- }
38
- baseToolDescription = baseToolDescription.replace(/,$/, '') + ' and READ operations';
25
+ const writes = writeCapabilities();
26
+ if (writes.length > 0) {
27
+ const supported = writes.map(({ label, schemas }) => (schemas ? `${label} (${schemas.join(', ')} only)` : label));
28
+ baseToolDescription += ` with support for: ${supported.join(', ')} and READ operations`;
39
29
  if (Object.keys(SCHEMA_INSERT_PERMISSIONS).length > 0 ||
40
30
  Object.keys(SCHEMA_UPDATE_PERMISSIONS).length > 0 ||
41
31
  Object.keys(SCHEMA_DELETE_PERMISSIONS).length > 0 ||
@@ -50,37 +40,43 @@ baseToolDescription +=
50
40
  `\n\nLIMITS: every read is cancelled after ${MYSQL_DEFAULT_TIMEOUT_SECONDS}s ` +
51
41
  `(raise per call with timeout_seconds, up to ${MYSQL_MAX_TIMEOUT_SECONDS}) and returns at most ` +
52
42
  `${MAX_RESPONSE_ROWS.toLocaleString('en-US')} rows. Aggregate in SQL rather than pulling rows to count them. ` +
53
- `USE and SET are rejected; write schema.table instead of USE.`;
54
- if (CODE_BRANCH) {
55
- baseToolDescription +=
56
- `\n\nCODE REVISION: this database matches the \`${CODE_BRANCH}\` branch. ` +
57
- `Read entities, migrations, and queries from that branch when correlating code with data.`;
43
+ `USE and SET are rejected; write schema.table instead of USE. ` +
44
+ `Executable comments (/*! ... */) and MAX_EXECUTION_TIME or SET_VAR hints are rejected; use timeout_seconds instead.`;
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
+ : '';
58
50
  }
51
+ let appSchemaDescription = '';
59
52
  if (APP_SCHEMAS.length > 0) {
60
- baseToolDescription +=
53
+ appSchemaDescription +=
61
54
  '\n\nAPP -> SCHEMA (authoritative — use these directly; do not run SHOW DATABASES ' +
62
55
  'or search information_schema to find a schema):';
63
56
  for (const entry of APP_SCHEMAS) {
64
- baseToolDescription +=
57
+ appSchemaDescription +=
65
58
  `\n - ${entry.app} -> ${entry.schema}` + (entry.description ? ` — ${entry.description}` : '');
66
59
  }
67
- baseToolDescription +=
60
+ appSchemaDescription +=
68
61
  '\nQualify every table with its schema (schema.table). Any schema not listed here is ' +
69
62
  'either absent from this environment or not owned by an application.';
70
63
  const needsQuoting = APP_SCHEMAS.find((entry) => !/^[A-Za-z0-9_$]+$/.test(entry.schema));
71
64
  if (needsQuoting) {
72
- baseToolDescription +=
65
+ appSchemaDescription +=
73
66
  `\nA schema name that is not a bare identifier must be backtick-quoted, ` +
74
67
  `e.g. SELECT ... FROM \`${needsQuoting.schema}\`.some_table.`;
75
68
  }
76
69
  }
77
- const isReadOnly = !(ALLOW_INSERT_OPERATION || ALLOW_UPDATE_OPERATION || ALLOW_DELETE_OPERATION || ALLOW_DDL_OPERATION);
70
+ const isReadOnly = writes.length === 0;
78
71
  const mysqlCatalogTool = {
79
72
  name: 'mysql_catalog',
80
73
  description: 'Read the local schema catalog without rediscovering database metadata. ' +
81
74
  'Use map for the app/schema overview, search to find tables or known columns, ' +
82
- 'describe before writing SQL, and docs_list/docs_read to inspect domain documents. ' +
83
- "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. ' +
84
80
  'Use note to save a table memo or alias, and forget to clear one catalog scope. ' +
85
81
  'Use refresh when cached metadata contradicts what a query actually returned, ' +
86
82
  'or right after a migration: added columns and indexes raise no error, so ' +
@@ -90,18 +86,7 @@ const mysqlCatalogTool = {
90
86
  properties: {
91
87
  action: {
92
88
  type: 'string',
93
- enum: [
94
- 'map',
95
- 'search',
96
- 'describe',
97
- 'docs_list',
98
- 'docs_read',
99
- 'link',
100
- 'unlink',
101
- 'note',
102
- 'forget',
103
- 'refresh',
104
- ],
89
+ enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'note', 'forget', 'refresh'],
105
90
  description: 'Catalog operation to perform',
106
91
  },
107
92
  q: {
@@ -119,22 +104,18 @@ const mysqlCatalogTool = {
119
104
  description: 'Qualified schema.table name for describe, or for unlink. note and ' +
120
105
  'forget take the same name as target instead.',
121
106
  },
122
- schema: {
107
+ branch: {
123
108
  type: 'string',
124
- description: 'Declared schema name for docs_list. Results are narrowed to the ' +
125
- 'documents under the app directory declared for that schema; the ' +
126
- 'response says so and reports how many were left out.',
127
- },
128
- path: {
129
- type: 'string',
130
- 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.',
131
113
  },
132
114
  target: {
133
115
  type: 'string',
134
116
  description: 'Qualified schema.table for note or forget. For refresh: "schema.table" for one table\'s ' +
135
117
  'columns, indexes and foreign keys; a declared schema name for the ' +
136
- 'table inventory; "docs" to re-read the document ref after a git ' +
137
- 'fetch. Omit it to refresh the inventory and the documents together.',
118
+ 'table inventory. Omit it to refresh the inventory.',
138
119
  },
139
120
  text: {
140
121
  type: 'string',
@@ -164,10 +145,17 @@ const mysqlCatalogTool = {
164
145
  },
165
146
  doc: {
166
147
  type: 'string',
167
- 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.',
168
156
  },
169
157
  },
170
- required: ['table', 'doc'],
158
+ required: ['table', 'doc', 'repo'],
171
159
  },
172
160
  },
173
161
  },
@@ -246,19 +234,19 @@ export default function createMcpServer() {
246
234
  filePath: identity.filePath,
247
235
  ttlHours: MYSQL_CATALOG_TTL_HOURS,
248
236
  appSchemas: APP_SCHEMAS,
249
- docsRepo: MYSQL_DOCS_REPO ?? null,
250
- docsRef: CODE_BRANCH ? `origin/${CODE_BRANCH}` : null,
251
237
  defaultSchema: typeof mysqlSettings.database === 'string' ? mysqlSettings.database : null,
252
238
  });
253
239
  setQueryDiagnosticsSource({
254
240
  indexFacts: (reference) => catalog.indexFacts(reference),
255
241
  });
256
- if (baseToolDescription.length > TOOL_DESCRIPTION_LIMIT) {
257
- 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 ` +
258
246
  `catalog tail; clients keep ${TOOL_DESCRIPTION_LIMIT} and silently drop the rest. ` +
259
247
  `Shorten MYSQL_APP_SCHEMAS descriptions, or the text in index.ts.`);
260
248
  }
261
- const mysqlQueryDescription = () => baseToolDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - baseToolDescription.length);
249
+ const mysqlQueryDescription = () => queryBaseDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - queryBaseDescription.length);
262
250
  const loadResourceTables = async () => {
263
251
  if (catalog.isEnabled()) {
264
252
  try {
@@ -338,6 +326,7 @@ export default function createMcpServer() {
338
326
  try {
339
327
  log('info', 'Handling ReadResourceRequest:', request.params.uri);
340
328
  if (request.params.uri === 'mysql://schemas') {
329
+ const codeBranch = catalog.codeBranch();
341
330
  return {
342
331
  contents: [
343
332
  {
@@ -345,7 +334,7 @@ export default function createMcpServer() {
345
334
  mimeType: 'application/json',
346
335
  text: JSON.stringify({
347
336
  profile: PROFILE_LABEL,
348
- ...(CODE_BRANCH ? { codeBranch: CODE_BRANCH } : {}),
337
+ ...(codeBranch ? { codeBranch } : {}),
349
338
  apps: APP_SCHEMAS,
350
339
  }, null, 2),
351
340
  },
@@ -441,25 +430,14 @@ export default function createMcpServer() {
441
430
  }
442
431
  text = await catalog.describe(args.table);
443
432
  }
444
- else if (action === 'docs_list') {
445
- if (typeof args.schema !== 'string' || !args.schema.trim()) {
446
- throw new Error('mysql_catalog docs_list requires "schema".');
447
- }
448
- text = await catalog.docsList(args.schema);
449
- }
450
- else if (action === 'docs_read') {
451
- if (typeof args.path !== 'string' || !args.path.trim()) {
452
- throw new Error('mysql_catalog docs_read requires "path".');
453
- }
454
- text = await catalog.docsRead(args.path);
455
- }
456
433
  else if (action === 'link') {
457
434
  if (!Array.isArray(args.links) ||
458
435
  !args.links.every((link) => link &&
459
436
  typeof link === 'object' &&
460
437
  typeof link.table === 'string' &&
461
- typeof link.doc === 'string')) {
462
- 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}, ...].');
463
441
  }
464
442
  text = await catalog.link(args.links);
465
443
  }
@@ -493,6 +471,12 @@ export default function createMcpServer() {
493
471
  }
494
472
  text = await catalog.forget(args.target, args.scope);
495
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
+ }
496
480
  else if (action === 'refresh') {
497
481
  if (args.target !== undefined && typeof args.target !== 'string') {
498
482
  throw new Error('mysql_catalog refresh takes "target" as a string.');
@@ -514,6 +498,9 @@ export default function createMcpServer() {
514
498
  throw new Error(`Unknown tool: ${request.params.name}`);
515
499
  }
516
500
  const sql = request.params.arguments?.sql;
501
+ if (typeof sql !== 'string' || sql.trim() === '') {
502
+ throw new Error('The "sql" argument is required and must be a non-empty string.');
503
+ }
517
504
  const timeoutSeconds = clampTimeoutSeconds(request.params.arguments?.timeout_seconds);
518
505
  const references = catalog.prepareQuery(sql);
519
506
  let result;
@@ -537,7 +524,7 @@ export default function createMcpServer() {
537
524
  }
538
525
  catch (err) {
539
526
  const error = err;
540
- log('error', 'Error in CallToolRequest handler:', error);
527
+ log('error', 'Error in CallToolRequest handler:', describeQueryError(error));
541
528
  return {
542
529
  content: [
543
530
  {
@@ -597,8 +584,8 @@ export default function createMcpServer() {
597
584
  process.exit(1);
598
585
  }
599
586
  })();
600
- const shutdown = async (signal) => {
601
- log('error', `Received ${signal}. Shutting down...`);
587
+ const shutdown = sharedOnce(async (signal) => {
588
+ log('info', `Received ${signal}. Shutting down...`);
602
589
  try {
603
590
  await catalog.close();
604
591
  if (poolPromise) {
@@ -612,7 +599,7 @@ export default function createMcpServer() {
612
599
  finally {
613
600
  await stopTunnel();
614
601
  }
615
- };
602
+ });
616
603
  const shutdownAndExit = async (reason) => {
617
604
  try {
618
605
  await shutdown(reason);
@@ -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
+ }