@ecubelabs/mysql-mcp 1.0.0-next.7 → 1.0.0
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 +296 -448
- package/dist/index.js +377 -239
- package/dist/src/catalog/collect.js +3 -2
- package/dist/src/catalog/docs.js +14 -12
- package/dist/src/catalog/index.js +59 -99
- package/dist/src/catalog/render.js +4 -10
- package/dist/src/catalog/store.js +193 -76
- package/dist/src/catalog/types.js +0 -12
- package/dist/src/config/index.js +175 -0
- package/dist/src/db/index.js +379 -379
- package/dist/src/db/permissions.js +32 -16
- package/dist/src/db/utils.js +3 -1
- package/dist/src/ssh/config.js +34 -27
- package/dist/src/ssh/tunnel.js +238 -155
- package/dist/src/utils/index.js +4 -35
- package/package.json +4 -4
- package/dist/src/catalog/context.js +0 -187
- package/dist/src/catalog/lock.js +0 -113
- package/dist/src/config/args.js +0 -30
- package/dist/src/config/load.js +0 -169
- package/dist/src/config/schema.js +0 -351
- package/dist/src/config/secrets.js +0 -128
- package/dist/src/config/ssl.js +0 -25
- package/dist/src/db/registry.js +0 -178
- package/dist/src/init/check.js +0 -31
- package/dist/src/init/cli.js +0 -26
- package/dist/src/init/config-edit.js +0 -95
- package/dist/src/init/prompt.js +0 -82
- package/dist/src/init/wizard.js +0 -223
- package/dist/src/server/catalog-tool.js +0 -91
- package/dist/src/server/connections.js +0 -117
package/dist/src/db/index.js
CHANGED
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
import { performance } from 'perf_hooks';
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
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';
|
|
4
|
+
import { isDDLAllowedForSchema, isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, } from './permissions.js';
|
|
4
5
|
import { DDL_STATEMENT_TYPES, extractReferencedSchemas, findFileExport, findLimitOverrideHint, findUnsupportedStatementType, getQueryTypes, hasExecutableComment, isUnparseableIntrospection, extractQualifiers, } from './utils.js';
|
|
5
6
|
import { isQueryTimeoutError, parseExplainPayload, renderTimeoutDiagnostic } from './diagnose.js';
|
|
6
7
|
import { log } from './../utils/index.js';
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
};
|
|
18
|
-
}
|
|
8
|
+
import { ensureTunnel, getTunnelEndpoint, getTunnelFatalError, describeTunnel } from './../ssh/tunnel.js';
|
|
9
|
+
let poolPromise;
|
|
10
|
+
const READ_LIMITS = {
|
|
11
|
+
maxExecutionTimeMs: MYSQL_DEFAULT_TIMEOUT_SECONDS * 1_000,
|
|
12
|
+
selectLimit: MAX_RESPONSE_ROWS + 1,
|
|
13
|
+
};
|
|
14
|
+
const CATALOG_LIMITS = {
|
|
15
|
+
maxExecutionTimeMs: MYSQL_CATALOG_TIMEOUT_SECONDS * 1_000,
|
|
16
|
+
selectLimit: null,
|
|
17
|
+
};
|
|
19
18
|
const SESSION_LIMITS = Symbol.for('mysql-mcp.sessionLimits');
|
|
20
19
|
function limitCarrier(connection) {
|
|
21
20
|
const inner = connection?.connection;
|
|
@@ -43,23 +42,43 @@ async function applySessionLimits(connection, desired) {
|
|
|
43
42
|
}
|
|
44
43
|
return 1;
|
|
45
44
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
45
|
+
const getPool = () => {
|
|
46
|
+
if (!poolPromise) {
|
|
47
|
+
poolPromise = (async () => {
|
|
48
|
+
const endpoint = await ensureTunnel();
|
|
49
|
+
const mysqlConfig = endpoint
|
|
50
|
+
? (() => {
|
|
51
|
+
const { socketPath: _ignored, ...rest } = config.mysql;
|
|
52
|
+
return { ...rest, host: endpoint.host, port: endpoint.port };
|
|
53
|
+
})()
|
|
54
|
+
: config.mysql;
|
|
55
|
+
const pool = mysql2.createPool(mysqlConfig);
|
|
56
|
+
pool.on('connection', (connection) => {
|
|
57
|
+
const carrier = limitCarrier(connection);
|
|
58
|
+
const raw = connection;
|
|
59
|
+
carrier[SESSION_LIMITS] = READ_LIMITS;
|
|
60
|
+
raw.query(limitsStatement(READ_LIMITS), (error) => {
|
|
61
|
+
if (!error) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
log('error', 'Failed to prime session limits on a new connection:', error);
|
|
65
|
+
delete carrier[SESSION_LIMITS];
|
|
66
|
+
});
|
|
59
67
|
});
|
|
68
|
+
log('info', `MySQL pool created successfully (profile: ${PROFILE_LABEL}` +
|
|
69
|
+
(endpoint
|
|
70
|
+
? `, via ${endpoint.reused ? 'reused' : 'new'} tunnel ${endpoint.host}:${endpoint.port}`
|
|
71
|
+
: '') +
|
|
72
|
+
')');
|
|
73
|
+
return pool;
|
|
74
|
+
})();
|
|
75
|
+
poolPromise.catch((error) => {
|
|
76
|
+
log('error', 'Error creating MySQL pool:', error);
|
|
77
|
+
poolPromise = undefined;
|
|
60
78
|
});
|
|
61
|
-
}
|
|
62
|
-
|
|
79
|
+
}
|
|
80
|
+
return poolPromise;
|
|
81
|
+
};
|
|
63
82
|
function describeQueryError(error) {
|
|
64
83
|
if (!(error instanceof Error)) {
|
|
65
84
|
return String(error);
|
|
@@ -78,7 +97,171 @@ async function rollbackQuietly(connection) {
|
|
|
78
97
|
log('error', 'Rollback failed; reporting the original error instead:', describeQueryError(error));
|
|
79
98
|
}
|
|
80
99
|
}
|
|
81
|
-
function
|
|
100
|
+
function assertTunnelHealthy() {
|
|
101
|
+
const fatal = getTunnelFatalError();
|
|
102
|
+
if (fatal) {
|
|
103
|
+
throw fatal;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function describeConnection() {
|
|
107
|
+
const endpoint = getTunnelEndpoint();
|
|
108
|
+
if (endpoint) {
|
|
109
|
+
return `${endpoint.host}:${endpoint.port} ` + `(${endpoint.reused ? 'reused' : 'new'} ssh tunnel)`;
|
|
110
|
+
}
|
|
111
|
+
const target = describeConfiguredTarget();
|
|
112
|
+
return SSH_ENABLED ? `${target} (via ssh tunnel, not yet established)` : target;
|
|
113
|
+
}
|
|
114
|
+
let codeBranchSource = null;
|
|
115
|
+
function setCodeBranchSource(source) {
|
|
116
|
+
codeBranchSource = source;
|
|
117
|
+
}
|
|
118
|
+
function profileBanner() {
|
|
119
|
+
const parts = [`profile: ${PROFILE_LABEL}`];
|
|
120
|
+
parts.push(IS_WRITE_FORBIDDEN_PROFILE ? 'READ-ONLY (enforced)' : 'read-only');
|
|
121
|
+
const db = config.mysql.database || 'multi-db';
|
|
122
|
+
parts.push(`database: ${db}`);
|
|
123
|
+
const branch = codeBranchSource?.();
|
|
124
|
+
if (branch) {
|
|
125
|
+
parts.push(`code: ${branch}`);
|
|
126
|
+
}
|
|
127
|
+
const tunnel = describeTunnel();
|
|
128
|
+
if (tunnel) {
|
|
129
|
+
parts.push(tunnel);
|
|
130
|
+
}
|
|
131
|
+
return `[${parts.join(' | ')}]`;
|
|
132
|
+
}
|
|
133
|
+
async function executeQuery(sql, params = []) {
|
|
134
|
+
let connection;
|
|
135
|
+
try {
|
|
136
|
+
assertTunnelHealthy();
|
|
137
|
+
const pool = await getPool();
|
|
138
|
+
connection = await pool.getConnection();
|
|
139
|
+
await applySessionLimits(connection, CATALOG_LIMITS);
|
|
140
|
+
const result = await connection.query(sql, params);
|
|
141
|
+
return (Array.isArray(result) ? result[0] : result);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
log('error', 'Error executing query:', error);
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
if (connection) {
|
|
149
|
+
try {
|
|
150
|
+
await applySessionLimits(connection, READ_LIMITS);
|
|
151
|
+
}
|
|
152
|
+
catch (restoreError) {
|
|
153
|
+
log('error', 'Error restoring session limits:', restoreError);
|
|
154
|
+
}
|
|
155
|
+
connection.release();
|
|
156
|
+
log('info', 'Connection released');
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async function executeWriteQuery(sql) {
|
|
161
|
+
let connection;
|
|
162
|
+
if (IS_WRITE_FORBIDDEN_PROFILE) {
|
|
163
|
+
log('error', `Refusing write operation: profile "${MYSQL_PROFILE}" is read-only by policy.`);
|
|
164
|
+
return {
|
|
165
|
+
content: [
|
|
166
|
+
{
|
|
167
|
+
type: 'text',
|
|
168
|
+
text: `${profileBanner()} Error: write operations are disabled by policy for profile "${MYSQL_PROFILE}". ` +
|
|
169
|
+
`This cannot be enabled through configuration.`,
|
|
170
|
+
},
|
|
171
|
+
],
|
|
172
|
+
isError: true,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
assertTunnelHealthy();
|
|
177
|
+
const pool = await getPool();
|
|
178
|
+
connection = await pool.getConnection();
|
|
179
|
+
log('info', 'Write connection acquired');
|
|
180
|
+
const schema = (extractReferencedSchemas(sql) ?? [null]).map((name) => name ?? 'default').join(', ');
|
|
181
|
+
await connection.beginTransaction();
|
|
182
|
+
try {
|
|
183
|
+
const startTime = performance.now();
|
|
184
|
+
const result = await connection.query(sql);
|
|
185
|
+
const endTime = performance.now();
|
|
186
|
+
const duration = endTime - startTime;
|
|
187
|
+
const response = Array.isArray(result) ? result[0] : result;
|
|
188
|
+
await connection.commit();
|
|
189
|
+
let responseText;
|
|
190
|
+
const queryTypes = await getQueryTypes(sql);
|
|
191
|
+
const isUpdateOperation = queryTypes.some((type) => ['update'].includes(type));
|
|
192
|
+
const isInsertOperation = queryTypes.some((type) => ['insert'].includes(type));
|
|
193
|
+
const isDeleteOperation = queryTypes.some((type) => ['delete'].includes(type));
|
|
194
|
+
const isDDLOperation = queryTypes.some((type) => DDL_STATEMENT_TYPES.has(type));
|
|
195
|
+
if (isInsertOperation) {
|
|
196
|
+
const resultHeader = response;
|
|
197
|
+
responseText = `Insert successful on schema '${schema}'. Affected rows: ${resultHeader.affectedRows}, Last insert ID: ${resultHeader.insertId}`;
|
|
198
|
+
}
|
|
199
|
+
else if (isUpdateOperation) {
|
|
200
|
+
const resultHeader = response;
|
|
201
|
+
responseText = `Update successful on schema '${schema}'. Affected rows: ${resultHeader.affectedRows}, Changed rows: ${resultHeader.changedRows || 0}`;
|
|
202
|
+
}
|
|
203
|
+
else if (isDeleteOperation) {
|
|
204
|
+
const resultHeader = response;
|
|
205
|
+
responseText = `Delete successful on schema '${schema}'. Affected rows: ${resultHeader.affectedRows}`;
|
|
206
|
+
}
|
|
207
|
+
else if (isDDLOperation) {
|
|
208
|
+
responseText = `DDL operation successful on schema '${schema}'.`;
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
responseText = JSON.stringify(response, null, 2);
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
content: [
|
|
215
|
+
{
|
|
216
|
+
type: 'text',
|
|
217
|
+
text: responseText,
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
type: 'text',
|
|
221
|
+
text: `Query execution time: ${duration.toFixed(2)} ms`,
|
|
222
|
+
},
|
|
223
|
+
],
|
|
224
|
+
isError: false,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
log('error', 'Error executing write query:', describeQueryError(error));
|
|
229
|
+
await rollbackQuietly(connection);
|
|
230
|
+
return {
|
|
231
|
+
content: [
|
|
232
|
+
{
|
|
233
|
+
type: 'text',
|
|
234
|
+
text: `Error executing write operation: ${error instanceof Error ? error.message : String(error)}`,
|
|
235
|
+
},
|
|
236
|
+
],
|
|
237
|
+
isError: true,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
log('error', 'Error in write operation transaction:', describeQueryError(error));
|
|
243
|
+
return {
|
|
244
|
+
content: [
|
|
245
|
+
{
|
|
246
|
+
type: 'text',
|
|
247
|
+
text: `Database connection error: ${error instanceof Error ? error.message : String(error)}`,
|
|
248
|
+
},
|
|
249
|
+
],
|
|
250
|
+
isError: true,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
if (connection) {
|
|
255
|
+
connection.release();
|
|
256
|
+
log('info', 'Write connection released');
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
let diagnosticsSource = null;
|
|
261
|
+
function setQueryDiagnosticsSource(source) {
|
|
262
|
+
diagnosticsSource = source;
|
|
263
|
+
}
|
|
264
|
+
function clampTimeoutSeconds(requested) {
|
|
82
265
|
let value;
|
|
83
266
|
if (typeof requested === 'number') {
|
|
84
267
|
value = requested;
|
|
@@ -86,418 +269,235 @@ function clampTimeoutSeconds(requested, defaults) {
|
|
|
86
269
|
else if (typeof requested === 'string') {
|
|
87
270
|
const trimmed = requested.trim();
|
|
88
271
|
if (trimmed === '') {
|
|
89
|
-
return
|
|
272
|
+
return MYSQL_DEFAULT_TIMEOUT_SECONDS;
|
|
90
273
|
}
|
|
91
274
|
value = Number(trimmed);
|
|
92
275
|
}
|
|
93
276
|
else {
|
|
94
|
-
return
|
|
277
|
+
return MYSQL_DEFAULT_TIMEOUT_SECONDS;
|
|
95
278
|
}
|
|
96
279
|
if (!Number.isFinite(value)) {
|
|
97
|
-
return
|
|
98
|
-
}
|
|
99
|
-
return Math.min(Math.max(Math.floor(value), 1), defaults.maxTimeoutSeconds);
|
|
100
|
-
}
|
|
101
|
-
function describeWriteMode(writeForbidden, capabilities) {
|
|
102
|
-
if (writeForbidden) {
|
|
103
|
-
return 'READ-ONLY (enforced)';
|
|
104
|
-
}
|
|
105
|
-
if (capabilities.length === 0) {
|
|
106
|
-
return 'read-only';
|
|
280
|
+
return MYSQL_DEFAULT_TIMEOUT_SECONDS;
|
|
107
281
|
}
|
|
108
|
-
return
|
|
282
|
+
return Math.min(Math.max(Math.floor(value), 1), MYSQL_MAX_TIMEOUT_SECONDS);
|
|
109
283
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
defaults;
|
|
116
|
-
defaultSchema;
|
|
117
|
-
constructor(handle, env) {
|
|
118
|
-
this.handle = handle;
|
|
119
|
-
this.env = env;
|
|
120
|
-
this.defaults = env.defaults;
|
|
121
|
-
this.defaultSchema = handle.spec.database ?? null;
|
|
122
|
-
}
|
|
123
|
-
get spec() {
|
|
124
|
-
return this.handle.spec;
|
|
125
|
-
}
|
|
126
|
-
setDiagnosticsSource(source) {
|
|
127
|
-
this.diagnosticsSource = source;
|
|
128
|
-
}
|
|
129
|
-
setCodeBranchSource(source) {
|
|
130
|
-
this.codeBranchSource = source;
|
|
131
|
-
}
|
|
132
|
-
banner() {
|
|
133
|
-
const parts = [
|
|
134
|
-
`env: ${this.env.label}`,
|
|
135
|
-
`connection: ${this.spec.name} (${this.spec.instance.name}, user ${this.spec.user})`,
|
|
136
|
-
];
|
|
137
|
-
parts.push(describeWriteMode(this.env.writeForbidden, writeCapabilities(this.spec.write)));
|
|
138
|
-
const branch = this.codeBranchSource?.();
|
|
139
|
-
if (branch) {
|
|
140
|
-
parts.push(`code: ${branch}`);
|
|
141
|
-
}
|
|
142
|
-
const transport = this.handle.describeTransport();
|
|
143
|
-
if (transport) {
|
|
144
|
-
parts.push(transport);
|
|
145
|
-
}
|
|
146
|
-
return `[${parts.join(' | ')}]`;
|
|
284
|
+
async function diagnoseTimeout(connection, sql, timeoutSeconds) {
|
|
285
|
+
let plan = null;
|
|
286
|
+
try {
|
|
287
|
+
const explained = await connection.query(`EXPLAIN FORMAT=JSON ${sql}`);
|
|
288
|
+
plan = parseExplainPayload(Array.isArray(explained) ? explained[0] : explained);
|
|
147
289
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const configured = instance.socketPath ? `socket: ${instance.socketPath}` : `${instance.host}:${instance.port}`;
|
|
151
|
-
const endpoint = this.handle.endpoint;
|
|
152
|
-
if (endpoint) {
|
|
153
|
-
return `${endpoint.host}:${endpoint.port} (ssh tunnel to ${configured})`;
|
|
154
|
-
}
|
|
155
|
-
return this.spec.bastion ? `${configured} (via ssh tunnel, not yet established)` : configured;
|
|
290
|
+
catch (error) {
|
|
291
|
+
log('error', 'Could not EXPLAIN the timed-out query:', describeQueryError(error));
|
|
156
292
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
throw error;
|
|
168
|
-
}
|
|
169
|
-
finally {
|
|
170
|
-
if (connection) {
|
|
171
|
-
try {
|
|
172
|
-
await applySessionLimits(connection, readLimits(this.defaults));
|
|
173
|
-
}
|
|
174
|
-
catch (restoreError) {
|
|
175
|
-
log('error', 'Error restoring session limits:', restoreError);
|
|
176
|
-
}
|
|
177
|
-
connection.release();
|
|
178
|
-
log('info', 'Connection released');
|
|
293
|
+
const qualifiers = extractQualifiers(sql);
|
|
294
|
+
const source = diagnosticsSource;
|
|
295
|
+
return renderTimeoutDiagnostic({
|
|
296
|
+
timeoutSeconds,
|
|
297
|
+
maxTimeoutSeconds: MYSQL_MAX_TIMEOUT_SECONDS,
|
|
298
|
+
plan,
|
|
299
|
+
qualifiers,
|
|
300
|
+
lookupIndexes: (name) => {
|
|
301
|
+
if (!source) {
|
|
302
|
+
return null;
|
|
179
303
|
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
304
|
+
const resolved = qualifiers.get(name.toLowerCase());
|
|
305
|
+
return source.indexFacts(resolved ?? { schema: null, table: name });
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
async function executeReadOnlyQuery(sql, options = {}) {
|
|
310
|
+
let connection;
|
|
311
|
+
try {
|
|
312
|
+
assertTunnelHealthy();
|
|
313
|
+
if (hasExecutableComment(sql)) {
|
|
314
|
+
log('error', 'Refusing a statement with an executable comment.');
|
|
186
315
|
return {
|
|
187
316
|
content: [
|
|
188
317
|
{
|
|
189
318
|
type: 'text',
|
|
190
|
-
text:
|
|
191
|
-
|
|
319
|
+
text: 'Error: executable comments (/*! ... */) are not allowed because MySQL runs their ' +
|
|
320
|
+
'contents. Write the statement without them.',
|
|
192
321
|
},
|
|
193
322
|
],
|
|
194
323
|
isError: true,
|
|
195
324
|
};
|
|
196
325
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
log('
|
|
200
|
-
const schema = (extractReferencedSchemas(sql, this.defaultSchema) ?? [null])
|
|
201
|
-
.map((name) => name ?? 'default')
|
|
202
|
-
.join(', ');
|
|
203
|
-
await connection.beginTransaction();
|
|
204
|
-
try {
|
|
205
|
-
const startTime = performance.now();
|
|
206
|
-
const result = await connection.query(sql);
|
|
207
|
-
const endTime = performance.now();
|
|
208
|
-
const duration = endTime - startTime;
|
|
209
|
-
const response = Array.isArray(result) ? result[0] : result;
|
|
210
|
-
await connection.commit();
|
|
211
|
-
let responseText;
|
|
212
|
-
const queryTypes = await getQueryTypes(sql);
|
|
213
|
-
const isUpdateOperation = queryTypes.some((type) => ['update'].includes(type));
|
|
214
|
-
const isInsertOperation = queryTypes.some((type) => ['insert'].includes(type));
|
|
215
|
-
const isDeleteOperation = queryTypes.some((type) => ['delete'].includes(type));
|
|
216
|
-
const isDDLOperation = queryTypes.some((type) => DDL_STATEMENT_TYPES.has(type));
|
|
217
|
-
if (isInsertOperation) {
|
|
218
|
-
const resultHeader = response;
|
|
219
|
-
responseText = `Insert successful on schema '${schema}'. Affected rows: ${resultHeader.affectedRows}, Last insert ID: ${resultHeader.insertId}`;
|
|
220
|
-
}
|
|
221
|
-
else if (isUpdateOperation) {
|
|
222
|
-
const resultHeader = response;
|
|
223
|
-
responseText = `Update successful on schema '${schema}'. Affected rows: ${resultHeader.affectedRows}, Changed rows: ${resultHeader.changedRows || 0}`;
|
|
224
|
-
}
|
|
225
|
-
else if (isDeleteOperation) {
|
|
226
|
-
const resultHeader = response;
|
|
227
|
-
responseText = `Delete successful on schema '${schema}'. Affected rows: ${resultHeader.affectedRows}`;
|
|
228
|
-
}
|
|
229
|
-
else if (isDDLOperation) {
|
|
230
|
-
responseText = `DDL operation successful on schema '${schema}'.`;
|
|
231
|
-
}
|
|
232
|
-
else {
|
|
233
|
-
responseText = JSON.stringify(response, null, 2);
|
|
234
|
-
}
|
|
235
|
-
return {
|
|
236
|
-
content: [
|
|
237
|
-
{
|
|
238
|
-
type: 'text',
|
|
239
|
-
text: responseText,
|
|
240
|
-
},
|
|
241
|
-
{
|
|
242
|
-
type: 'text',
|
|
243
|
-
text: `Query execution time: ${duration.toFixed(2)} ms`,
|
|
244
|
-
},
|
|
245
|
-
],
|
|
246
|
-
isError: false,
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
catch (error) {
|
|
250
|
-
log('error', 'Error executing write query:', describeQueryError(error));
|
|
251
|
-
await rollbackQuietly(connection);
|
|
252
|
-
return {
|
|
253
|
-
content: [
|
|
254
|
-
{
|
|
255
|
-
type: 'text',
|
|
256
|
-
text: `Error executing write operation: ${error instanceof Error ? error.message : String(error)}`,
|
|
257
|
-
},
|
|
258
|
-
],
|
|
259
|
-
isError: true,
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
catch (error) {
|
|
264
|
-
log('error', 'Error in write operation transaction:', describeQueryError(error));
|
|
326
|
+
const limitHint = findLimitOverrideHint(sql);
|
|
327
|
+
if (limitHint) {
|
|
328
|
+
log('error', `Refusing a statement with the ${limitHint} optimizer hint.`);
|
|
265
329
|
return {
|
|
266
330
|
content: [
|
|
267
331
|
{
|
|
268
332
|
type: 'text',
|
|
269
|
-
text: `
|
|
333
|
+
text: `Error: the ${limitHint} optimizer hint is not allowed because it overrides the ` +
|
|
334
|
+
`server's execution limit. Remove it and pass timeout_seconds (up to ` +
|
|
335
|
+
`${MYSQL_MAX_TIMEOUT_SECONDS}) if the query needs more time.`,
|
|
270
336
|
},
|
|
271
337
|
],
|
|
272
338
|
isError: true,
|
|
273
339
|
};
|
|
274
340
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
341
|
+
const bypassesQueryTypeChecks = isUnparseableIntrospection(sql);
|
|
342
|
+
let queryTypes = [];
|
|
343
|
+
let isUpdateOperation = false;
|
|
344
|
+
let isInsertOperation = false;
|
|
345
|
+
let isDeleteOperation = false;
|
|
346
|
+
let isDDLOperation = false;
|
|
347
|
+
if (!bypassesQueryTypeChecks) {
|
|
348
|
+
queryTypes = await getQueryTypes(sql);
|
|
349
|
+
if (queryTypes.length === 0) {
|
|
350
|
+
return {
|
|
351
|
+
content: [{ type: 'text', text: 'Error: no SQL statement found outside comments.' }],
|
|
352
|
+
isError: true,
|
|
353
|
+
};
|
|
279
354
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
try {
|
|
285
|
-
const explained = await connection.query(`EXPLAIN FORMAT=JSON ${sql}`);
|
|
286
|
-
plan = parseExplainPayload(Array.isArray(explained) ? explained[0] : explained);
|
|
287
|
-
}
|
|
288
|
-
catch (error) {
|
|
289
|
-
log('error', 'Could not EXPLAIN the timed-out query:', describeQueryError(error));
|
|
290
|
-
}
|
|
291
|
-
const qualifiers = extractQualifiers(sql);
|
|
292
|
-
const source = this.diagnosticsSource;
|
|
293
|
-
return renderTimeoutDiagnostic({
|
|
294
|
-
timeoutSeconds,
|
|
295
|
-
maxTimeoutSeconds: this.defaults.maxTimeoutSeconds,
|
|
296
|
-
plan,
|
|
297
|
-
qualifiers,
|
|
298
|
-
lookupIndexes: (name) => {
|
|
299
|
-
if (!source) {
|
|
300
|
-
return null;
|
|
301
|
-
}
|
|
302
|
-
const resolved = qualifiers.get(name.toLowerCase());
|
|
303
|
-
return source.indexFacts(resolved ?? { schema: null, table: name });
|
|
304
|
-
},
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
async executeReadOnlyQuery(sql, options = {}) {
|
|
308
|
-
let connection;
|
|
309
|
-
try {
|
|
310
|
-
if (hasExecutableComment(sql)) {
|
|
311
|
-
log('error', 'Refusing a statement with an executable comment.');
|
|
355
|
+
const unsupported = findUnsupportedStatementType(queryTypes);
|
|
356
|
+
if (unsupported) {
|
|
357
|
+
const statement = unsupported.toUpperCase();
|
|
358
|
+
log('error', `Refusing ${statement} statement: not a supported statement type.`);
|
|
312
359
|
return {
|
|
313
360
|
content: [
|
|
314
361
|
{
|
|
315
362
|
type: 'text',
|
|
316
|
-
text:
|
|
317
|
-
|
|
363
|
+
text: `Error: ${statement} statements are not allowed. This server runs SELECT, SHOW, ` +
|
|
364
|
+
`DESCRIBE and EXPLAIN, plus INSERT, UPDATE, DELETE and DDL where the profile's write ` +
|
|
365
|
+
`permissions allow them. Qualify table names with their schema instead of USE.`,
|
|
318
366
|
},
|
|
319
367
|
],
|
|
320
368
|
isError: true,
|
|
321
369
|
};
|
|
322
370
|
}
|
|
323
|
-
const
|
|
324
|
-
if (
|
|
325
|
-
log('error', `Refusing a
|
|
371
|
+
const fileExport = findFileExport(sql);
|
|
372
|
+
if (fileExport) {
|
|
373
|
+
log('error', `Refusing SELECT ... ${fileExport}: it writes a file on the database server.`);
|
|
326
374
|
return {
|
|
327
375
|
content: [
|
|
328
376
|
{
|
|
329
377
|
type: 'text',
|
|
330
|
-
text: `Error:
|
|
331
|
-
`server
|
|
332
|
-
`${this.defaults.maxTimeoutSeconds}) if the query needs more time.`,
|
|
378
|
+
text: `Error: SELECT ... ${fileExport} is not allowed because it writes a file on the ` +
|
|
379
|
+
`database server. Run the SELECT without it; rows come back in this response.`,
|
|
333
380
|
},
|
|
334
381
|
],
|
|
335
382
|
isError: true,
|
|
336
383
|
};
|
|
337
384
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
if (
|
|
354
|
-
|
|
355
|
-
log('error', `Refusing ${statement} statement: not a supported statement type.`);
|
|
356
|
-
return {
|
|
357
|
-
content: [
|
|
358
|
-
{
|
|
359
|
-
type: 'text',
|
|
360
|
-
text: `Error: ${statement} statements are not allowed. This server runs SELECT, SHOW, ` +
|
|
361
|
-
`DESCRIBE and EXPLAIN, plus INSERT, UPDATE, DELETE and DDL where the connection's write ` +
|
|
362
|
-
`permissions allow them. Qualify table names with their schema instead of USE.`,
|
|
363
|
-
},
|
|
364
|
-
],
|
|
365
|
-
isError: true,
|
|
366
|
-
};
|
|
367
|
-
}
|
|
368
|
-
const fileExport = findFileExport(sql);
|
|
369
|
-
if (fileExport) {
|
|
370
|
-
log('error', `Refusing SELECT ... ${fileExport}: it writes a file on the database server.`);
|
|
371
|
-
return {
|
|
372
|
-
content: [
|
|
373
|
-
{
|
|
374
|
-
type: 'text',
|
|
375
|
-
text: `Error: SELECT ... ${fileExport} is not allowed because it writes a file on the ` +
|
|
376
|
-
`database server. Run the SELECT without it; rows come back in this response.`,
|
|
377
|
-
},
|
|
378
|
-
],
|
|
379
|
-
isError: true,
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
isUpdateOperation = queryTypes.some((type) => ['update'].includes(type));
|
|
383
|
-
isInsertOperation = queryTypes.some((type) => ['insert'].includes(type));
|
|
384
|
-
isDeleteOperation = queryTypes.some((type) => ['delete'].includes(type));
|
|
385
|
-
isDDLOperation = queryTypes.some((type) => DDL_STATEMENT_TYPES.has(type));
|
|
386
|
-
}
|
|
387
|
-
const writeChecks = [
|
|
388
|
-
{ enabled: isInsertOperation, kind: 'insert' },
|
|
389
|
-
{ enabled: isUpdateOperation, kind: 'update' },
|
|
390
|
-
{ enabled: isDeleteOperation, kind: 'delete' },
|
|
391
|
-
{ enabled: isDDLOperation, kind: 'ddl' },
|
|
392
|
-
].filter((check) => check.enabled);
|
|
393
|
-
if (writeChecks.length > 0) {
|
|
394
|
-
const schemas = extractReferencedSchemas(sql, this.defaultSchema);
|
|
395
|
-
for (const { kind } of writeChecks) {
|
|
396
|
-
const deniedIndex = schemas
|
|
397
|
-
? schemas.findIndex((name) => !isWriteAllowed(this.spec.write, kind, name))
|
|
398
|
-
: 0;
|
|
399
|
-
if (deniedIndex === -1) {
|
|
400
|
-
continue;
|
|
401
|
-
}
|
|
402
|
-
const label = WRITE_LABELS[kind];
|
|
403
|
-
const target = schemas ? (schemas[deniedIndex] ?? 'default') : 'unknown';
|
|
404
|
-
const setting = `environments.${this.env.name}.accounts.${this.spec.name}.write`;
|
|
405
|
-
log('error', `${label} operations are not allowed for schema '${target}'. Configure ${setting}.`);
|
|
406
|
-
return {
|
|
407
|
-
content: [
|
|
408
|
-
{
|
|
409
|
-
type: 'text',
|
|
410
|
-
text: `Error: ${label} operations are not allowed for schema '${target}' on connection "${this.spec.name}". Ask the administrator to update ${setting} in the server config.`,
|
|
411
|
-
},
|
|
412
|
-
],
|
|
413
|
-
isError: true,
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
return this.executeWriteQuery(sql);
|
|
417
|
-
}
|
|
418
|
-
connection = await this.handle.getConnection();
|
|
419
|
-
log('info', 'Read-only connection acquired');
|
|
420
|
-
const timeoutSeconds = clampTimeoutSeconds(options.timeoutSeconds, this.defaults);
|
|
421
|
-
let roundTrips = await applySessionLimits(connection, {
|
|
422
|
-
maxExecutionTimeMs: timeoutSeconds * 1_000,
|
|
423
|
-
selectLimit: this.defaults.maxResponseRows + 1,
|
|
424
|
-
});
|
|
425
|
-
if (!this.spec.instance.disableReadOnlyTransactions) {
|
|
426
|
-
await connection.query('START TRANSACTION READ ONLY');
|
|
427
|
-
}
|
|
428
|
-
else {
|
|
429
|
-
log('info', `Read-only transactions disabled via instances.${this.spec.instance.name}.disableReadOnlyTransactions`);
|
|
430
|
-
await connection.beginTransaction();
|
|
431
|
-
}
|
|
432
|
-
roundTrips += 1;
|
|
433
|
-
try {
|
|
434
|
-
const startTime = performance.now();
|
|
435
|
-
const result = await connection.query(sql);
|
|
436
|
-
const endTime = performance.now();
|
|
437
|
-
const duration = endTime - startTime;
|
|
438
|
-
roundTrips += 1;
|
|
439
|
-
let rows = Array.isArray(result) ? result[0] : result;
|
|
440
|
-
await connection.rollback();
|
|
441
|
-
roundTrips += 1;
|
|
442
|
-
log('info', `Read query completed in ${roundTrips} DB round trips`);
|
|
443
|
-
let truncated = false;
|
|
444
|
-
if (Array.isArray(rows) && rows.length > this.defaults.maxResponseRows) {
|
|
445
|
-
truncated = true;
|
|
446
|
-
rows = rows.slice(0, this.defaults.maxResponseRows);
|
|
385
|
+
isUpdateOperation = queryTypes.some((type) => ['update'].includes(type));
|
|
386
|
+
isInsertOperation = queryTypes.some((type) => ['insert'].includes(type));
|
|
387
|
+
isDeleteOperation = queryTypes.some((type) => ['delete'].includes(type));
|
|
388
|
+
isDDLOperation = queryTypes.some((type) => DDL_STATEMENT_TYPES.has(type));
|
|
389
|
+
}
|
|
390
|
+
const writeChecks = [
|
|
391
|
+
{ enabled: isInsertOperation, label: 'INSERT', allowed: isInsertAllowedForSchema },
|
|
392
|
+
{ enabled: isUpdateOperation, label: 'UPDATE', allowed: isUpdateAllowedForSchema },
|
|
393
|
+
{ enabled: isDeleteOperation, label: 'DELETE', allowed: isDeleteAllowedForSchema },
|
|
394
|
+
{ enabled: isDDLOperation, label: 'DDL', allowed: isDDLAllowedForSchema },
|
|
395
|
+
].filter((check) => check.enabled);
|
|
396
|
+
if (writeChecks.length > 0) {
|
|
397
|
+
const schemas = extractReferencedSchemas(sql);
|
|
398
|
+
for (const check of writeChecks) {
|
|
399
|
+
const deniedIndex = schemas ? schemas.findIndex((name) => !check.allowed(name)) : 0;
|
|
400
|
+
if (deniedIndex === -1) {
|
|
401
|
+
continue;
|
|
447
402
|
}
|
|
403
|
+
const target = schemas ? (schemas[deniedIndex] ?? 'default') : 'unknown';
|
|
404
|
+
const setting = `SCHEMA_${check.label}_PERMISSIONS`;
|
|
405
|
+
log('error', `${check.label} operations are not allowed for schema '${target}'. Configure ${setting}.`);
|
|
448
406
|
return {
|
|
449
407
|
content: [
|
|
450
408
|
{
|
|
451
409
|
type: 'text',
|
|
452
|
-
text:
|
|
453
|
-
},
|
|
454
|
-
...(truncated
|
|
455
|
-
? [
|
|
456
|
-
{
|
|
457
|
-
type: 'text',
|
|
458
|
-
text: `[TRUNCATED] Only the first ${this.defaults.maxResponseRows.toLocaleString('en-US')} rows are shown; ` +
|
|
459
|
-
`the query matched more. This is NOT the complete result - do not count, sum, or ` +
|
|
460
|
-
`conclude anything about totals from it. Add a narrower WHERE, an aggregate ` +
|
|
461
|
-
`(COUNT/SUM/GROUP BY), or paginate with ORDER BY + LIMIT/OFFSET. Raising the cap ` +
|
|
462
|
-
`is an operator change (defaults.maxResponseRows in the server config), not something to retry around.`,
|
|
463
|
-
},
|
|
464
|
-
]
|
|
465
|
-
: []),
|
|
466
|
-
{
|
|
467
|
-
type: 'text',
|
|
468
|
-
text: `Query execution time: ${duration.toFixed(2)} ms`,
|
|
410
|
+
text: `Error: ${check.label} operations are not allowed for schema '${target}'. Ask the administrator to update ${setting}.`,
|
|
469
411
|
},
|
|
470
412
|
],
|
|
471
|
-
isError:
|
|
413
|
+
isError: true,
|
|
472
414
|
};
|
|
473
415
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
416
|
+
return executeWriteQuery(sql);
|
|
417
|
+
}
|
|
418
|
+
const pool = await getPool();
|
|
419
|
+
connection = await pool.getConnection();
|
|
420
|
+
log('info', 'Read-only connection acquired');
|
|
421
|
+
const timeoutSeconds = clampTimeoutSeconds(options.timeoutSeconds);
|
|
422
|
+
let roundTrips = await applySessionLimits(connection, {
|
|
423
|
+
maxExecutionTimeMs: timeoutSeconds * 1_000,
|
|
424
|
+
selectLimit: MAX_RESPONSE_ROWS + 1,
|
|
425
|
+
});
|
|
426
|
+
if (!MYSQL_DISABLE_READ_ONLY_TRANSACTIONS) {
|
|
427
|
+
await connection.query('START TRANSACTION READ ONLY');
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
log('info', 'Read-only transactions disabled via MYSQL_DISABLE_READ_ONLY_TRANSACTIONS=true');
|
|
431
|
+
await connection.beginTransaction();
|
|
432
|
+
}
|
|
433
|
+
roundTrips += 1;
|
|
434
|
+
try {
|
|
435
|
+
const startTime = performance.now();
|
|
436
|
+
const result = await connection.query(sql);
|
|
437
|
+
const endTime = performance.now();
|
|
438
|
+
const duration = endTime - startTime;
|
|
439
|
+
roundTrips += 1;
|
|
440
|
+
let rows = Array.isArray(result) ? result[0] : result;
|
|
441
|
+
await connection.rollback();
|
|
442
|
+
roundTrips += 1;
|
|
443
|
+
log('info', `Read query completed in ${roundTrips} DB round trips`);
|
|
444
|
+
let truncated = false;
|
|
445
|
+
if (Array.isArray(rows) && rows.length > MAX_RESPONSE_ROWS) {
|
|
446
|
+
truncated = true;
|
|
447
|
+
rows = rows.slice(0, MAX_RESPONSE_ROWS);
|
|
486
448
|
}
|
|
449
|
+
return {
|
|
450
|
+
content: [
|
|
451
|
+
{
|
|
452
|
+
type: 'text',
|
|
453
|
+
text: JSON.stringify(rows, null, 2),
|
|
454
|
+
},
|
|
455
|
+
...(truncated
|
|
456
|
+
? [
|
|
457
|
+
{
|
|
458
|
+
type: 'text',
|
|
459
|
+
text: `[TRUNCATED] Only the first ${MAX_RESPONSE_ROWS.toLocaleString('en-US')} rows are shown; ` +
|
|
460
|
+
`the query matched more. This is NOT the complete result - do not count, sum, or ` +
|
|
461
|
+
`conclude anything about totals from it. Add a narrower WHERE, an aggregate ` +
|
|
462
|
+
`(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.`,
|
|
464
|
+
},
|
|
465
|
+
]
|
|
466
|
+
: []),
|
|
467
|
+
{
|
|
468
|
+
type: 'text',
|
|
469
|
+
text: `Query execution time: ${duration.toFixed(2)} ms`,
|
|
470
|
+
},
|
|
471
|
+
],
|
|
472
|
+
isError: false,
|
|
473
|
+
};
|
|
487
474
|
}
|
|
488
475
|
catch (error) {
|
|
489
|
-
log('error', 'Error
|
|
490
|
-
|
|
491
|
-
|
|
476
|
+
log('error', 'Error executing read-only query:', describeQueryError(error));
|
|
477
|
+
await rollbackQuietly(connection);
|
|
478
|
+
if (isQueryTimeoutError(error)) {
|
|
479
|
+
const diagnostic = await diagnoseTimeout(connection, sql, timeoutSeconds);
|
|
480
|
+
log('info', `Read query cancelled at ${timeoutSeconds}s after ${roundTrips + 3} DB round trips (including one EXPLAIN)`);
|
|
481
|
+
return {
|
|
482
|
+
content: [{ type: 'text', text: diagnostic }],
|
|
483
|
+
isError: true,
|
|
484
|
+
};
|
|
492
485
|
}
|
|
493
486
|
throw error;
|
|
494
487
|
}
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
488
|
+
}
|
|
489
|
+
catch (error) {
|
|
490
|
+
log('error', 'Error in read-only query transaction:', describeQueryError(error));
|
|
491
|
+
if (connection) {
|
|
492
|
+
await rollbackQuietly(connection);
|
|
493
|
+
}
|
|
494
|
+
throw error;
|
|
495
|
+
}
|
|
496
|
+
finally {
|
|
497
|
+
if (connection) {
|
|
498
|
+
connection.release();
|
|
499
|
+
log('info', 'Read-only connection released');
|
|
500
500
|
}
|
|
501
501
|
}
|
|
502
502
|
}
|
|
503
|
-
export { clampTimeoutSeconds, describeQueryError,
|
|
503
|
+
export { profileBanner, describeConnection, executeQuery, getPool, executeWriteQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, rollbackQuietly, poolPromise, };
|