@berthojoris/mcp-mysql-server 1.45.2 → 1.46.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/CHANGELOG.md CHANGED
@@ -5,6 +5,19 @@ All notable changes to the MySQL MCP Server will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.46.0] - 2026-10-26
9
+
10
+ ### Security
11
+ - `run_select_query` validates optimizer `hints` before adding them to the SQL. Table and index names must be identifiers, strategies and `MAX_EXECUTION_TIME`/`RESOURCE_GROUP`/`SET_VAR` values must match their MySQL forms, and invalid values are dropped. The query with hints applied is validated again before it runs.
12
+ - System schema checks (`mysql.user`, `mysql.db`, and the `execute` requirement for `information_schema`/`mysql`/`performance_schema`/`sys`) now also match names with whitespace around the dot.
13
+
14
+ ### Changed
15
+ - **Breaking:** `optimize_table`, `repair_table`, `flush_table`, and `optimize_fulltext` require `ddl` instead of `utility`, so the read-only default (`list,read,utility`) no longer enables them. `analyze_table`, `check_table`, and `analyze_index` stay in `utility`.
16
+ - `flush_table` flushes only tables in the connected database (all of them when `table_name` is omitted) and rejects `with_read_lock`, which left the lock held on a pooled connection. The parameter was removed from the tool schema. The catalog remains at 88 tools.
17
+
18
+ ### Added
19
+ - Jest tests for hint validation, qualified system schema names, and the maintenance tool permissions.
20
+
8
21
  ## [1.45.2] - 2026-10-26
9
22
 
10
23
  ### Changed
