@ecubelabs/mysql-mcp 1.0.0-next.6 → 1.0.0-next.7

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.
@@ -1,20 +1,21 @@
1
1
  import { performance } from 'perf_hooks';
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';
2
+ import { isWriteForbiddenEnv } from '../config/load.js';
3
+ import { isWriteAllowed, WRITE_LABELS, writeCapabilities } from './permissions.js';
5
4
  import { DDL_STATEMENT_TYPES, extractReferencedSchemas, findFileExport, findLimitOverrideHint, findUnsupportedStatementType, getQueryTypes, hasExecutableComment, isUnparseableIntrospection, extractQualifiers, } from './utils.js';
6
5
  import { isQueryTimeoutError, parseExplainPayload, renderTimeoutDiagnostic } from './diagnose.js';
7
6
  import { log } from './../utils/index.js';
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
- };
7
+ function readLimits(defaults) {
8
+ return {
9
+ maxExecutionTimeMs: defaults.defaultTimeoutSeconds * 1_000,
10
+ selectLimit: defaults.maxResponseRows + 1,
11
+ };
12
+ }
13
+ function catalogLimits(defaults) {
14
+ return {
15
+ maxExecutionTimeMs: defaults.catalogTimeoutSeconds * 1_000,
16
+ selectLimit: null,
17
+ };
18
+ }
18
19
  const SESSION_LIMITS = Symbol.for('mysql-mcp.sessionLimits');
19
20
  function limitCarrier(connection) {
20
21
  const inner = connection?.connection;
@@ -42,43 +43,23 @@ async function applySessionLimits(connection, desired) {
42
43
  }
43
44
  return 1;
44
45
  }
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
- });
46
+ function sessionLimitPrimer(defaults) {
47
+ const limits = readLimits(defaults);
48
+ return (pool) => {
49
+ pool.on('connection', (connection) => {
50
+ const carrier = limitCarrier(connection);
51
+ const raw = connection;
52
+ carrier[SESSION_LIMITS] = limits;
53
+ raw.query(limitsStatement(limits), (error) => {
54
+ if (!error) {
55
+ return;
56
+ }
57
+ log('error', 'Failed to prime session limits on a new connection:', error);
58
+ delete carrier[SESSION_LIMITS];
67
59
  });
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;
78
60
  });
79
- }
80
- return poolPromise;
81
- };
61
+ };
62
+ }
82
63
  function describeQueryError(error) {
83
64
  if (!(error instanceof Error)) {
84
65
  return String(error);
@@ -97,171 +78,7 @@ async function rollbackQuietly(connection) {
97
78
  log('error', 'Rollback failed; reporting the original error instead:', describeQueryError(error));
98
79
  }
99
80
  }
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) {
81
+ function clampTimeoutSeconds(requested, defaults) {
265
82
  let value;
266
83
  if (typeof requested === 'number') {
267
84
  value = requested;
@@ -269,235 +86,418 @@ function clampTimeoutSeconds(requested) {
269
86
  else if (typeof requested === 'string') {
270
87
  const trimmed = requested.trim();
271
88
  if (trimmed === '') {
272
- return MYSQL_DEFAULT_TIMEOUT_SECONDS;
89
+ return defaults.defaultTimeoutSeconds;
273
90
  }
274
91
  value = Number(trimmed);
275
92
  }
276
93
  else {
277
- return MYSQL_DEFAULT_TIMEOUT_SECONDS;
94
+ return defaults.defaultTimeoutSeconds;
278
95
  }
279
96
  if (!Number.isFinite(value)) {
280
- return MYSQL_DEFAULT_TIMEOUT_SECONDS;
97
+ return defaults.defaultTimeoutSeconds;
281
98
  }
282
- return Math.min(Math.max(Math.floor(value), 1), MYSQL_MAX_TIMEOUT_SECONDS);
99
+ return Math.min(Math.max(Math.floor(value), 1), defaults.maxTimeoutSeconds);
283
100
  }
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);
101
+ function describeWriteMode(writeForbidden, capabilities) {
102
+ if (writeForbidden) {
103
+ return 'READ-ONLY (enforced)';
289
104
  }
290
- catch (error) {
291
- log('error', 'Could not EXPLAIN the timed-out query:', describeQueryError(error));
105
+ if (capabilities.length === 0) {
106
+ return 'read-only';
292
107
  }
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;
303
- }
304
- const resolved = qualifiers.get(name.toLowerCase());
305
- return source.indexFacts(resolved ?? { schema: null, table: name });
306
- },
307
- });
108
+ return `writes: ${capabilities.map(({ label, schemas }) => (schemas ? `${label} (${schemas.join(', ')} only)` : label)).join(', ')}`;
308
109
  }
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.');
110
+ export class ConnectionDatabase {
111
+ handle;
112
+ env;
113
+ diagnosticsSource = null;
114
+ codeBranchSource = null;
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(' | ')}]`;
147
+ }
148
+ describeConnection() {
149
+ const { instance } = this.spec;
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;
156
+ }
157
+ async executeQuery(sql, params = []) {
158
+ let connection;
159
+ try {
160
+ connection = await this.handle.getConnection();
161
+ await applySessionLimits(connection, catalogLimits(this.defaults));
162
+ const result = await connection.query(sql, params);
163
+ return (Array.isArray(result) ? result[0] : result);
164
+ }
165
+ catch (error) {
166
+ log('error', 'Error executing query:', error);
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');
179
+ }
180
+ }
181
+ }
182
+ async executeWriteQuery(sql) {
183
+ let connection;
184
+ if (this.env.writeForbidden || isWriteForbiddenEnv(this.env.name)) {
185
+ log('error', `Refusing write operation: environment "${this.env.name}" is read-only by policy.`);
315
186
  return {
316
187
  content: [
317
188
  {
318
189
  type: 'text',
319
- text: 'Error: executable comments (/*! ... */) are not allowed because MySQL runs their ' +
320
- 'contents. Write the statement without them.',
190
+ text: `Error: write operations are disabled by policy for environment "${this.env.name}". ` +
191
+ `This cannot be enabled through configuration.`,
321
192
  },
322
193
  ],
323
194
  isError: true,
324
195
  };
325
196
  }
326
- const limitHint = findLimitOverrideHint(sql);
327
- if (limitHint) {
328
- log('error', `Refusing a statement with the ${limitHint} optimizer hint.`);
197
+ try {
198
+ connection = await this.handle.getConnection();
199
+ log('info', 'Write connection acquired');
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));
329
265
  return {
330
266
  content: [
331
267
  {
332
268
  type: '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.`,
