@ecubelabs/mysql-mcp 1.1.0 → 2.0.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +245 -452
- package/dist/index.js +11 -11
- package/dist/src/config/index.js +265 -131
- package/dist/src/db/index.js +30 -13
- package/dist/src/db/permissions.js +4 -1
- package/dist/src/ssh/config.js +0 -135
- package/dist/src/ssh/known-hosts.js +1 -4
- package/dist/src/ssh/tunnel.js +26 -97
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,8 +5,8 @@ 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
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, 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';
|
|
8
|
+
import { describeWriteCapabilities, 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, 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,10 +24,13 @@ 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
|
-
|
|
30
|
-
baseToolDescription += ` with support for: ${supported.join(', ')} and READ operations`;
|
|
33
|
+
baseToolDescription += ` with support for: ${describeWriteCapabilities(writes)} and READ operations`;
|
|
31
34
|
if (Object.keys(SCHEMA_INSERT_PERMISSIONS).length > 0 ||
|
|
32
35
|
Object.keys(SCHEMA_UPDATE_PERMISSIONS).length > 0 ||
|
|
33
36
|
Object.keys(SCHEMA_DELETE_PERMISSIONS).length > 0 ||
|
|
@@ -208,7 +211,7 @@ export default function createMcpServer() {
|
|
|
208
211
|
})()
|
|
209
212
|
: typeof mysqlSettings.socketPath === 'string'
|
|
210
213
|
? JSON.stringify(['unix', mysqlSettings.socketPath])
|
|
211
|
-
: JSON.stringify(['tcp', String(mysqlSettings.host
|
|
214
|
+
: JSON.stringify(['tcp', String(mysqlSettings.host), Number(mysqlSettings.port)]);
|
|
212
215
|
const identity = catalogIdentity({
|
|
213
216
|
profile: MYSQL_PROFILE,
|
|
214
217
|
target: catalogTarget,
|
|
@@ -569,8 +572,7 @@ export default function createMcpServer() {
|
|
|
569
572
|
if (SSH_ENABLED) {
|
|
570
573
|
log('info', 'Opening SSH tunnel before connecting to MySQL...');
|
|
571
574
|
const endpoint = await ensureTunnel();
|
|
572
|
-
log('info', `SSH tunnel ready on ${endpoint?.host}:${endpoint?.port}`
|
|
573
|
-
(endpoint?.reused ? ' (reused an existing forward)' : ''));
|
|
575
|
+
log('info', `SSH tunnel ready on ${endpoint?.host}:${endpoint?.port}`);
|
|
574
576
|
}
|
|
575
577
|
log('info', 'Attempting to test database connection...');
|
|
576
578
|
const pool = await getPool();
|
|
@@ -580,8 +582,7 @@ export default function createMcpServer() {
|
|
|
580
582
|
catalog.startInventory();
|
|
581
583
|
}
|
|
582
584
|
catch (error) {
|
|
583
|
-
console.error(
|
|
584
|
-
(error instanceof Error ? error.message : String(error)));
|
|
585
|
+
console.error(startupFailureMessage(error));
|
|
585
586
|
log('error', 'Fatal error during server startup:', error);
|
|
586
587
|
await stopTunnel();
|
|
587
588
|
process.exit(1);
|
|
@@ -665,8 +666,7 @@ if (isMainModule()) {
|
|
|
665
666
|
log('info', 'Server started and listening on stdio');
|
|
666
667
|
}
|
|
667
668
|
catch (error) {
|
|
668
|
-
console.error(
|
|
669
|
-
(error instanceof Error ? error.message : String(error)));
|
|
669
|
+
console.error(startupFailureMessage(error));
|
|
670
670
|
log('error', 'Server error:', error);
|
|
671
671
|
process.exit(1);
|
|
672
672
|
}
|
package/dist/src/config/index.js
CHANGED
|
@@ -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
|
-
|
|
69
|
-
|
|
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,169 @@ export function parseServerArgs(argv) {
|
|
|
78
190
|
}
|
|
79
191
|
seen.add(token.name);
|
|
80
192
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
193
|
+
const values = parsed.values;
|
|
194
|
+
const text = (name) => {
|
|
195
|
+
const value = values[name];
|
|
196
|
+
return typeof value === 'string' ? value.trim() || undefined : undefined;
|
|
84
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'),
|
|
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
|
+
else {
|
|
245
|
+
const missing = ['host', 'port'].filter((name) => text(name) === undefined);
|
|
246
|
+
if (missing.length > 0) {
|
|
247
|
+
violations.push(`${missing.map((name) => `--${name}`).join(' and ')} ${missing.length > 1 ? 'are' : 'is'} ` +
|
|
248
|
+
'required unless --socket-path is given');
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (!args.sshHost) {
|
|
252
|
+
const orphans = SSH_DEPENDENT_ARGS.filter((name) => text(name) !== undefined);
|
|
253
|
+
if (orphans.length > 0) {
|
|
254
|
+
violations.push(`${orphans.map((name) => `--${name}`).join(', ')} requires --ssh-host`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
else if (!args.sshUser) {
|
|
258
|
+
violations.push('--ssh-host requires --ssh-user');
|
|
259
|
+
}
|
|
260
|
+
if (violations.length > 0) {
|
|
261
|
+
throw new Error(`invalid server arguments: ${violations.join('; ')}.`);
|
|
262
|
+
}
|
|
263
|
+
return args;
|
|
85
264
|
}
|
|
86
265
|
function parseServerArgv(argv) {
|
|
87
266
|
return parseArgs({
|
|
88
267
|
args: [...argv],
|
|
89
|
-
options:
|
|
90
|
-
profile: { type: 'string' },
|
|
91
|
-
'ssh-config-host': { type: 'string' },
|
|
92
|
-
},
|
|
268
|
+
options: SERVER_ARG_OPTIONS,
|
|
93
269
|
strict: true,
|
|
94
270
|
allowPositionals: false,
|
|
95
271
|
tokens: true,
|
|
96
272
|
});
|
|
97
273
|
}
|
|
98
274
|
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
275
|
function normalizeProfile(raw) {
|
|
117
276
|
return (raw ?? '').trim().toLowerCase();
|
|
118
277
|
}
|
|
119
|
-
const
|
|
120
|
-
|
|
278
|
+
export const MYSQL_PROFILE = normalizeProfile(SERVER_ARGS.profile);
|
|
279
|
+
const PROFILE_ENV_WITHOUT_ARG = !SERVER_ARGS.profile && IGNORED_ENV.includes('MYSQL_PROFILE');
|
|
121
280
|
export function isWriteForbiddenProfile(profile) {
|
|
122
281
|
return normalizeProfile(profile).startsWith('prod');
|
|
123
282
|
}
|
|
124
|
-
export const IS_WRITE_FORBIDDEN_PROFILE = isWriteForbiddenProfile(MYSQL_PROFILE);
|
|
283
|
+
export const IS_WRITE_FORBIDDEN_PROFILE = isWriteForbiddenProfile(MYSQL_PROFILE) || PROFILE_ENV_WITHOUT_ARG;
|
|
284
|
+
export const WRITE_FORBIDDEN_REASON = isWriteForbiddenProfile(MYSQL_PROFILE)
|
|
285
|
+
? `write operations are disabled by policy for profile "${MYSQL_PROFILE}". ` +
|
|
286
|
+
`This cannot be enabled through configuration.`
|
|
287
|
+
: PROFILE_ENV_WITHOUT_ARG
|
|
288
|
+
? 'write operations are disabled because MYSQL_PROFILE is set in the server env without --profile. ' +
|
|
289
|
+
'The server ignores that env; register the server with --profile <label> instead.'
|
|
290
|
+
: null;
|
|
125
291
|
export const PROFILE_LABEL = MYSQL_PROFILE ? MYSQL_PROFILE.toUpperCase() : 'UNSPECIFIED';
|
|
126
|
-
export
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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;
|
|
292
|
+
export function startupFailureMessage(error) {
|
|
293
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
294
|
+
const notice = ignoredEnvNotice();
|
|
295
|
+
return `[startup] fatal error for profile ${PROFILE_LABEL}: ${reason}` + (notice ? ` (${notice})` : '');
|
|
138
296
|
}
|
|
139
|
-
export const
|
|
140
|
-
export const
|
|
297
|
+
export const MYSQL_CATALOG_ENABLED = !SERVER_ARGS.noCatalog;
|
|
298
|
+
export const MYSQL_CATALOG_PATH = SERVER_ARGS.catalogPath;
|
|
299
|
+
export const MYSQL_CATALOG_TTL_HOURS = SERVER_ARGS.catalogTtl ?? 24;
|
|
300
|
+
export const ENABLE_LOGGING = SERVER_ARGS.log;
|
|
141
301
|
export const PACKAGE_VERSION = readPackageVersion(path.dirname(fileURLToPath(import.meta.url))) ?? 'unknown';
|
|
142
|
-
export const MYSQL_DB =
|
|
143
|
-
const
|
|
144
|
-
const writeFlag = (name) => (IS_WRITE_FORBIDDEN_PROFILE ? false : envFlag(name));
|
|
302
|
+
export const MYSQL_DB = SERVER_ARGS.db;
|
|
303
|
+
const writeFlag = (requested) => (IS_WRITE_FORBIDDEN_PROFILE ? false : requested);
|
|
145
304
|
if (IS_WRITE_FORBIDDEN_PROFILE) {
|
|
146
305
|
const requested = [
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
306
|
+
SERVER_ARGS.allowInsert && '--allow-insert',
|
|
307
|
+
SERVER_ARGS.allowUpdate && '--allow-update',
|
|
308
|
+
SERVER_ARGS.allowDelete && '--allow-delete',
|
|
309
|
+
SERVER_ARGS.allowDdl && '--allow-ddl',
|
|
310
|
+
SERVER_ARGS.schemaInsert && '--schema-insert',
|
|
311
|
+
SERVER_ARGS.schemaUpdate && '--schema-update',
|
|
312
|
+
SERVER_ARGS.schemaDelete && '--schema-delete',
|
|
313
|
+
SERVER_ARGS.schemaDdl && '--schema-ddl',
|
|
314
|
+
].filter((name) => Boolean(name));
|
|
155
315
|
if (requested.length > 0) {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
}
|
|
159
|
-
|
|
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;
|
|
316
|
+
const why = PROFILE_ENV_WITHOUT_ARG
|
|
317
|
+
? 'writes stay disabled because MYSQL_PROFILE is set without --profile'
|
|
318
|
+
: `profile "${MYSQL_PROFILE}" is read-only by policy`;
|
|
319
|
+
console.error(`[config] ${why}; ignoring ${requested.join(', ')}.`);
|
|
184
320
|
}
|
|
185
|
-
return port;
|
|
186
321
|
}
|
|
187
|
-
export const
|
|
322
|
+
export const ALLOW_INSERT_OPERATION = writeFlag(SERVER_ARGS.allowInsert);
|
|
323
|
+
export const ALLOW_UPDATE_OPERATION = writeFlag(SERVER_ARGS.allowUpdate);
|
|
324
|
+
export const ALLOW_DELETE_OPERATION = writeFlag(SERVER_ARGS.allowDelete);
|
|
325
|
+
export const ALLOW_DDL_OPERATION = writeFlag(SERVER_ARGS.allowDdl);
|
|
326
|
+
export const MYSQL_DISABLE_READ_ONLY_TRANSACTIONS = SERVER_ARGS.noReadOnlyTransactions;
|
|
327
|
+
export const MYSQL_MAX_TIMEOUT_SECONDS = SERVER_ARGS.maxTimeout ?? 30;
|
|
188
328
|
export const MYSQL_DEFAULT_TIMEOUT_SECONDS = Math.min(10, MYSQL_MAX_TIMEOUT_SECONDS);
|
|
189
|
-
export const MYSQL_CATALOG_TIMEOUT_SECONDS =
|
|
190
|
-
export const MAX_RESPONSE_ROWS =
|
|
191
|
-
export const MYSQL_POOL_SIZE =
|
|
192
|
-
export const MYSQL_QUEUE_LIMIT =
|
|
193
|
-
export const MYSQL_CONNECT_TIMEOUT =
|
|
194
|
-
export const MYSQL_SOCKET_PATH =
|
|
195
|
-
export const MYSQL_HOST =
|
|
196
|
-
export const MYSQL_PORT =
|
|
197
|
-
export const
|
|
198
|
-
export const
|
|
199
|
-
export const
|
|
200
|
-
export const
|
|
201
|
-
export const
|
|
202
|
-
export const
|
|
203
|
-
export const
|
|
204
|
-
export const
|
|
205
|
-
export const
|
|
206
|
-
export const
|
|
207
|
-
const
|
|
208
|
-
export const
|
|
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;
|
|
329
|
+
export const MYSQL_CATALOG_TIMEOUT_SECONDS = SERVER_ARGS.catalogTimeout ?? 60;
|
|
330
|
+
export const MAX_RESPONSE_ROWS = SERVER_ARGS.maxRows ?? 5000;
|
|
331
|
+
export const MYSQL_POOL_SIZE = SERVER_ARGS.poolSize ?? 10;
|
|
332
|
+
export const MYSQL_QUEUE_LIMIT = SERVER_ARGS.queueLimit ?? 100;
|
|
333
|
+
export const MYSQL_CONNECT_TIMEOUT = SERVER_ARGS.connectTimeout ?? 10000;
|
|
334
|
+
export const MYSQL_SOCKET_PATH = SERVER_ARGS.socketPath;
|
|
335
|
+
export const MYSQL_HOST = SERVER_ARGS.host;
|
|
336
|
+
export const MYSQL_PORT = SERVER_ARGS.port;
|
|
337
|
+
export const MYSQL_SSL_ENABLED = SERVER_ARGS.ssl;
|
|
338
|
+
export const MYSQL_SSL_REJECT_UNAUTHORIZED = SERVER_ARGS.sslRejectUnauthorized;
|
|
339
|
+
export const MYSQL_SSL_CA_PATH = SERVER_ARGS.sslCa;
|
|
340
|
+
export const MYSQL_SSL_CERT_PATH = SERVER_ARGS.sslCert;
|
|
341
|
+
export const MYSQL_SSL_KEY_PATH = SERVER_ARGS.sslKey;
|
|
342
|
+
export const MYSQL_TIMEZONE = SERVER_ARGS.timezone;
|
|
343
|
+
export const MYSQL_DATE_STRINGS = SERVER_ARGS.dateStrings;
|
|
344
|
+
export const MYSQL_BIG_NUMBER_STRINGS = SERVER_ARGS.bigNumberStrings;
|
|
345
|
+
export const SSH_HOST = SERVER_ARGS.sshHost;
|
|
346
|
+
export const SSH_USER = SERVER_ARGS.sshUser;
|
|
347
|
+
export const SSH_PORT = SERVER_ARGS.sshPort;
|
|
348
|
+
export const SSH_PRIVATE_KEY_PATH = SERVER_ARGS.sshPrivateKeyPath;
|
|
214
349
|
export const SSH_PASSPHRASE = process.env.MYSQL_SSH_PASSPHRASE?.trim() || undefined;
|
|
215
|
-
export const
|
|
216
|
-
|
|
217
|
-
const
|
|
218
|
-
export const
|
|
219
|
-
export const
|
|
220
|
-
export const
|
|
221
|
-
export const SCHEMA_DDL_PERMISSIONS = schemaPermissions('SCHEMA_DDL_PERMISSIONS');
|
|
350
|
+
export const SSH_ENABLED = Boolean(SSH_HOST);
|
|
351
|
+
const schemaPermissions = (requested) => IS_WRITE_FORBIDDEN_PROFILE ? {} : (requested ?? {});
|
|
352
|
+
export const SCHEMA_INSERT_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaInsert);
|
|
353
|
+
export const SCHEMA_UPDATE_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaUpdate);
|
|
354
|
+
export const SCHEMA_DELETE_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaDelete);
|
|
355
|
+
export const SCHEMA_DDL_PERMISSIONS = schemaPermissions(SERVER_ARGS.schemaDdl);
|
|
222
356
|
export const isMultiDbMode = !MYSQL_DB;
|
|
223
357
|
const MYSQL_PASS = process.env.MYSQL_PASS ?? '';
|
|
224
358
|
export const mcpConfig = {
|
|
@@ -226,7 +360,7 @@ export const mcpConfig = {
|
|
|
226
360
|
...(MYSQL_SOCKET_PATH
|
|
227
361
|
? { socketPath: MYSQL_SOCKET_PATH }
|
|
228
362
|
: {
|
|
229
|
-
host: MYSQL_HOST
|
|
363
|
+
host: MYSQL_HOST,
|
|
230
364
|
port: MYSQL_PORT,
|
|
231
365
|
}),
|
|
232
366
|
user: process.env.MYSQL_USER?.trim() || 'root',
|
|
@@ -257,6 +391,6 @@ export const mcpConfig = {
|
|
|
257
391
|
},
|
|
258
392
|
};
|
|
259
393
|
export function describeConfiguredTarget() {
|
|
260
|
-
return MYSQL_SOCKET_PATH ? `socket: ${MYSQL_SOCKET_PATH}` : `${MYSQL_HOST
|
|
394
|
+
return MYSQL_SOCKET_PATH ? `socket: ${MYSQL_SOCKET_PATH}` : `${MYSQL_HOST}:${MYSQL_PORT}`;
|
|
261
395
|
}
|
|
262
396
|
export { readCACertificate, readSSLFile };
|
package/dist/src/db/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { performance } from 'perf_hooks';
|
|
2
2
|
import * as mysql2 from 'mysql2/promise';
|
|
3
|
-
import { mcpConfig as config, describeConfiguredTarget, SSH_ENABLED,
|
|
4
|
-
import { isDDLAllowedForSchema, isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, } from './permissions.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
|
+
import { isDDLAllowedForSchema, isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, describeWriteCapabilities, writeCapabilities, } 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';
|
|
7
7
|
import { log } from './../utils/index.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}
|
|
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;
|
|
@@ -117,7 +115,16 @@ function setCodeBranchSource(source) {
|
|
|
117
115
|
}
|
|
118
116
|
function profileBanner() {
|
|
119
117
|
const parts = [`profile: ${PROFILE_LABEL}`];
|
|
120
|
-
|
|
118
|
+
const writes = writeCapabilities();
|
|
119
|
+
if (IS_WRITE_FORBIDDEN_PROFILE) {
|
|
120
|
+
parts.push('READ-ONLY (enforced)');
|
|
121
|
+
}
|
|
122
|
+
else if (writes.length > 0) {
|
|
123
|
+
parts.push(`writes: ${describeWriteCapabilities(writes)}`);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
parts.push('read-only');
|
|
127
|
+
}
|
|
121
128
|
const db = config.mysql.database || 'multi-db';
|
|
122
129
|
parts.push(`database: ${db}`);
|
|
123
130
|
const branch = codeBranchSource?.();
|
|
@@ -128,6 +135,10 @@ function profileBanner() {
|
|
|
128
135
|
if (tunnel) {
|
|
129
136
|
parts.push(tunnel);
|
|
130
137
|
}
|
|
138
|
+
const ignored = ignoredEnvSummary();
|
|
139
|
+
if (ignored) {
|
|
140
|
+
parts.push(ignored);
|
|
141
|
+
}
|
|
131
142
|
return `[${parts.join(' | ')}]`;
|
|
132
143
|
}
|
|
133
144
|
async function executeQuery(sql, params = []) {
|
|
@@ -160,13 +171,12 @@ async function executeQuery(sql, params = []) {
|
|
|
160
171
|
async function executeWriteQuery(sql) {
|
|
161
172
|
let connection;
|
|
162
173
|
if (IS_WRITE_FORBIDDEN_PROFILE) {
|
|
163
|
-
log('error', `Refusing write operation:
|
|
174
|
+
log('error', `Refusing write operation: ${WRITE_FORBIDDEN_REASON}`);
|
|
164
175
|
return {
|
|
165
176
|
content: [
|
|
166
177
|
{
|
|
167
178
|
type: 'text',
|
|
168
|
-
text: `${profileBanner()} Error:
|
|
169
|
-
`This cannot be enabled through configuration.`,
|
|
179
|
+
text: `${profileBanner()} Error: ${WRITE_FORBIDDEN_REASON}`,
|
|
170
180
|
},
|
|
171
181
|
],
|
|
172
182
|
isError: true,
|
|
@@ -393,6 +403,13 @@ async function executeReadOnlyQuery(sql, options = {}) {
|
|
|
393
403
|
{ enabled: isDeleteOperation, label: 'DELETE', allowed: isDeleteAllowedForSchema },
|
|
394
404
|
{ enabled: isDDLOperation, label: 'DDL', allowed: isDDLAllowedForSchema },
|
|
395
405
|
].filter((check) => check.enabled);
|
|
406
|
+
if (writeChecks.length > 0 && IS_WRITE_FORBIDDEN_PROFILE) {
|
|
407
|
+
log('error', `Refusing write operation: ${WRITE_FORBIDDEN_REASON}`);
|
|
408
|
+
return {
|
|
409
|
+
content: [{ type: 'text', text: `Error: ${WRITE_FORBIDDEN_REASON}` }],
|
|
410
|
+
isError: true,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
396
413
|
if (writeChecks.length > 0) {
|
|
397
414
|
const schemas = extractReferencedSchemas(sql);
|
|
398
415
|
for (const check of writeChecks) {
|
|
@@ -401,7 +418,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
|
|
|
401
418
|
continue;
|
|
402
419
|
}
|
|
403
420
|
const target = schemas ? (schemas[deniedIndex] ?? 'default') : 'unknown';
|
|
404
|
-
const setting =
|
|
421
|
+
const setting = `--schema-${check.label.toLowerCase()}`;
|
|
405
422
|
log('error', `${check.label} operations are not allowed for schema '${target}'. Configure ${setting}.`);
|
|
406
423
|
return {
|
|
407
424
|
content: [
|
|
@@ -427,7 +444,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
|
|
|
427
444
|
await connection.query('START TRANSACTION READ ONLY');
|
|
428
445
|
}
|
|
429
446
|
else {
|
|
430
|
-
log('info', 'Read-only transactions disabled via
|
|
447
|
+
log('info', 'Read-only transactions disabled via --no-read-only-transactions');
|
|
431
448
|
await connection.beginTransaction();
|
|
432
449
|
}
|
|
433
450
|
roundTrips += 1;
|
|
@@ -460,7 +477,7 @@ async function executeReadOnlyQuery(sql, options = {}) {
|
|
|
460
477
|
`the query matched more. This is NOT the complete result - do not count, sum, or ` +
|
|
461
478
|
`conclude anything about totals from it. Add a narrower WHERE, an aggregate ` +
|
|
462
479
|
`(COUNT/SUM/GROUP BY), or paginate with ORDER BY + LIMIT/OFFSET. Raising the cap ` +
|
|
463
|
-
`is an operator change (
|
|
480
|
+
`is an operator change (--max-rows), not something to retry around.`,
|
|
464
481
|
},
|
|
465
482
|
]
|
|
466
483
|
: []),
|
|
@@ -59,4 +59,7 @@ function writeCapabilities() {
|
|
|
59
59
|
}
|
|
60
60
|
return capabilities;
|
|
61
61
|
}
|
|
62
|
-
|
|
62
|
+
function describeWriteCapabilities(writes) {
|
|
63
|
+
return writes.map(({ label, schemas }) => (schemas ? `${label} (${schemas.join(', ')} only)` : label)).join(', ');
|
|
64
|
+
}
|
|
65
|
+
export { isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, isDDLAllowedForSchema, writeCapabilities, describeWriteCapabilities, };
|