package/DOCUMENTATIONS.md CHANGED
@@ -253,8 +253,8 @@ For CSV exports, use `export_table_to_csv` for table-based exports and `export_q
253
253
  | `update` | Update records | `update_record`, `bulk_update` |
254
254
  | `delete` | Delete records | `delete_record`, `bulk_delete`, DELETE via `execute_write_query` (requires both `execute` and `delete`) |
255
255
  | `execute` | Custom SQL (INSERT/UPDATE; not DELETE without `delete`) | `execute_write_query` |
256
- | `ddl` | Schema changes | `create_table`, `alter_table` |
257
- | `utility` | Utility operations | `test_connection`, `analyze_table` |
256
+ | `ddl` | Schema changes; rebuilding, repairing or flushing tables | `create_table`, `alter_table`, `optimize_table`, `repair_table`, `flush_table`, `optimize_fulltext` |
257
+ | `utility` | Utility operations | `test_connection`, `analyze_table`, `check_table`, `analyze_index` |
258
258
  | `transaction` | Transaction management | `begin_transaction`, `commit_transaction` |
259
259
  | `procedure` | Stored procedures | `create_stored_procedure`, `execute_stored_procedure` |
260
260
 
@@ -274,6 +274,12 @@ Information queries such as SHOW/DESCRIBE/EXPLAIN require `list` or `read`. MySQ
274
274
 
275
275
  `EXPLAIN ANALYZE` (MySQL 8.0.18+) executes the statement it wraps, including multi-table UPDATE/DELETE, so it is authorized as that inner statement: `read` for SELECT, `update` or `execute` for UPDATE, and `delete` for DELETE. Plan-only `EXPLAIN` (without ANALYZE) remains an information query and only requires `list` or `read` (2026-10-12 20:39:13).
276
276
 
277
+ `optimize_table`, `repair_table`, `flush_table`, and `optimize_fulltext` rebuild, repair, or flush tables, so they require `ddl` instead of `utility` and are no longer part of the read-only default. `flush_table` only flushes tables in the connected database (all of them when `table_name` is omitted) and rejects `with_read_lock`, because the lock would stay held on a pooled connection after the call returns. `analyze_table`, `check_table`, and `analyze_index` remain `utility` tools (2026-10-26 16:39:47).
278
+
279
+ `run_select_query` optimizer `hints` are added to the SQL after it is validated, so every hint value is checked first: table and index names must be plain identifiers, `SEMIJOIN`/`SUBQUERY` strategies must be MySQL strategy names, `MAX_EXECUTION_TIME` must be a positive integer, and `SET_VAR` must be `name=value`. Invalid values are dropped, and the query with hints applied is validated again before it runs (2026-10-26 16:39:47).
280
+
281
+ Schema-qualified names are matched with any whitespace around the dot, so `mysql . user` is blocked like `mysql.user`, and `information_schema . tables` still requires `execute` (2026-10-26 16:39:47).
282
+
277
283
  `execute_write_query` accepts only INSERT, UPDATE, and DELETE. Schema changes must use enabled DDL tools, even when `execute` and `ddl` permissions are both present.
278
284
 
279
285
  ---
@@ -337,7 +343,7 @@ Information queries such as SHOW/DESCRIBE/EXPLAIN require `list` or `read`. MySQ
337
343
  - `get_fulltext_info` - Get FULLTEXT index information
338
344
  - `drop_fulltext_index` - Drop FULLTEXT indexes
339
345
  - `get_fulltext_stats` - Get FULLTEXT index statistics
340
- - `optimize_fulltext` - Optimize FULLTEXT indexes
346
+ - `optimize_fulltext` - Optimize FULLTEXT indexes (requires `ddl`)
341
347
 
342
348
  ### 9. Constraint Management (7 tools)
343
349
  - `list_foreign_keys` - List foreign keys
@@ -373,12 +379,12 @@ Information queries such as SHOW/DESCRIBE/EXPLAIN require `list` or `read`. MySQ
373
379
 
374
380
  ### 13. Table Maintenance (8 tools)
375
381
  - `analyze_table` - Update statistics
376
- - `optimize_table` - Reclaim space
382
+ - `optimize_table` - Reclaim space (requires `ddl`)
377
383
  - `check_table` - Check for errors
378
- - `repair_table` - Repair corrupted tables
384
+ - `repair_table` - Repair corrupted tables (requires `ddl`)
379
385
  - `truncate_table` - Remove all rows
380
386
  - `get_table_status` - Get table statistics
381
- - `flush_table` - Close/reopen table
387
+ - `flush_table` - Close/reopen tables in the connected database (requires `ddl`)
382
388
  - `get_table_size` - Get size information
383
389
 
384
390
  ### 14. Transaction Management (5 tools)
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  **A production-ready Model Context Protocol (MCP) server for MySQL database integration with AI agents**
6
6
 
7
- **Last Updated:** 2026-10-26 15:57:37
7
+ **Last Updated:** 2026-10-26 16:39:47
8
8
 
9
9
  [![npm version](https://img.shields.io/npm/v/@berthojoris/mcp-mysql-server)](https://www.npmjs.com/package/@berthojoris/mcp-mysql-server)
10
10
  [![npm downloads](https://img.shields.io/npm/dm/@berthojoris/mcp-mysql-server)](https://www.npmjs.com/package/@berthojoris/mcp-mysql-server)
@@ -349,11 +349,16 @@ Control database access with a **dual-layer filtering system** that provides bot
349
349
  | `update` | UPDATE existing records | Data maintenance |
350
350
  | `delete` | DELETE records | Data cleanup |
351
351
  | `execute` | Execute custom INSERT/UPDATE SQL (DELETE requires `delete` permission too) | Complex write operations |
352
- | `ddl` | CREATE/ALTER/DROP tables | Schema management |
352
+ | `ddl` | CREATE/ALTER/DROP tables; optimize, repair, and flush tables | Schema management |
353
353
  | `procedure` | Stored procedures (CREATE/DROP/EXECUTE) | Procedure management |
354
354
  | `transaction` | BEGIN, COMMIT, ROLLBACK | ACID operations |
355
355
  | `utility` | Connection testing, diagnostics | Troubleshooting |
356
356
 
357
+ **Security changes in v1.46.0 (review before upgrading):**
358
+ - `optimize_table`, `repair_table`, `flush_table`, and `optimize_fulltext` now require `ddl` instead of `utility`, so the read-only default no longer includes them. `flush_table` is limited to the connected database and no longer accepts `with_read_lock`.
359
+ - `run_select_query` drops invalid optimizer hint values and validates the query again after hints are applied.
360
+ - System schema names are detected with whitespace around the dot (e.g. `mysql . user`).
361
+
357
362
  **Changes in v1.44.0 (review before upgrading):**
358
363
  - **Read-only by default**: with no permissions and no categories, the server now enables only `list,read,utility` (previously every tool). To keep full access, pass `list,read,create,update,delete,execute,ddl,utility,transaction,procedure`.
359
364
  - **No implicit `mysql` schema**: without a database in the connection string or `DB_NAME`, database-scoped tools report "No database specified" instead of using the `mysql` system schema.
@@ -154,14 +154,14 @@ exports.toolCategoryMap = {
154
154
  addUniqueConstraint: ToolCategory.DDL,
155
155
  dropConstraint: ToolCategory.DDL,
156
156
  addCheckConstraint: ToolCategory.DDL,
157
- // Table maintenance tools
157
+ // Table maintenance tools (rebuilding, repairing or flushing tables needs ddl)
158
158
  analyzeTable: ToolCategory.UTILITY,
159
- optimizeTable: ToolCategory.UTILITY,
159
+ optimizeTable: ToolCategory.DDL,
160
160
  checkTable: ToolCategory.UTILITY,
161
- repairTable: ToolCategory.UTILITY,
161
+ repairTable: ToolCategory.DDL,
162
162
  truncateTable: ToolCategory.DDL,
163
163
  getTableStatus: ToolCategory.LIST,
164
- flushTable: ToolCategory.UTILITY,
164
+ flushTable: ToolCategory.DDL,
165
165
  getTableSize: ToolCategory.LIST,
166
166
  // Query optimization tools
167
167
  analyzeQuery: ToolCategory.UTILITY,
@@ -176,7 +176,7 @@ exports.toolCategoryMap = {
176
176
  getFulltextInfo: ToolCategory.LIST,
177
177
  dropFulltextIndex: ToolCategory.DDL,
178
178
  getFulltextStats: ToolCategory.LIST,
179
- optimizeFulltext: ToolCategory.UTILITY,
179
+ optimizeFulltext: ToolCategory.DDL,
180
180
  };
181
181
  const toolAdditionalPermissions = {
182
182
  exportTableToCSV: [ToolCategory.READ],
@@ -1976,7 +1976,7 @@ const TOOLS = (0, toolAnnotations_1.withToolAnnotations)([
1976
1976
  },
1977
1977
  {
1978
1978
  name: "optimize_table",
1979
- description: "Optimizes a table to reclaim unused space and defragment data.",
1979
+ description: "Optimizes a table to reclaim unused space and defragment data. Rebuilds the table, so it requires 'ddl' permission.",
1980
1980
  inputSchema: {
1981
1981
  type: "object",
1982
1982
  properties: {
@@ -2017,7 +2017,7 @@ const TOOLS = (0, toolAnnotations_1.withToolAnnotations)([
2017
2017
  },
2018
2018
  {
2019
2019
  name: "repair_table",
2020
- description: "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only).",
2020
+ description: "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only). Requires 'ddl' permission.",
2021
2021
  inputSchema: {
2022
2022
  type: "object",
2023
2023
  properties: {
@@ -2073,17 +2073,13 @@ const TOOLS = (0, toolAnnotations_1.withToolAnnotations)([
2073
2073
  },
2074
2074
  {
2075
2075
  name: "flush_table",
2076
- description: "Flushes table(s) - closes and reopens them.",
2076
+ description: "Flushes table(s) in the connected database - closes and reopens them. Requires 'ddl' permission.",
2077
2077
  inputSchema: {
2078
2078
  type: "object",
2079
2079
  properties: {
2080
2080
  table_name: {
2081
2081
  type: "string",
2082
- description: "Optional: specific table (omit for all tables)",
2083
- },
2084
- with_read_lock: {
2085
- type: "boolean",
2086
- description: "Acquire read lock after flushing",
2082
+ description: "Optional: specific table (omit for all tables in the connected database)",
2087
2083
  },
2088
2084
  database: {
2089
2085
  type: "string",
@@ -2263,7 +2259,7 @@ const TOOLS = (0, toolAnnotations_1.withToolAnnotations)([
2263
2259
  },
2264
2260
  {
2265
2261
  name: "optimize_fulltext",
2266
- description: "Optimizes a table to update FULLTEXT index statistics and reclaim space. Use this after bulk inserts or updates to improve search performance.",
2262
+ description: "Optimizes a table to update FULLTEXT index statistics and reclaim space. Use this after bulk inserts or updates to improve search performance. Rebuilds the table, so it requires 'ddl' permission.",
2267
2263
  inputSchema: {
2268
2264
  type: "object",
2269
2265
  properties: {
@@ -76,15 +76,23 @@ export declare class QueryOptimizer {
76
76
  * Escape special regex characters in a string
77
77
  */
78
78
  private escapeRegex;
79
- /**
80
- * Sanitize identifier (table name, index name) to prevent injection
81
- * Only allows alphanumeric characters, underscores, and dots (for schema.table)
82
- */
83
- private sanitizeIdentifier;
84
79
  /**
85
80
  * Validate that an identifier is safe to use
86
81
  */
87
82
  private isValidIdentifier;
83
+ /**
84
+ * Return the values that are safe identifiers. Hints are added after the
85
+ * query has been validated, so anything else is dropped rather than quoted.
86
+ */
87
+ private safeIdentifiers;
88
+ /**
89
+ * Return a SEMIJOIN/SUBQUERY strategy list if every strategy is allowed
90
+ */
91
+ private safeStrategy;
92
+ /**
93
+ * Return a positive integer no larger than max, or null
94
+ */
95
+ private safePositiveInteger;
88
96
  /**
89
97
  * Apply optimizer hints to a SELECT query
90
98
  */
@@ -28,14 +28,6 @@ class QueryOptimizer {
28
28
  escapeRegex(str) {
29
29
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30
30
  }
31
- /**
32
- * Sanitize identifier (table name, index name) to prevent injection
33
- * Only allows alphanumeric characters, underscores, and dots (for schema.table)
34
- */
35
- sanitizeIdentifier(identifier) {
36
- // Remove any characters that aren't alphanumeric, underscore, or dot
37
- return identifier.replace(/[^a-zA-Z0-9_\.]/g, "");
38
- }
39
31
  /**
40
32
  * Validate that an identifier is safe to use
41
33
  */
@@ -44,6 +36,37 @@ class QueryOptimizer {
44
36
  // Max length 64 (MySQL limit)
45
37
  return /^[a-zA-Z_][a-zA-Z0-9_\.]{0,63}$/.test(identifier);
46
38
  }
39
+ /**
40
+ * Return the values that are safe identifiers. Hints are added after the
41
+ * query has been validated, so anything else is dropped rather than quoted.
42
+ */
43
+ safeIdentifiers(value) {
44
+ const values = Array.isArray(value) ? value : [value];
45
+ return values.filter((item) => typeof item === "string" && this.isValidIdentifier(item));
46
+ }
47
+ /**
48
+ * Return a SEMIJOIN/SUBQUERY strategy list if every strategy is allowed
49
+ */
50
+ safeStrategy(strategy, allowed) {
51
+ if (typeof strategy !== "string") {
52
+ return null;
53
+ }
54
+ const strategies = strategy
55
+ .split(",")
56
+ .map((item) => item.trim().toUpperCase());
57
+ return strategies.every((item) => allowed.includes(item))
58
+ ? strategies.join(", ")
59
+ : null;
60
+ }
61
+ /**
62
+ * Return a positive integer no larger than max, or null
63
+ */
64
+ safePositiveInteger(value, max) {
65
+ const number = Number(value);
66
+ return Number.isInteger(number) && number > 0 && number <= max
67
+ ? number
68
+ : null;
69
+ }
47
70
  /**
48
71
  * Apply optimizer hints to a SELECT query
49
72
  */
@@ -110,33 +133,22 @@ class QueryOptimizer {
110
133
  }
111
134
  // Process shorthand hints
112
135
  if (hints.maxExecutionTime !== undefined) {
113
- // Validate maxExecutionTime is a positive integer
114
- const maxTime = Math.floor(Math.abs(Number(hints.maxExecutionTime)));
115
- if (maxTime > 0 && maxTime <= 31536000000) {
116
- // Max 1 year in ms
136
+ // Max 1 year in ms
137
+ const maxTime = this.safePositiveInteger(Math.floor(Math.abs(Number(hints.maxExecutionTime))), 31536000000);
138
+ if (maxTime !== null) {
117
139
  hintParts.push(`MAX_EXECUTION_TIME(${maxTime})`);
118
140
  }
119
141
  }
120
142
  if (hints.forceIndex) {
121
- const indexes = Array.isArray(hints.forceIndex)
122
- ? hints.forceIndex
123
- : [hints.forceIndex];
124
- const sanitizedIndexes = indexes
125
- .map((idx) => this.sanitizeIdentifier(idx))
126
- .filter((idx) => this.isValidIdentifier(idx));
127
- if (sanitizedIndexes.length > 0) {
128
- hintParts.push(`INDEX(${sanitizedIndexes.join(", ")})`);
143
+ const indexes = this.safeIdentifiers(hints.forceIndex);
144
+ if (indexes.length > 0) {
145
+ hintParts.push(`INDEX(${indexes.join(", ")})`);
129
146
  }
130
147
  }
131
148
  if (hints.ignoreIndex) {
132
- const indexes = Array.isArray(hints.ignoreIndex)
133
- ? hints.ignoreIndex
134
- : [hints.ignoreIndex];
135
- const sanitizedIndexes = indexes
136
- .map((idx) => this.sanitizeIdentifier(idx))
137
- .filter((idx) => this.isValidIdentifier(idx));
138
- if (sanitizedIndexes.length > 0) {
139
- hintParts.push(`NO_INDEX(${sanitizedIndexes.join(", ")})`);
149
+ const indexes = this.safeIdentifiers(hints.ignoreIndex);
150
+ if (indexes.length > 0) {
151
+ hintParts.push(`NO_INDEX(${indexes.join(", ")})`);
140
152
  }
141
153
  }
142
154
  return hintParts.join(" ");
@@ -145,6 +157,10 @@ class QueryOptimizer {
145
157
  * Format a single optimizer hint
146
158
  */
147
159
  formatHint(hint) {
160
+ const table = this.safeIdentifiers(hint.table)[0];
161
+ if (hint.table !== undefined && !table) {
162
+ return "";
163
+ }
148
164
  switch (hint.type) {
149
165
  // Join-Order Hints
150
166
  case "JOIN_FIXED_ORDER":
@@ -153,7 +169,10 @@ class QueryOptimizer {
153
169
  case "JOIN_PREFIX":
154
170
  case "JOIN_SUFFIX":
155
171
  if (hint.tables && hint.tables.length > 0) {
156
- return `${hint.type}(${hint.tables.join(", ")})`;
172
+ const tables = this.safeIdentifiers(hint.tables);
173
+ if (tables.length === hint.tables.length) {
174
+ return `${hint.type}(${tables.join(", ")})`;
175
+ }
157
176
  }
158
177
  return "";
159
178
  // Table-Level Hints
@@ -165,8 +184,8 @@ class QueryOptimizer {
165
184
  case "NO_HASH_JOIN":
166
185
  case "MERGE":
167
186
  case "NO_MERGE":
168
- if (hint.table) {
169
- return `${hint.type}(${hint.table})`;
187
+ if (table) {
188
+ return `${hint.type}(${table})`;
170
189
  }
171
190
  return `${hint.type}()`;
172
191
  // Index-Level Hints
@@ -180,41 +199,48 @@ class QueryOptimizer {
180
199
  case "NO_RANGE_OPTIMIZATION":
181
200
  case "SKIP_SCAN":
182
201
  case "NO_SKIP_SCAN":
183
- if (hint.table && hint.index) {
184
- const indexes = Array.isArray(hint.index)
185
- ? hint.index.join(", ")
186
- : hint.index;
187
- return `${hint.type}(${hint.table} ${indexes})`;
202
+ if (table && hint.index) {
203
+ const indexes = this.safeIdentifiers(hint.index);
204
+ const indexCount = Array.isArray(hint.index) ? hint.index.length : 1;
205
+ if (indexes.length === 0 || indexes.length !== indexCount) {
206
+ return "";
207
+ }
208
+ return `${hint.type}(${table} ${indexes.join(", ")})`;
188
209
  }
189
- else if (hint.table) {
190
- return `${hint.type}(${hint.table})`;
210
+ else if (table) {
211
+ return `${hint.type}(${table})`;
191
212
  }
192
213
  return "";
193
214
  // Subquery Hints
194
215
  case "SEMIJOIN":
195
216
  case "NO_SEMIJOIN":
196
217
  if (hint.strategy) {
197
- return `${hint.type}(${hint.strategy})`;
218
+ const strategy = this.safeStrategy(hint.strategy, [
219
+ "DUPSWEEDOUT", "FIRSTMATCH", "LOOSESCAN", "MATERIALIZATION",
220
+ ]);
221
+ return strategy ? `${hint.type}(${strategy})` : "";
198
222
  }
199
223
  return `${hint.type}()`;
200
- case "SUBQUERY":
201
- if (hint.strategy) {
202
- return `SUBQUERY(${hint.strategy})`;
203
- }
204
- return "";
224
+ case "SUBQUERY": {
225
+ const strategy = this.safeStrategy(hint.strategy, [
226
+ "INTOEXISTS", "MATERIALIZATION",
227
+ ]);
228
+ return strategy ? `SUBQUERY(${strategy})` : "";
229
+ }
205
230
  // Miscellaneous
206
- case "MAX_EXECUTION_TIME":
207
- if (hint.value !== undefined) {
208
- return `MAX_EXECUTION_TIME(${hint.value})`;
209
- }
210
- return "";
211
- case "RESOURCE_GROUP":
212
- if (hint.value) {
213
- return `RESOURCE_GROUP(${hint.value})`;
214
- }
215
- return "";
231
+ case "MAX_EXECUTION_TIME": {
232
+ const maxTime = this.safePositiveInteger(hint.value, 31536000000);
233
+ return maxTime !== null ? `MAX_EXECUTION_TIME(${maxTime})` : "";
234
+ }
235
+ case "RESOURCE_GROUP": {
236
+ const group = this.safeIdentifiers(hint.value)[0];
237
+ return group ? `RESOURCE_GROUP(${group})` : "";
238
+ }
216
239
  case "SET_VAR":
217
- if (hint.value) {
240
+ // name=value, where value is a number, a word, or a quoted list such
241
+ // as optimizer_switch='mrr=on,mrr_cost_based=off'
242
+ if (typeof hint.value === "string" &&
243
+ /^[a-zA-Z_][a-zA-Z0-9_]{0,63}s*=s*(?:[a-zA-Z0-9_.]{1,64}|'[a-zA-Z0-9_=,.]{1,256}')$/.test(hint.value)) {
218
244
  return `SET_VAR(${hint.value})`;
219
245
  }
220
246
  return "";
@@ -234,9 +260,10 @@ class QueryOptimizer {
234
260
  return query;
235
261
  }
236
262
  // Find table references and add USE INDEX after them
237
- const indexes = Array.isArray(hints.useIndex)
238
- ? hints.useIndex
239
- : [hints.useIndex];
263
+ const indexes = this.safeIdentifiers(hints.useIndex);
264
+ if (indexes.length === 0) {
265
+ return query;
266
+ }
240
267
  const useIndexClause = `USE INDEX (${indexes.join(", ")})`;
241
268
  // Simple approach: add after FROM clause table
242
269
  // This is a basic implementation - complex queries may need more sophisticated parsing
@@ -444,8 +444,9 @@ class SecurityLayer {
444
444
  */
445
445
  detectDangerousKeywords(cleanQuery, allowAdvancedQueries) {
446
446
  // Remove string literals to avoid false positives, and unwrap quoted
447
- // identifiers so `mysql`.`user` is still detected
448
- const queryWithoutStrings = this.maskQuotedContent(cleanQuery, true) ?? cleanQuery.replace(/`/g, "");
447
+ // identifiers so `mysql`.`user` is still detected. MySQL allows whitespace
448
+ // around the qualifier dot, so `mysql . user` is joined to mysql.user.
449
+ const queryWithoutStrings = (this.maskQuotedContent(cleanQuery, true) ?? cleanQuery.replace(/`/g, "")).replace(/\s*\.\s*/g, ".");
449
450
  for (const keyword of this.dangerousKeywords) {
450
451
  // Enhanced regex with word boundaries and case insensitivity
451
452
  const keywordRegex = new RegExp(`\\b${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
@@ -78,7 +78,9 @@ export declare class MaintenanceTools {
78
78
  error?: string;
79
79
  }>;
80
80
  /**
81
- * Flush table (close and reopen)
81
+ * Flush table(s) of the connected database (close and reopen).
82
+ * WITH READ LOCK is not supported: the lock would stay on a pooled
83
+ * connection and, without a table name, block writes server-wide.
82
84
  */
83
85
  flushTable(params: {
84
86
  table_name?: string;
@@ -252,7 +252,9 @@ class MaintenanceTools {
252
252
  }
253
253
  }
254
254
  /**
255
- * Flush table (close and reopen)
255
+ * Flush table(s) of the connected database (close and reopen).
256
+ * WITH READ LOCK is not supported: the lock would stay on a pooled
257
+ * connection and, without a table name, block writes server-wide.
256
258
  */
257
259
  async flushTable(params) {
258
260
  try {
@@ -262,25 +264,35 @@ class MaintenanceTools {
262
264
  }
263
265
  const { table_name, with_read_lock = false } = params;
264
266
  const database = dbValidation.database;
265
- let query;
267
+ if (with_read_lock) {
268
+ return {
269
+ status: "error",
270
+ error: "with_read_lock is not supported: the read lock would outlive this call on a pooled connection.",
271
+ };
272
+ }
273
+ let tableNames;
266
274
  if (table_name) {
267
275
  if (!this.security.validateIdentifier(table_name).valid) {
268
276
  return { status: "error", error: "Invalid table name" };
269
277
  }
270
- query = `FLUSH TABLES \`${database}\`.\`${table_name}\``;
271
- if (with_read_lock) {
272
- query += " WITH READ LOCK";
273
- }
278
+ tableNames = [table_name];
274
279
  }
275
280
  else {
276
- query = with_read_lock ? "FLUSH TABLES WITH READ LOCK" : "FLUSH TABLES";
281
+ // Flush only the connected database, never every table on the server
282
+ const rows = await this.db.query("SELECT TABLE_NAME AS table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'", [database]);
283
+ tableNames = rows.map((row) => row.table_name);
284
+ }
285
+ if (tableNames.length > 0) {
286
+ const tableList = tableNames
287
+ .map((name) => `\`${database}\`.\`${name.replace(/`/g, "``")}\``)
288
+ .join(", ");
289
+ await this.db.query(`FLUSH TABLES ${tableList}`);
277
290
  }
278
- await this.db.query(query);
279
291
  return {
280
292
  status: "success",
281
293
  message: table_name
282
- ? `Table '${table_name}' flushed successfully${with_read_lock ? " with read lock" : ""}`
283
- : `All tables flushed successfully${with_read_lock ? " with read lock" : ""}`,
294
+ ? `Table '${table_name}' flushed successfully`
295
+ : `${tableNames.length} table(s) in '${database}' flushed successfully`,
284
296
  };
285
297
  }
286
298
  catch (error) {
@@ -61,6 +61,15 @@ class QueryTools {
61
61
  if (finalQuery !== query) {
62
62
  optimizedQuery = finalQuery;
63
63
  }
64
+ // Hints change the SQL after validation, so validate the result too.
65
+ // The optimizer hint comment is the only comment allowed through.
66
+ const hintedValidation = this.security.validateQuery(finalQuery.replace(/\/\*\+[^*]*\*\//, " "), hasExecutePermission);
67
+ if (!hintedValidation.valid || hintedValidation.queryType !== "SELECT") {
68
+ return {
69
+ status: "error",
70
+ error: `Query validation failed after applying hints: ${hintedValidation.error || "Only SELECT queries are allowed"}`,
71
+ };
72
+ }
64
73
  }
65
74
  // Handle dry_run: return query plan and cost estimate without executing
66
75
  if (queryParams.dry_run) {
package/manifest.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mysql-mcp",
3
3
  "description": "A Model Context Protocol for MySQL database interaction",
4
- "version": "1.45.2",
4
+ "version": "1.46.0",
5
5
  "tools": [
6
6
  {
7
7
  "name": "list_databases",
@@ -2660,7 +2660,7 @@
2660
2660
  },
2661
2661
  {
2662
2662
  "name": "optimize_table",
2663
- "description": "Optimizes a table to reclaim unused space and defragment data.",
2663
+ "description": "Optimizes a table to reclaim unused space and defragment data. Rebuilds the table, so it requires 'ddl' permission.",
2664
2664
  "input_schema": {
2665
2665
  "type": "object",
2666
2666
  "properties": {
@@ -2717,7 +2717,7 @@
2717
2717
  },
2718
2718
  {
2719
2719
  "name": "repair_table",
2720
- "description": "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only).",
2720
+ "description": "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only). Requires 'ddl' permission.",
2721
2721
  "input_schema": {
2722
2722
  "type": "object",
2723
2723
  "properties": {
@@ -2795,17 +2795,13 @@
2795
2795
  },
2796
2796
  {
2797
2797
  "name": "flush_table",
2798
- "description": "Flushes table(s) - closes and reopens them.",
2798
+ "description": "Flushes table(s) in the connected database - closes and reopens them. Requires 'ddl' permission.",
2799
2799
  "input_schema": {
2800
2800
  "type": "object",
2801
2801
  "properties": {
2802
2802
  "table_name": {
2803
2803
  "type": "string",
2804
- "description": "Optional: specific table (omit for all tables)"
2805
- },
2806
- "with_read_lock": {
2807
- "type": "boolean",
2808
- "description": "Acquire read lock after flushing"
2804
+ "description": "Optional: specific table (omit for all tables in the connected database)"
2809
2805
  },
2810
2806
  "database": {
2811
2807
  "type": "string",
@@ -3028,7 +3024,7 @@
3028
3024
  },
3029
3025
  {
3030
3026
  "name": "optimize_fulltext",
3031
- "description": "Optimizes a table to update FULLTEXT index statistics and reclaim space. Use this after bulk inserts or updates to improve search performance.",
3027
+ "description": "Optimizes a table to update FULLTEXT index statistics and reclaim space. Use this after bulk inserts or updates to improve search performance. Rebuilds the table, so it requires 'ddl' permission.",
3032
3028
  "input_schema": {
3033
3029
  "type": "object",
3034
3030
  "properties": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@berthojoris/mcp-mysql-server",
3
- "version": "1.45.2",
3
+ "version": "1.46.0",
4
4
  "description": "Model Context Protocol server for MySQL database integration with dynamic per-project permissions",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",