@ecubelabs/mysql-mcp 1.1.0-next.3 → 2.0.0-next.1

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
@@ -6,7 +6,7 @@ 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, 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, ignoredEnvSummary, startupFailureMessage, } 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
12
  import { renderSchemasResource } from './src/catalog/render.js';
@@ -24,6 +24,10 @@ if (MYSQL_PROFILE) {
24
24
  if (isMultiDbMode) {
25
25
  baseToolDescription += ' (Multi-DB mode enabled)';
26
26
  }
27
+ const ignoredEnv = ignoredEnvSummary();
28
+ if (ignoredEnv) {
29
+ baseToolDescription += ` [${ignoredEnv}]`;
30
+ }
27
31
  const writes = writeCapabilities();
28
32
  if (writes.length > 0) {
29
33
  const supported = writes.map(({ label, schemas }) => (schemas ? `${label} (${schemas.join(', ')} only)` : label));
@@ -569,8 +573,7 @@ export default function createMcpServer() {
569
573
  if (SSH_ENABLED) {
570
574
  log('info', 'Opening SSH tunnel before connecting to MySQL...');
571
575
  const endpoint = await ensureTunnel();
572
- log('info', `SSH tunnel ready on ${endpoint?.host}:${endpoint?.port}` +
573
- (endpoint?.reused ? ' (reused an existing forward)' : ''));
576
+ log('info', `SSH tunnel ready on ${endpoint?.host}:${endpoint?.port}`);
574
577
  }
575
578
  log('info', 'Attempting to test database connection...');
576
579
  const pool = await getPool();
@@ -580,8 +583,7 @@ export default function createMcpServer() {
580
583
  catalog.startInventory();
581
584
  }
582
585
  catch (error) {
583
- console.error(`[startup] fatal error for profile ${PROFILE_LABEL}: ` +
584
- (error instanceof Error ? error.message : String(error)));
586
+ console.error(startupFailureMessage(error));
585
587
  log('error', 'Fatal error during server startup:', error);
586
588
  await stopTunnel();
587
589
  process.exit(1);
@@ -665,8 +667,7 @@ if (isMainModule()) {
665
667
  log('info', 'Server started and listening on stdio');
666
668
  }
667
669
  catch (error) {
668
- console.error(`[startup] fatal error for profile ${PROFILE_LABEL}: ` +
669
- (error instanceof Error ? error.message : String(error)));
670
+ console.error(startupFailureMessage(error));
670
671
  log('error', 'Server error:', error);
671
672
  process.exit(1);
672
673
  }
@@ -2,19 +2,6 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import { parseArgs } from 'util';
5
- function parseSchemaPermissions(permissionsString) {
6
- const permissions = {};
7
- if (!permissionsString) {
8
- return permissions;
9
- }
10
- for (const pair of permissionsString.split(',')) {
11
- const [schema, value] = pair.split(':');
12
- if (schema && value) {
13
- permissions[schema.trim()] = value.trim() === 'true';
14
- }
15
- }
16
- return permissions;
17
- }
18
5
  function readSSLFile(filePath, label) {
19
6
  try {
20
7
  if (!fs.existsSync(filePath)) {
@@ -58,6 +45,129 @@ export function readPackageVersion(startDir) {
58
45
  dir = parent;
59
46
  }
60
47
  }
48
+ export const MIGRATED_ENV = {
49
+ MYSQL_PROFILE: '--profile',
50
+ MYSQL_SSH_HOST: '--ssh-host',
51
+ MYSQL_SSH_USER: '--ssh-user',
52
+ MYSQL_SSH_PORT: '--ssh-port',
53
+ MYSQL_SSH_PRIVATE_KEY_PATH: '--ssh-private-key-path',
54
+ MYSQL_HOST: '--host',
55
+ MYSQL_PORT: '--port',
56
+ MYSQL_SOCKET_PATH: '--socket-path',
57
+ MYSQL_DB: '--db',
58
+ MYSQL_SSL: '--ssl',
59
+ MYSQL_SSL_REJECT_UNAUTHORIZED: '--ssl-reject-unauthorized',
60
+ MYSQL_SSL_CA: '--ssl-ca',
61
+ MYSQL_SSL_CERT: '--ssl-cert',
62
+ MYSQL_SSL_KEY: '--ssl-key',
63
+ MYSQL_TIMEZONE: '--timezone',
64
+ MYSQL_DATE_STRINGS: '--date-strings',
65
+ MYSQL_BIG_NUMBER_STRINGS: '--big-number-strings',
66
+ MYSQL_POOL_SIZE: '--pool-size',
67
+ MYSQL_QUEUE_LIMIT: '--queue-limit',
68
+ MYSQL_CONNECT_TIMEOUT: '--connect-timeout',
69
+ ALLOW_INSERT_OPERATION: '--allow-insert',
70
+ ALLOW_UPDATE_OPERATION: '--allow-update',
71
+ ALLOW_DELETE_OPERATION: '--allow-delete',
72
+ ALLOW_DDL_OPERATION: '--allow-ddl',
73
+ SCHEMA_INSERT_PERMISSIONS: '--schema-insert',
74
+ SCHEMA_UPDATE_PERMISSIONS: '--schema-update',
75
+ SCHEMA_DELETE_PERMISSIONS: '--schema-delete',
76
+ SCHEMA_DDL_PERMISSIONS: '--schema-ddl',
77
+ MYSQL_DISABLE_READ_ONLY_TRANSACTIONS: '--no-read-only-transactions',
78
+ MYSQL_MAX_TIMEOUT_SECONDS: '--max-timeout',
79
+ MYSQL_MAX_RESPONSE_ROWS: '--max-rows',
80
+ MYSQL_CATALOG_TIMEOUT_SECONDS: '--catalog-timeout',
81
+ MYSQL_CATALOG_ENABLED: '--no-catalog',
82
+ MYSQL_CATALOG_PATH: '--catalog-path',
83
+ MYSQL_CATALOG_TTL_HOURS: '--catalog-ttl',
84
+ ENABLE_LOGGING: '--log',
85
+ };
86
+ export const IGNORED_ENV = Object.keys(MIGRATED_ENV).filter((name) => Boolean(process.env[name]?.trim()));
87
+ export function ignoredEnvNotice() {
88
+ if (IGNORED_ENV.length === 0) {
89
+ return null;
90
+ }
91
+ return (`ignored ${IGNORED_ENV.length} env var(s) that are now server arguments: ${IGNORED_ENV.join(', ')}. ` +
92
+ 'See the "인자로 옮긴 env" table in the README.');
93
+ }
94
+ export function ignoredEnvSummary() {
95
+ return IGNORED_ENV.length === 0 ? null : `ignored env: ${IGNORED_ENV.length} (now server arguments)`;
96
+ }
97
+ if (IGNORED_ENV.length > 0) {
98
+ console.error(`[config] ${ignoredEnvNotice()}`);
99
+ }
100
+ const SERVER_ARG_OPTIONS = {
101
+ profile: { type: 'string' },
102
+ 'ssh-host': { type: 'string' },
103
+ 'ssh-user': { type: 'string' },
104
+ 'ssh-port': { type: 'string' },
105
+ 'ssh-private-key-path': { type: 'string' },
106
+ host: { type: 'string' },
107
+ port: { type: 'string' },
108
+ 'socket-path': { type: 'string' },
109
+ db: { type: 'string' },
110
+ ssl: { type: 'boolean' },
111
+ 'ssl-reject-unauthorized': { type: 'boolean' },
112
+ 'ssl-ca': { type: 'string' },
113
+ 'ssl-cert': { type: 'string' },
114
+ 'ssl-key': { type: 'string' },
115
+ timezone: { type: 'string' },
116
+ 'date-strings': { type: 'boolean' },
117
+ 'big-number-strings': { type: 'boolean' },
118
+ 'pool-size': { type: 'string' },
119
+ 'queue-limit': { type: 'string' },
120
+ 'connect-timeout': { type: 'string' },
121
+ 'allow-insert': { type: 'boolean' },
122
+ 'allow-update': { type: 'boolean' },
123
+ 'allow-delete': { type: 'boolean' },
124
+ 'allow-ddl': { type: 'boolean' },
125
+ 'schema-insert': { type: 'string' },
126
+ 'schema-update': { type: 'string' },
127
+ 'schema-delete': { type: 'string' },
128
+ 'schema-ddl': { type: 'string' },
129
+ 'no-read-only-transactions': { type: 'boolean' },
130
+ 'max-timeout': { type: 'string' },
131
+ 'max-rows': { type: 'string' },
132
+ 'catalog-timeout': { type: 'string' },
133
+ 'no-catalog': { type: 'boolean' },
134
+ 'catalog-path': { type: 'string' },
135
+ 'catalog-ttl': { type: 'string' },
136
+ log: { type: 'boolean' },
137
+ };
138
+ const SSH_DEPENDENT_ARGS = ['ssh-user', 'ssh-port', 'ssh-private-key-path'];
139
+ const PORT_RANGE = { min: 1, max: 65535 };
140
+ const POSITIVE_RANGE = { min: 1, max: Number.MAX_SAFE_INTEGER };
141
+ function parseIntegerArg(name, raw, range, violations) {
142
+ if (raw === undefined) {
143
+ return undefined;
144
+ }
145
+ const value = Number(raw);
146
+ if (!/^\d+$/.test(raw) || value < range.min || value > range.max) {
147
+ violations.push(range === POSITIVE_RANGE
148
+ ? `--${name} "${raw}" is not a positive integer`
149
+ : `--${name} "${raw}" is not an integer between ${range.min} and ${range.max}`);
150
+ return undefined;
151
+ }
152
+ return value;
153
+ }
154
+ function parseSchemaPermissionsArg(name, raw, violations) {
155
+ if (raw === undefined) {
156
+ return undefined;
157
+ }
158
+ const permissions = {};
159
+ for (const item of raw.split(',')) {
160
+ const separator = item.indexOf(':');
161
+ const schema = separator === -1 ? '' : item.slice(0, separator).trim();
162
+ const value = separator === -1 ? '' : item.slice(separator + 1).trim();
163
+ if (!schema || (value !== 'true' && value !== 'false')) {
164
+ violations.push(`--${name} item "${item.trim()}" is not <schema>:true or <schema>:false`);
165
+ continue;
166
+ }
167
+ permissions[schema] = value === 'true';
168
+ }
169
+ return permissions;
170
+ }
61
171
  export function parseServerArgs(argv) {
62
172
  let parsed;
63
173
  try {
@@ -65,8 +175,10 @@ export function parseServerArgs(argv) {
65
175
  }
66
176
  catch (error) {
67
177
  const reason = (error instanceof Error ? error.message : String(error)).replace(/\.?$/, '.');
68
- throw new Error(`invalid server arguments: ${reason} ` +
69
- `Supported: --profile <label>, --ssh-config-host <~/.ssh/config Host alias>.`);
178
+ const supported = Object.keys(SERVER_ARG_OPTIONS)
179
+ .map((name) => `--${name}`)
180
+ .join(', ');
181
+ throw new Error(`invalid server arguments: ${reason} Supported: ${supported}.`);
70
182
  }
71
183
  const seen = new Set();
72
184
  for (const token of parsed.tokens) {
@@ -78,147 +190,166 @@ export function parseServerArgs(argv) {
78
190
  }
79
191
  seen.add(token.name);
80
192
  }
81
- return {
82
- profile: parsed.values.profile?.trim() || undefined,
83
- sshConfigHost: parsed.values['ssh-config-host']?.trim() || undefined,
193
+ const values = parsed.values;
194
+ const text = (name) => {
195
+ const value = values[name];
196
+ return typeof value === 'string' ? value.trim() || undefined : undefined;
197
+ };
198
+ const flag = (name) => values[name] === true;
199
+ const violations = [];
200
+ const args = {
201
+ profile: text('profile'),
202
+ sshHost: text('ssh-host'),
203
+ sshUser: text('ssh-user'),
204
+ sshPort: parseIntegerArg('ssh-port', text('ssh-port'), PORT_RANGE, violations),
205
+ sshPrivateKeyPath: text('ssh-private-key-path'),
206
+ host: text('host'),
207
+ port: parseIntegerArg('port', text('port'), PORT_RANGE, violations),
208
+ socketPath: text('socket-path'),
209
+ db: text('db'),
210
+ ssl: flag('ssl'),
211
+ sslRejectUnauthorized: flag('ssl-reject-unauthorized'),
212
+ sslCa: text('ssl-ca'),
213
+ sslCert: text('ssl-cert'),
214
+ sslKey: text('ssl-key'),
215
+ timezone: text('timezone'),
216
+ dateStrings: flag('date-strings'),
217
+ bigNumberStrings: flag('big-number-strings'),
218
+ poolSize: parseIntegerArg('pool-size', text('pool-size'), POSITIVE_RANGE, violations),
219
+ queueLimit: parseIntegerArg('queue-limit', text('queue-limit'), POSITIVE_RANGE, violations),
220
+ connectTimeout: parseIntegerArg('connect-timeout', text('connect-timeout'), POSITIVE_RANGE, violations),
221
+ allowInsert: flag('allow-insert'),
222
+ allowUpdate: flag('allow-update'),
223
+ allowDelete: flag('allow-delete'),
224
+ allowDdl: flag('allow-ddl'),
225
+ schemaInsert: parseSchemaPermissionsArg('schema-insert', text('schema-insert'), violations),
226
+ schemaUpdate: parseSchemaPermissionsArg('schema-update', text('schema-update'), violations),
227
+ schemaDelete: parseSchemaPermissionsArg('schema-delete', text('schema-delete'), violations),
228
+ schemaDdl: parseSchemaPermissionsArg('schema-ddl', text('schema-ddl'), violations),
229
+ noReadOnlyTransactions: flag('no-read-only-transactions'),
230
+ maxTimeout: parseIntegerArg('max-timeout', text('max-timeout'), POSITIVE_RANGE, violations),
231
+ maxRows: parseIntegerArg('max-rows', text('max-rows'), POSITIVE_RANGE, violations),
232
+ catalogTimeout: parseIntegerArg('catalog-timeout', text('catalog-timeout'), POSITIVE_RANGE, violations),
233
+ noCatalog: flag('no-catalog'),
234
+ catalogPath: text('catalog-path'),
235
+ catalogTtl: parseIntegerArg('catalog-ttl', text('catalog-ttl'), POSITIVE_RANGE, violations),
236
+ log: flag('log'),
84
237
  };
238
+ if (args.socketPath) {
239
+ const conflicts = ['host', 'port', 'ssh-host'].filter((name) => text(name) !== undefined);
240
+ if (conflicts.length > 0) {
241
+ violations.push(`--socket-path cannot be combined with ${conflicts.map((name) => `--${name}`).join(', ')}`);
242
+ }
243
+ }
244
+ if (!args.sshHost) {
245
+ const orphans = SSH_DEPENDENT_ARGS.filter((name) => text(name) !== undefined);
246
+ if (orphans.length > 0) {
247
+ violations.push(`${orphans.map((name) => `--${name}`).join(', ')} requires --ssh-host`);
248
+ }
249
+ }
250
+ else {
251
+ const missing = [!args.sshUser && '--ssh-user', !args.host && '--host'].filter(Boolean);
252
+ if (missing.length > 0) {
253
+ violations.push(`--ssh-host requires ${missing.join(' and ')}`);
254
+ }
255
+ }
256
+ if (violations.length > 0) {
257
+ throw new Error(`invalid server arguments: ${violations.join('; ')}.`);
258
+ }
259
+ return args;
85
260
  }
86
261
  function parseServerArgv(argv) {
87
262
  return parseArgs({
88
263
  args: [...argv],
89
- options: {
90
- profile: { type: 'string' },
91
- 'ssh-config-host': { type: 'string' },
92
- },
264
+ options: SERVER_ARG_OPTIONS,
93
265
  strict: true,
94
266
  allowPositionals: false,
95
267
  tokens: true,
96
268
  });
97
269
  }
98
270
  const SERVER_ARGS = parseServerArgs(process.argv.slice(2));
99
- function readDeprecatedEnv(name, flag, placeholder, argValue, normalize = (value) => value) {
100
- const value = process.env[name]?.trim() || undefined;
101
- if (!value) {
102
- return undefined;
103
- }
104
- if (argValue === undefined) {
105
- console.error(`[config] ${name} is deprecated; pass ${flag} ${placeholder} as a server argument instead.`);
106
- }
107
- else if (normalize(value) === normalize(argValue)) {
108
- console.error(`[config] ${name} is ignored because ${flag} is given. Remove ${name} from the server env.`);
109
- }
110
- else {
111
- console.error(`[config] ${flag} "${normalize(argValue)}" overrides ${name}="${normalize(value)}". ` +
112
- `Remove ${name} from the server env.`);
113
- }
114
- return value;
115
- }
116
271
  function normalizeProfile(raw) {
117
272
  return (raw ?? '').trim().toLowerCase();
118
273
  }
119
- const ENV_PROFILE = normalizeProfile(readDeprecatedEnv('MYSQL_PROFILE', '--profile', '<label>', SERVER_ARGS.profile, normalizeProfile));
120
- export const MYSQL_PROFILE = SERVER_ARGS.profile ? normalizeProfile(SERVER_ARGS.profile) : ENV_PROFILE;
274
+ export const MYSQL_PROFILE = normalizeProfile(SERVER_ARGS.profile);
275
+ const PROFILE_ENV_WITHOUT_ARG = !SERVER_ARGS.profile && IGNORED_ENV.includes('MYSQL_PROFILE');
121
276
  export function isWriteForbiddenProfile(profile) {
122
277
  return normalizeProfile(profile).startsWith('prod');
123
278
  }
124
- export const IS_WRITE_FORBIDDEN_PROFILE = isWriteForbiddenProfile(MYSQL_PROFILE);
279
+ export const IS_WRITE_FORBIDDEN_PROFILE = isWriteForbiddenProfile(MYSQL_PROFILE) || PROFILE_ENV_WITHOUT_ARG;
280
+ export const WRITE_FORBIDDEN_REASON = isWriteForbiddenProfile(MYSQL_PROFILE)
281
+ ? `write operations are disabled by policy for profile "${MYSQL_PROFILE}". ` +
282
+ `This cannot be enabled through configuration.`
283
+ : PROFILE_ENV_WITHOUT_ARG
284
+ ? 'write operations are disabled because MYSQL_PROFILE is set in the server env without --profile. ' +
285
+ 'The server ignores that env; register the server with --profile <label> instead.'
286
+ : null;
125
287
  export const PROFILE_LABEL = MYSQL_PROFILE ? MYSQL_PROFILE.toUpperCase() : 'UNSPECIFIED';
126
- export const MYSQL_CATALOG_ENABLED = process.env.MYSQL_CATALOG_ENABLED !== 'false';
127
- export const MYSQL_CATALOG_PATH = process.env.MYSQL_CATALOG_PATH?.trim() || undefined;
128
- function parseCatalogTtl(raw) {
129
- if (!raw) {
130
- return 24;
131
- }
132
- const value = Number(raw);
133
- if (!Number.isFinite(value) || value <= 0) {
134
- console.error(`[config] ignoring MYSQL_CATALOG_TTL_HOURS="${raw}": expected a positive number; using 24.`);
135
- return 24;
136
- }
137
- return value;
288
+ export function startupFailureMessage(error) {
289
+ const reason = error instanceof Error ? error.message : String(error);
290
+ const notice = ignoredEnvNotice();
291
+ return `[startup] fatal error for profile ${PROFILE_LABEL}: ${reason}` + (notice ? ` (${notice})` : '');
138
292
  }
139
- export const MYSQL_CATALOG_TTL_HOURS = parseCatalogTtl(process.env.MYSQL_CATALOG_TTL_HOURS);
140
- export const ENABLE_LOGGING = process.env.ENABLE_LOGGING === 'true' || process.env.ENABLE_LOGGING === '1';
293
+ export const MYSQL_CATALOG_ENABLED = !SERVER_ARGS.noCatalog;
294
+ export const MYSQL_CATALOG_PATH = SERVER_ARGS.catalogPath;
295
+ export const MYSQL_CATALOG_TTL_HOURS = SERVER_ARGS.catalogTtl ?? 24;
296
+ export const ENABLE_LOGGING = SERVER_ARGS.log;
141
297
  export const PACKAGE_VERSION = readPackageVersion(path.dirname(fileURLToPath(import.meta.url))) ?? 'unknown';
142
- export const MYSQL_DB = process.env.MYSQL_DB?.trim() || undefined;
143
- const envFlag = (name) => process.env[name] === 'true';
144
- const writeFlag = (name) => (IS_WRITE_FORBIDDEN_PROFILE ? false : envFlag(name));
298
+ export const MYSQL_DB = SERVER_ARGS.db;
299
+ const writeFlag = (requested) => (IS_WRITE_FORBIDDEN_PROFILE ? false : requested);
145
300
  if (IS_WRITE_FORBIDDEN_PROFILE) {
146
301
  const requested = [
147
- ...['ALLOW_INSERT_OPERATION', 'ALLOW_UPDATE_OPERATION', 'ALLOW_DELETE_OPERATION', 'ALLOW_DDL_OPERATION'].filter(envFlag),
148
- ...[
149
- 'SCHEMA_INSERT_PERMISSIONS',
150
- 'SCHEMA_UPDATE_PERMISSIONS',
151
- 'SCHEMA_DELETE_PERMISSIONS',
152
- 'SCHEMA_DDL_PERMISSIONS',
153
- ].filter((name) => Boolean(process.env[name]?.trim())),
154
- ];
302
+ SERVER_ARGS.allowInsert && '--allow-insert',
303
+ SERVER_ARGS.allowUpdate && '--allow-update',
304
+ SERVER_ARGS.allowDelete && '--allow-delete',
305
+ SERVER_ARGS.allowDdl && '--allow-ddl',
306
+ SERVER_ARGS.schemaInsert && '--schema-insert',
307
+ SERVER_ARGS.schemaUpdate && '--schema-update',
308
+ SERVER_ARGS.schemaDelete && '--schema-delete',
309
+ SERVER_ARGS.schemaDdl && '--schema-ddl',
310
+ ].filter((name) => Boolean(name));
155
311
  if (requested.length > 0) {
156
- console.error(`[config] profile "${MYSQL_PROFILE}" is read-only by policy; ignoring ${requested.join(', ')}.`);
157
- }
158
- }
159
- export const ALLOW_INSERT_OPERATION = writeFlag('ALLOW_INSERT_OPERATION');
160
- export const ALLOW_UPDATE_OPERATION = writeFlag('ALLOW_UPDATE_OPERATION');
161
- export const ALLOW_DELETE_OPERATION = writeFlag('ALLOW_DELETE_OPERATION');
162
- export const ALLOW_DDL_OPERATION = writeFlag('ALLOW_DDL_OPERATION');
163
- export const MYSQL_DISABLE_READ_ONLY_TRANSACTIONS = process.env.MYSQL_DISABLE_READ_ONLY_TRANSACTIONS === 'true';
164
- function parsePositiveInt(name, raw, fallback) {
165
- if (!raw) {
166
- return fallback;
167
- }
168
- const value = Number(raw);
169
- if (!Number.isFinite(value) || value < 1) {
170
- console.error(`[config] ignoring ${name}="${raw}": expected a positive integer; using ${fallback}.`);
171
- return fallback;
172
- }
173
- return Math.floor(value);
174
- }
175
- function parsePortEnv(name, raw) {
176
- const trimmed = raw?.trim();
177
- if (!trimmed) {
178
- return undefined;
179
- }
180
- const port = Number(trimmed);
181
- if (!Number.isInteger(port) || port < 0 || port > 65535) {
182
- console.error(`[config] ignoring ${name}="${raw}": expected an integer between 0 and 65535.`);
183
- return undefined;
312
+ const why = PROFILE_ENV_WITHOUT_ARG
313
+ ? 'writes stay disabled because MYSQL_PROFILE is set without --profile'
314
+ : `profile "${MYSQL_PROFILE}" is read-only by policy`;
315
+ console.error(`[config] ${why}; ignoring ${requested.join(', ')}.`);
184
316
  }
185
- return port;
186
317
  }
187
- export const MYSQL_MAX_TIMEOUT_SECONDS = parsePositiveInt('MYSQL_MAX_TIMEOUT_SECONDS', process.env.MYSQL_MAX_TIMEOUT_SECONDS, 30);
318
+ export const ALLOW_INSERT_OPERATION = writeFlag(SERVER_ARGS.allowInsert);
319
+ export const ALLOW_UPDATE_OPERATION = writeFlag(SERVER_ARGS.allowUpdate);
320
+ export const ALLOW_DELETE_OPERATION = writeFlag(SERVER_ARGS.allowDelete);
321
+ export const ALLOW_DDL_OPERATION = writeFlag(SERVER_ARGS.allowDdl);
322
+ export const MYSQL_DISABLE_READ_ONLY_TRANSACTIONS = SERVER_ARGS.noReadOnlyTransactions;
323
+ export const MYSQL_MAX_TIMEOUT_SECONDS = SERVER_ARGS.maxTimeout ?? 30;
188
324
  export const MYSQL_DEFAULT_TIMEOUT_SECONDS = Math.min(10, MYSQL_MAX_TIMEOUT_SECONDS);
189
- export const MYSQL_CATALOG_TIMEOUT_SECONDS = parsePositiveInt('MYSQL_CATALOG_TIMEOUT_SECONDS', process.env.MYSQL_CATALOG_TIMEOUT_SECONDS, 60);
190
- export const MAX_RESPONSE_ROWS = parsePositiveInt('MYSQL_MAX_RESPONSE_ROWS', process.env.MYSQL_MAX_RESPONSE_ROWS, 5000);
191
- export const MYSQL_POOL_SIZE = parsePositiveInt('MYSQL_POOL_SIZE', process.env.MYSQL_POOL_SIZE, 10);
192
- export const MYSQL_QUEUE_LIMIT = parsePositiveInt('MYSQL_QUEUE_LIMIT', process.env.MYSQL_QUEUE_LIMIT, 100);
193
- export const MYSQL_CONNECT_TIMEOUT = parsePositiveInt('MYSQL_CONNECT_TIMEOUT', process.env.MYSQL_CONNECT_TIMEOUT, 10000);
194
- export const MYSQL_SOCKET_PATH = process.env.MYSQL_SOCKET_PATH?.trim() || undefined;
195
- export const MYSQL_HOST = process.env.MYSQL_HOST?.trim() || undefined;
196
- export const MYSQL_PORT = parsePortEnv('MYSQL_PORT', process.env.MYSQL_PORT) ?? 3306;
325
+ export const MYSQL_CATALOG_TIMEOUT_SECONDS = SERVER_ARGS.catalogTimeout ?? 60;
326
+ export const MAX_RESPONSE_ROWS = SERVER_ARGS.maxRows ?? 5000;
327
+ export const MYSQL_POOL_SIZE = SERVER_ARGS.poolSize ?? 10;
328
+ export const MYSQL_QUEUE_LIMIT = SERVER_ARGS.queueLimit ?? 100;
329
+ export const MYSQL_CONNECT_TIMEOUT = SERVER_ARGS.connectTimeout ?? 10000;
330
+ export const MYSQL_SOCKET_PATH = SERVER_ARGS.socketPath;
331
+ export const MYSQL_HOST = SERVER_ARGS.host;
332
+ export const MYSQL_PORT = SERVER_ARGS.port ?? 3306;
197
333
  export const DEFAULT_MYSQL_HOST = '127.0.0.1';
198
- export const MYSQL_SSL_ENABLED = process.env.MYSQL_SSL === 'true';
199
- export const MYSQL_SSL_REJECT_UNAUTHORIZED = process.env.MYSQL_SSL_REJECT_UNAUTHORIZED === 'true';
200
- export const MYSQL_SSL_CA_PATH = process.env.MYSQL_SSL_CA?.trim() || undefined;
201
- export const MYSQL_SSL_CERT_PATH = process.env.MYSQL_SSL_CERT?.trim() || undefined;
202
- export const MYSQL_SSL_KEY_PATH = process.env.MYSQL_SSL_KEY?.trim() || undefined;
203
- export const MYSQL_TIMEZONE = process.env.MYSQL_TIMEZONE?.trim() || undefined;
204
- export const MYSQL_DATE_STRINGS = process.env.MYSQL_DATE_STRINGS === 'true';
205
- export const MYSQL_BIG_NUMBER_STRINGS = process.env.MYSQL_BIG_NUMBER_STRINGS === 'true';
206
- export const SSH_REUSE_EXISTING = process.env.MYSQL_SSH_REUSE_EXISTING === 'true';
207
- const ENV_SSH_CONFIG_HOST = readDeprecatedEnv('MYSQL_SSH_CONFIG_HOST', '--ssh-config-host', '<alias>', SERVER_ARGS.sshConfigHost);
208
- export const SSH_CONFIG_HOST = SERVER_ARGS.sshConfigHost ?? ENV_SSH_CONFIG_HOST;
209
- export const SSH_CONFIG_HOST_SOURCE = SERVER_ARGS.sshConfigHost ? '--ssh-config-host' : ENV_SSH_CONFIG_HOST ? 'MYSQL_SSH_CONFIG_HOST' : undefined;
210
- export const SSH_HOST = process.env.MYSQL_SSH_HOST?.trim() || undefined;
211
- export const SSH_USER = process.env.MYSQL_SSH_USER?.trim() || undefined;
212
- export const SSH_PORT = parsePortEnv('MYSQL_SSH_PORT', process.env.MYSQL_SSH_PORT);
213
- export const SSH_PRIVATE_KEY_PATH = process.env.MYSQL_SSH_PRIVATE_KEY_PATH?.trim() || undefined;
334
+ export const MYSQL_SSL_ENABLED = SERVER_ARGS.ssl;
335
+ export const MYSQL_SSL_REJECT_UNAUTHORIZED = SERVER_ARGS.sslRejectUnauthorized;
336
+ export const MYSQL_SSL_CA_PATH = SERVER_ARGS.sslCa;
337
+ export const MYSQL_SSL_CERT_PATH = SERVER_ARGS.sslCert;
338
+ export const MYSQL_SSL_KEY_PATH = SERVER_ARGS.sslKey;
339
+ export const MYSQL_TIMEZONE = SERVER_ARGS.timezone;
340
+ export const MYSQL_DATE_STRINGS = SERVER_ARGS.dateStrings;
341
+ export const MYSQL_BIG_NUMBER_STRINGS = SERVER_ARGS.bigNumberStrings;
342
+ export const SSH_HOST = SERVER_ARGS.sshHost;
343
+ export const SSH_USER = SERVER_ARGS.sshUser;
344
+ export const SSH_PORT = SERVER_ARGS.sshPort;
345
+ export const SSH_PRIVATE_KEY_PATH = SERVER_ARGS.sshPrivateKeyPath;
214
346
  export const SSH_PASSPHRASE = process.env.MYSQL_SSH_PASSPHRASE?.trim() || undefined;
215
- export const SSH_LOCAL_PORT = parsePortEnv('MYSQL_SSH_LOCAL_PORT', process.env.MYSQL_SSH_LOCAL_PORT);
216
- export const SSH_ENABLED = Boolean(SSH_CONFIG_HOST || SSH_HOST);
217
- const schemaPermissions = (name) => IS_WRITE_FORBIDDEN_PROFILE ? {} : parseSchemaPermissions(process.env[name]);
218
- export const SCHEMA_INSERT_PERMISSIONS = schemaPermissions('SCHEMA_INSERT_PERMISSIONS');
219
- export const SCHEMA_UPDATE_PERMISSIONS = schemaPermissions('SCHEMA_UPDATE_PERMISSIONS');
220
- export const SCHEMA_DELETE_PERMISSIONS = schemaPermissions('SCHEMA_DELETE_PERMISSIONS');
221
- export const SCHEMA_DDL_PERMISSIONS = schemaPermissions('SCHEMA_DDL_PERMISSIONS');
347
+ export const SSH_ENABLED = Boolean(SSH_HOST);
348
+ const schemaPermissions = (requested) => IS_WRITE_FORBIDDEN_PROFILE ? {} : (requested ?? {});
349
+ export const SCHEMA_INSERT_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaInsert);
350
+ export const SCHEMA_UPDATE_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaUpdate);
351
+ export const SCHEMA_DELETE_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaDelete);
352
+ export const SCHEMA_DDL_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaDdl);
222
353
  export const isMultiDbMode = !MYSQL_DB;
223
354
  const MYSQL_PASS = process.env.MYSQL_PASS ?? '';
224
355
  export const mcpConfig = {
@@ -1,6 +1,6 @@
1
1
  import { performance } from 'perf_hooks';
2
2
  import * as mysql2 from 'mysql2/promise';
3
- import { mcpConfig as config, describeConfiguredTarget, SSH_ENABLED, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, MYSQL_DISABLE_READ_ONLY_TRANSACTIONS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MYSQL_CATALOG_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, } from './../config/index.js';
3
+ import { mcpConfig as config, describeConfiguredTarget, SSH_ENABLED, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, WRITE_FORBIDDEN_REASON, ignoredEnvSummary, MYSQL_DISABLE_READ_ONLY_TRANSACTIONS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MYSQL_CATALOG_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, } from './../config/index.js';
4
4
  import { isDDLAllowedForSchema, isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, } from './permissions.js';
5
5
  import { DDL_STATEMENT_TYPES, extractReferencedSchemas, findFileExport, findLimitOverrideHint, findUnsupportedStatementType, getQueryTypes, hasExecutableComment, isUnparseableIntrospection, extractQualifiers, } from './utils.js';
6
6
  import { isQueryTimeoutError, parseExplainPayload, renderTimeoutDiagnostic } from './diagnose.js';
@@ -66,9 +66,7 @@ const getPool = () => {
66
66
  });
67
67
  });
68
68
  log('info', `MySQL pool created successfully (profile: ${PROFILE_LABEL}` +
69
- (endpoint
70
- ? `, via ${endpoint.reused ? 'reused' : 'new'} tunnel ${endpoint.host}:${endpoint.port}`
71
- : '') +
69
+ (endpoint ? `, via tunnel ${endpoint.host}:${endpoint.port}` : '') +
72
70
  ')');
73
71
  return pool;
74
72
  })();