269
+ text: `Database connection error: ${error instanceof Error ? error.message : String(error)}`,
336
270
  },
337
271
  ],
338
272
  isError: true,
339
273
  };
340
274
  }
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
- };
275
+ finally {
276
+ if (connection) {
277
+ connection.release();
278
+ log('info', 'Write connection released');
354
279
  }
355
- const unsupported = findUnsupportedStatementType(queryTypes);
356
- if (unsupported) {
357
- const statement = unsupported.toUpperCase();
358
- log('error', `Refusing ${statement} statement: not a supported statement type.`);
280
+ }
281
+ }
282
+ async diagnoseTimeout(connection, sql, timeoutSeconds) {
283
+ let plan = null;
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.');
359
312
  return {
360
313
  content: [
361
314
  {
362
315
  type: 'text',
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.`,
316
+ text: 'Error: executable comments (/*! ... */) are not allowed because MySQL runs their ' +
317
+ 'contents. Write the statement without them.',
366
318
  },
367
319
  ],
368
320
  isError: true,
369
321
  };
370
322
  }
371
- const fileExport = findFileExport(sql);
372
- if (fileExport) {
373
- log('error', `Refusing SELECT ... ${fileExport}: it writes a file on the database server.`);
323
+ const limitHint = findLimitOverrideHint(sql);
324
+ if (limitHint) {
325
+ log('error', `Refusing a statement with the ${limitHint} optimizer hint.`);
374
326
  return {
375
327
  content: [
376
328
  {
377
329
  type: 'text',
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.`,
330
+ text: `Error: the ${limitHint} optimizer hint is not allowed because it overrides the ` +
331
+ `server's execution limit. Remove it and pass timeout_seconds (up to ` +
332
+ `${this.defaults.maxTimeoutSeconds}) if the query needs more time.`,
380
333
  },
381
334
  ],
382
335
  isError: true,
383
336
  };
384
337
  }
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;
338
+ const bypassesQueryTypeChecks = isUnparseableIntrospection(sql);
339
+ let queryTypes = [];
340
+ let isUpdateOperation = false;
341
+ let isInsertOperation = false;
342
+ let isDeleteOperation = false;
343
+ let isDDLOperation = false;
344
+ if (!bypassesQueryTypeChecks) {
345
+ queryTypes = await getQueryTypes(sql);
346
+ if (queryTypes.length === 0) {
347
+ return {
348
+ content: [{ type: 'text', text: 'Error: no SQL statement found outside comments.' }],
349
+ isError: true,
350
+ };
351
+ }
352
+ const unsupported = findUnsupportedStatementType(queryTypes);
353
+ if (unsupported) {
354
+ const statement = unsupported.toUpperCase();
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);
402
447
  }
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}.`);
406
448
  return {
407
449
  content: [
408
450
  {
409
451
  type: 'text',
410
- text: `Error: ${check.label} operations are not allowed for schema '${target}'. Ask the administrator to update ${setting}.`,
452
+ text: JSON.stringify(rows, null, 2),
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`,
411
469
  },
412
470
  ],
413
- isError: true,
471
+ isError: false,
414
472
  };
415
473
  }
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);
474
+ catch (error) {
475
+ log('error', 'Error executing read-only query:', describeQueryError(error));
476
+ await rollbackQuietly(connection);
477
+ if (isQueryTimeoutError(error)) {
478
+ const diagnostic = await this.diagnoseTimeout(connection, sql, timeoutSeconds);
479
+ log('info', `Read query cancelled at ${timeoutSeconds}s after ${roundTrips + 3} DB round trips (including one EXPLAIN)`);
480
+ return {
481
+ content: [{ type: 'text', text: diagnostic }],
482
+ isError: true,
483
+ };
484
+ }
485
+ throw error;
448
486
  }
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
- };
474
487
  }
475
488
  catch (error) {
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
- };
489
+ log('error', 'Error in read-only query transaction:', describeQueryError(error));
490
+ if (connection) {
491
+ await rollbackQuietly(connection);
485
492
  }
486
493
  throw error;
487
494
  }
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');
495
+ finally {
496
+ if (connection) {
497
+ connection.release();
498
+ log('info', 'Read-only connection released');
499
+ }
500
500
  }
501
501
  }
502
502
  }
503
- export { profileBanner, describeConnection, executeQuery, getPool, executeWriteQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, rollbackQuietly, poolPromise, };
503
+ export { clampTimeoutSeconds, describeQueryError, describeWriteMode, rollbackQuietly, sessionLimitPrimer };