@@ -106,7 +104,7 @@ function assertTunnelHealthy() {
106
104
  function describeConnection() {
107
105
  const endpoint = getTunnelEndpoint();
108
106
  if (endpoint) {
109
- return `${endpoint.host}:${endpoint.port} ` + `(${endpoint.reused ? 'reused' : 'new'} ssh tunnel)`;
107
+ return `${endpoint.host}:${endpoint.port} (ssh tunnel)`;
110
108
  }
111
109
  const target = describeConfiguredTarget();
112
110
  return SSH_ENABLED ? `${target} (via ssh tunnel, not yet established)` : target;
@@ -128,6 +126,10 @@ function profileBanner() {
128
126
  if (tunnel) {
129
127
  parts.push(tunnel);
130
128
  }
129
+ const ignored = ignoredEnvSummary();
130
+ if (ignored) {
131
+ parts.push(ignored);
132
+ }
131
133
  return `[${parts.join(' | ')}]`;
132
134
  }
133
135
  async function executeQuery(sql, params = []) {
@@ -160,13 +162,12 @@ async function executeQuery(sql, params = []) {
160
162
  async function executeWriteQuery(sql) {
161
163
  let connection;
162
164
  if (IS_WRITE_FORBIDDEN_PROFILE) {
163
- log('error', `Refusing write operation: profile "${MYSQL_PROFILE}" is read-only by policy.`);
165
+ log('error', `Refusing write operation: ${WRITE_FORBIDDEN_REASON}`);
164
166
  return {
165
167
  content: [
166
168
  {
167
169
  type: 'text',
168
- text: `${profileBanner()} Error: write operations are disabled by policy for profile "${MYSQL_PROFILE}". ` +
169
- `This cannot be enabled through configuration.`,
170
+ text: `${profileBanner()} Error: ${WRITE_FORBIDDEN_REASON}`,
170
171
  },
171
172
  ],
172
173
  isError: true,
@@ -393,6 +394,13 @@ async function executeReadOnlyQuery(sql, options = {}) {
393
394
  { enabled: isDeleteOperation, label: 'DELETE', allowed: isDeleteAllowedForSchema },
394
395
  { enabled: isDDLOperation, label: 'DDL', allowed: isDDLAllowedForSchema },
395
396
  ].filter((check) => check.enabled);
397
+ if (writeChecks.length > 0 && IS_WRITE_FORBIDDEN_PROFILE) {
398
+ log('error', `Refusing write operation: ${WRITE_FORBIDDEN_REASON}`);
399
+ return {
400
+ content: [{ type: 'text', text: `Error: ${WRITE_FORBIDDEN_REASON}` }],
401
+ isError: true,
402
+ };
403
+ }
396
404
  if (writeChecks.length > 0) {
397
405
  const schemas = extractReferencedSchemas(sql);
398
406
  for (const check of writeChecks) {
@@ -401,7 +409,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
401
409
  continue;
402
410
  }
403
411
  const target = schemas ? (schemas[deniedIndex] ?? 'default') : 'unknown';
404
- const setting = `SCHEMA_${check.label}_PERMISSIONS`;
412
+ const setting = `--schema-${check.label.toLowerCase()}`;
405
413
  log('error', `${check.label} operations are not allowed for schema '${target}'. Configure ${setting}.`);
406
414
  return {
407
415
  content: [
@@ -427,7 +435,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
427
435
  await connection.query('START TRANSACTION READ ONLY');
428
436
  }
429
437
  else {
430
- log('info', 'Read-only transactions disabled via MYSQL_DISABLE_READ_ONLY_TRANSACTIONS=true');
438
+ log('info', 'Read-only transactions disabled via --no-read-only-transactions');
431
439
  await connection.beginTransaction();
432
440
  }
433
441
  roundTrips += 1;
@@ -460,7 +468,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
460
468
  `the query matched more. This is NOT the complete result - do not count, sum, or ` +
461
469
  `conclude anything about totals from it. Add a narrower WHERE, an aggregate ` +
462
470
  `(COUNT/SUM/GROUP BY), or paginate with ORDER BY + LIMIT/OFFSET. Raising the cap ` +
463
- `is an operator change (MYSQL_MAX_RESPONSE_ROWS), not something to retry around.`,
471
+ `is an operator change (--max-rows), not something to retry around.`,
464
472
  },
465
473
  ]
466
474
  : []),