@berthojoris/mcp-mysql-server 1.43.2 → 1.43.5

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,12 +5,41 @@ 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.43.2] - 2026-07-23
9
-
10
- ### Changed
11
- - Version bump to `1.43.2` for npm publish.
12
- - Synchronized version across `package.json`, `src/mcp-server.ts`, `DOCUMENTATIONS.md`, `README.md`, and `manifest.json`.
13
-
8
+ ## [1.43.5] - 2026-10-12
9
+
10
+ ### Added
11
+ - Added `SECURITY.md` defining supported versions, private vulnerability reporting via GitHub Private Vulnerability Reporting, report requirements, and response/disclosure expectations (acknowledgment within 7 days, coordinated disclosure).
12
+
13
+ ### Changed
14
+ - Linked the security reporting policy from `README.md` and `DOCUMENTATIONS.md`, and synchronized version metadata to `1.43.5`; the catalog remains at 88 tools.
15
+
16
+ ## [1.43.4] - 2026-10-12
17
+
18
+ ### Fixed
19
+ - Authorized `EXPLAIN ANALYZE` statements as the SQL operation they execute. MySQL 8.0.18+ runs the wrapped statement (including multi-table UPDATE/DELETE), so it now requires the matching permission: `read` for SELECT, `update` or `execute` for UPDATE, and `delete` for DELETE. This closes a bypass where `transaction` plus `list`/`read` could run `EXPLAIN ANALYZE UPDATE/DELETE` through `execute_in_transaction` without the corresponding write permission.
20
+
21
+ ### Changed
22
+ - Updated permission documentation for `EXPLAIN ANALYZE` (plan-only `EXPLAIN` remains an information query) and synchronized version metadata to `1.43.4`; the catalog remains at 88 tools.
23
+
24
+ ## [1.43.3] - 2026-10-12
25
+
26
+ ### Fixed
27
+ - Enforced permission/category checks at tool execution, including the Cursor bridge and its destination tool.
28
+ - Required SQL operation permissions inside transactions; DDL also respects the schema tool category.
29
+ - Required both `utility` and `read` for CSV exports, including tool discovery and direct execution.
30
+ - Restricted `execute_write_query` to INSERT/UPDATE/DELETE, preventing DDL through the write-query tool.
31
+ - Applied mandatory dangerous SQL checks regardless of `execute` permission, including information queries and query repair.
32
+
33
+ ### Changed
34
+ - Updated permission documentation and tool descriptions. Advanced SELECT features still require `execute`.
35
+ - Synchronized version metadata and lockfile to `1.43.3`; the catalog remains at 88 tools.
36
+
37
+ ## [1.43.2] - 2026-07-23
38
+
39
+ ### Changed
40
+ - Version bump to `1.43.2` for npm publish.
41
+ - Synchronized version across `package.json`, `src/mcp-server.ts`, `DOCUMENTATIONS.md`, `README.md`, and `manifest.json`.
42
+
14
43
  ## [1.43.1] - 2026-05-26
15
44
 
16
45
  ### Fixed
package/DOCUMENTATIONS.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # MySQL MCP Server - Documentation
2
2
 
3
- **Last Updated:** 2026-07-23 05:00:00
4
- **Version:** 1.43.2
3
+ **Last Updated:** 2026-10-12 21:16:54
4
+ **Version:** 1.43.5
5
5
  **Total Tools:** 88
6
6
 
7
7
  Comprehensive documentation for the MySQL MCP Server. For quick start, see [README.md](README.md).
@@ -93,6 +93,8 @@ Or execute SQL directly with automatic routing:
93
93
 
94
94
  Supported `mode` values are `auto`, `select`, `write`, and `ddl`. Set `MYSQL_MCP_CURSOR_REQUEST_FILE` to override the request file path.
95
95
 
96
+ The bridge requires `utility` permission and the `utilities` category when category filtering is enabled. The requested destination tool must also be enabled. Disabled tools cannot be called directly or through the bridge.
97
+
96
98
  ---
97
99
 
98
100
  ### AI Agent Tool Discovery
@@ -126,6 +128,16 @@ For CSV exports, use `export_table_to_csv` for table-based exports and `export_q
126
128
  Tool enabled = (Has Permission) AND (Has Category OR No categories specified)
127
129
  ```
128
130
 
131
+ CSV exports require both `utility` and `read` permissions; their category remains `utilities`.
132
+
133
+ `execute_in_transaction` requires `transaction` plus the permission for the SQL operation: `read` for SELECT, `create` or `execute` for INSERT, `update` or `execute` for UPDATE, and `delete` for DELETE. DDL also requires `ddl` and an enabled `execute_ddl` tool. Transaction permission alone does not authorize reading or modifying data.
134
+
135
+ Information queries such as SHOW/DESCRIBE/EXPLAIN require `list` or `read`. MySQL DDL may implicitly commit, even when called through a transaction tool.
136
+
137
+ `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).
138
+
139
+ `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.
140
+
129
141
  ---
130
142
 
131
143
  ## Tool Categories
@@ -162,10 +174,9 @@ Tool enabled = (Has Permission) AND (Has Category OR No categories specified)
162
174
  - `infer_seed_rules` - Infer advanced generators from schema, samples, unique indexes, and domain presets
163
175
  - `seed_from_template` - Create reusable plan-first seed workflows for ecommerce, POS, and CRM domains
164
176
 
165
- ### 5. Query Management (3 tools)
177
+ ### 5. Query Management (2 tools)
166
178
  - `run_select_query` - Execute SELECT queries
167
179
  - `execute_write_query` - Execute INSERT/UPDATE (DELETE requires the `delete` permission)
168
- - `repair_query` - Diagnose and fix SQL errors
169
180
 
170
181
  ### 6. Schema Management (4 tools)
171
182
  - `create_table` - Create new tables
@@ -177,11 +188,12 @@ Tool enabled = (Has Permission) AND (Has Category OR No categories specified)
177
188
  - `export_table_to_csv` - Export table data to CSV
178
189
  - `export_query_to_csv` - Export SELECT query results to CSV
179
190
 
180
- ### 8. Index Management (10 tools)
191
+ ### 8. Index Management (11 tools)
181
192
  - `list_indexes` - List table indexes
182
193
  - `get_index_info` - Get index details
183
194
  - `create_index` - Create indexes
184
195
  - `drop_index` - Drop indexes
196
+ - `analyze_index` - Analyze and update index statistics
185
197
  - `create_fulltext_index` - Create FULLTEXT indexes for text search
186
198
  - `fulltext_search` - Perform full-text search with MATCH AGAINST
187
199
  - `get_fulltext_info` - Get FULLTEXT index information
@@ -445,11 +457,16 @@ await mcp.call("commit_transaction", {});
445
457
  - **Layer 1**: Broad permission categories (list, read, create, etc.)
446
458
  - **Layer 2**: Fine-grained tool category filtering
447
459
  - **Tool-level**: Each tool requires specific permissions
460
+ - **Execution-time enforcement**: Tool permissions and categories are checked for every call, including file-backed Cursor requests.
461
+ - **Mandatory SQL restrictions**: File access, account/privilege changes, dangerous server operations, comments, and multiple statements remain blocked even with `execute`. Execute permission permits advanced SELECT features, not bypassing these restrictions.
462
+
463
+ ### Vulnerability Reporting
464
+
465
+ Suspected security issues must be reported privately via GitHub Private Vulnerability Reporting; see `SECURITY.md` for the policy, reporting requirements, and disclosure timeline (added 2026-10-12 21:16:54).
448
466
 
449
467
  ### Data Protection
450
468
 
451
469
  - **PII Masking**: Automatic sensitive data redaction in exports
452
- - **Safe Exports**: `safe_export_table` masks emails, credit cards, passwords
453
470
  - **Query Validation**: Input validation and SQL injection prevention
454
471
 
455
472
  ### Connection Security
@@ -460,37 +477,6 @@ await mcp.call("commit_transaction", {});
460
477
 
461
478
  ---
462
479
 
463
- ## Migration & Schema Management
464
-
465
- ### Schema Versioning
466
-
467
- Complete migration support with tracking:
468
-
469
- ```javascript
470
- // Initialize migration tracking
471
- await mcp.call("init_migrations_table", {});
472
-
473
- // Create migration
474
- await mcp.call("create_migration", {
475
- name: "add_user_avatar",
476
- up_sql: "ALTER TABLE users ADD COLUMN avatar VARCHAR(255);",
477
- down_sql: "ALTER TABLE users DROP COLUMN avatar;"
478
- });
479
-
480
- // Apply migrations
481
- await mcp.call("apply_migrations", { dry_run: false });
482
- ```
483
-
484
- ### Schema Comparison
485
-
486
- ```javascript
487
- // Compare table structures
488
- await mcp.call("compare_table_structure", {
489
- table1: "users_old",
490
- table2: "users_new"
491
- });
492
- ```
493
-
494
480
  ---
495
481
 
496
482
  ## Troubleshooting
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-07-23 05:00:00
7
+ **Last Updated:** 2026-10-22 19:50:16
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)
@@ -271,6 +271,18 @@ Control database access with a **dual-layer filtering system** that provides bot
271
271
  | `transaction` | BEGIN, COMMIT, ROLLBACK | ACID operations |
272
272
  | `utility` | Connection testing, diagnostics | Troubleshooting |
273
273
 
274
+ **Security changes in v1.43.4:**
275
+ - `EXPLAIN ANALYZE` runs the statement it wraps (MySQL 8.0.18+), so it now requires that statement's permission: `delete` for DELETE, `update` or `execute` for UPDATE, `read` for SELECT. Plan-only `EXPLAIN` still needs just `list` or `read`.
276
+
277
+ **Security changes in v1.43.3:**
278
+ - CSV exports require both `utility` and `read`; enable the `utilities` category when filtering categories.
279
+ - SQL within a transaction requires the corresponding operation permission. `transaction` alone does not permit reads or writes.
280
+ - `execute_write_query` accepts only INSERT/UPDATE/DELETE. DDL requires enabled DDL tools.
281
+ - Disabled tools cannot be called directly or through the Cursor bridge. The bridge requires `utility` and an enabled destination tool.
282
+ - `execute` does not bypass mandatory SQL safety restrictions, including file access and account/privilege changes.
283
+
284
+ Report suspected security issues privately via [Private Vulnerability Reporting](https://github.com/berthojoris/mysql-mcp/security/advisories/new); see [SECURITY.md](SECURITY.md) for the policy.
285
+
274
286
  Common configuration examples are documented in **[DOCUMENTATIONS.md → Category Filtering System](DOCUMENTATIONS.md#🆕-category-filtering-system)**.
275
287
 
276
288
  ---
@@ -292,10 +304,10 @@ Use documentation categories to fine-tune which tools are exposed (Layer 2):
292
304
  | `stored_procedures` | Create, execute, and manage stored procedures | `create_stored_procedure, drop_stored_procedure, execute_stored_procedure, get_stored_procedure_info, list_stored_procedures, show_create_procedure` |
293
305
  | `views_management` | Create and manage database views | `alter_view, create_view, drop_view, get_view_info, list_views, show_create_view` |
294
306
  | `triggers_management` | Create and manage database triggers | `create_trigger, drop_trigger, get_trigger_info, list_triggers, show_create_trigger` |
295
- | `index_management` | Optimize performance with index management | `analyze_index, create_index, drop_index, get_index_info, list_indexes` |
307
+ | `index_management` | Optimize performance with index and fulltext management | `analyze_index, create_fulltext_index, create_index, drop_fulltext_index, drop_index, fulltext_search, get_fulltext_info, get_fulltext_stats, get_index_info, list_indexes, optimize_fulltext` |
296
308
  | `constraint_management` | Manage data integrity constraints | `add_check_constraint, add_foreign_key, add_unique_constraint, drop_constraint, drop_foreign_key, list_constraints, list_foreign_keys` |
297
309
  | `table_maintenance` | Table optimization, repair, and maintenance | `analyze_table, check_table, flush_table, get_table_size, get_table_status, optimize_table, repair_table, truncate_table` |
298
- | `query_optimization` | Analyze and optimize SQL queries | `analyze_query, get_optimization_hints` |
310
+ | `query_optimization` | Analyze and optimize SQL queries | `analyze_query, get_optimization_hints, repair_query` |
299
311
  | `analysis` | Data analysis, schema discovery, and reporting tools | `find_tables_by_keyword, get_column_statistics, get_database_summary, get_schema_erd, get_schema_rag_context, search_data_across_tables, search_schema` |
300
312
 
301
313
  <details>
@@ -324,13 +336,14 @@ The server exposes **88 tools** organized into categories (CRUD, seed, schema, d
324
336
  For comprehensive documentation, see **[DOCUMENTATIONS.md](DOCUMENTATIONS.md)**:
325
337
 
326
338
  - **DDL Operations** - Create, alter, and drop tables
327
- - **Data Export Tools** - Export to CSV, JSON, and SQL formats
339
+ - **Data Export Tools** - Export data to CSV format
328
340
  - **Relational Data Seeder** - Plan, preview, execute, validate, infer rules, and template FK-aware dummy data
329
- - **Data Import Tools** - Import from CSV and JSON sources
330
- - **Data Migration Tools** - Copy, move, clone, compare, and sync data
331
- - **Schema Versioning** - Version control for database schema changes
341
+ - **Full-Text Search** - Create and search FULLTEXT indexes with multiple search modes
332
342
  - **Transaction Management** - ACID transactions
333
343
  - **Stored Procedures** - Create and execute with IN/OUT/INOUT parameters
344
+ - **Views & Triggers** - Manage database views and triggers
345
+ - **Index & Constraint Management** - Optimize performance and enforce data integrity
346
+ - **Table Maintenance** - Analyze, optimize, check, and repair tables
334
347
  - **Query Logging** - See all SQL queries executed automatically
335
348
  - **Security Features** - Built-in security and best practices
336
349
  - **Bulk Operations** - High-performance batch processing
@@ -178,6 +178,14 @@ exports.toolCategoryMap = {
178
178
  getFulltextStats: ToolCategory.LIST,
179
179
  optimizeFulltext: ToolCategory.UTILITY,
180
180
  };
181
+ const toolAdditionalPermissions = {
182
+ exportTableToCSV: [ToolCategory.READ],
183
+ exportTableToCsv: [ToolCategory.READ],
184
+ export_table_to_csv: [ToolCategory.READ],
185
+ exportQueryToCSV: [ToolCategory.READ],
186
+ exportQueryToCsv: [ToolCategory.READ],
187
+ export_query_to_csv: [ToolCategory.READ],
188
+ };
181
189
  /**
182
190
  * Map of tool names to their documentation categories (New Enhanced System)
183
191
  */
@@ -469,6 +477,9 @@ class FeatureConfig {
469
477
  if (!hasPermission) {
470
478
  return false;
471
479
  }
480
+ if (!(toolAdditionalPermissions[toolName] || []).every((permission) => this.enabledLegacyCategories.has(permission))) {
481
+ return false;
482
+ }
472
483
  // Layer 2: Check category (documentation category) if dual-layer mode
473
484
  if (this.useDualLayer) {
474
485
  const hasCategory = docCategory
@@ -488,6 +499,11 @@ class FeatureConfig {
488
499
  if (!docCategory && !legacyCategory) {
489
500
  return `Unknown tool '${toolName}'. This tool is not recognized by the MCP server.`;
490
501
  }
502
+ const missingPermission = (toolAdditionalPermissions[toolName] || []).find((permission) => !this.enabledLegacyCategories.has(permission));
503
+ if (legacyCategory && this.enabledLegacyCategories.has(legacyCategory) && missingPermission) {
504
+ return (`Permission denied: This tool also requires '${missingPermission}' permission (Layer 1). ` +
505
+ `Add '${missingPermission}' to the permissions argument.`);
506
+ }
491
507
  const isAllEnabled = !this.originalPermissionsString.trim() &&
492
508
  !this.originalCategoriesString.trim();
493
509
  if (isAllEnabled) {
package/dist/index.js CHANGED
@@ -149,16 +149,6 @@ class MySQLMCP {
149
149
  if (!check.enabled) {
150
150
  return { status: "error", error: check.error };
151
151
  }
152
- // Additional security check - block DDL unless DDL permission is enabled
153
- if (this.security.hasDangerousOperations(params.query)) {
154
- // Check if DDL permission is enabled
155
- if (!this.featureConfig.isCategoryEnabled("ddl")) {
156
- return {
157
- status: "error",
158
- error: 'DDL operations (DROP, TRUNCATE, ALTER, CREATE) require the "ddl" permission. Use execute_ddl tool or add "ddl" to permissions.',
159
- };
160
- }
161
- }
162
152
  return await this.queryTools.executeWriteQuery(params);
163
153
  }
164
154
  // Analysis Tools
@@ -18,7 +18,7 @@ const toolArgumentValidation_js_1 = require("./tools/toolArgumentValidation.js")
18
18
  const permissions = process.env.MCP_PERMISSIONS || process.env.MCP_CONFIG || "";
19
19
  const categories = process.env.MCP_CATEGORIES || "";
20
20
  const SERVER_NAME = "mysql-mcp-server";
21
- const SERVER_VERSION = "1.43.2";
21
+ const SERVER_VERSION = "1.43.5";
22
22
  // Declare the MySQL MCP instance (will be initialized in main())
23
23
  let mysqlMCP;
24
24
  // Define all available tools with their schemas
@@ -1056,7 +1056,7 @@ const TOOLS = [
1056
1056
  },
1057
1057
  {
1058
1058
  name: "cursor_execute_request",
1059
- description: "Cursor compatibility bridge for clients that can call MCP tools but cannot send arguments. Reads .cursor/mysql-mcp-request.json (or MYSQL_MCP_CURSOR_REQUEST_FILE) and dispatches to the requested MySQL MCP tool. The request file supports {\"tool\":\"execute_ddl\",\"arguments\":{\"query\":\"DROP TABLE IF EXISTS t;\"}} or direct SQL with {\"query\":\"...\",\"mode\":\"auto\"}.",
1059
+ description: "Cursor compatibility bridge for clients that can call MCP tools but cannot send arguments. Requires utility permission and an enabled destination tool. Reads .cursor/mysql-mcp-request.json (or MYSQL_MCP_CURSOR_REQUEST_FILE) and dispatches to the requested MySQL MCP tool. The request file supports {\"tool\":\"execute_ddl\",\"arguments\":{\"query\":\"DROP TABLE IF EXISTS t;\"}} or direct SQL with {\"query\":\"...\",\"mode\":\"auto\"}.",
1060
1060
  inputSchema: {
1061
1061
  type: "object",
1062
1062
  properties: {},
@@ -1160,7 +1160,7 @@ const TOOLS = [
1160
1160
  },
1161
1161
  {
1162
1162
  name: "execute_in_transaction",
1163
- description: "Executes a SQL query within an existing transaction context. The query becomes part of the transaction and will be committed or rolled back with it. Use after begin_transaction.",
1163
+ description: "Executes a SQL query within an existing transaction context. Requires transaction plus the SQL operation permission: read for SELECT, create or execute for INSERT, update or execute for UPDATE, delete for DELETE. DDL requires an enabled execute_ddl tool and may implicitly commit. EXPLAIN ANALYZE requires the permission of the statement it executes. Use after begin_transaction.",
1164
1164
  inputSchema: {
1165
1165
  type: "object",
1166
1166
  properties: {
@@ -1325,7 +1325,7 @@ const TOOLS = [
1325
1325
  // Data Export Tools
1326
1326
  {
1327
1327
  name: "export_table_to_csv",
1328
- description: "📄 Exports table data to CSV format with filtering, pagination, and sorting. For sensitive data, use safe_export_table instead which includes automatic data masking.",
1328
+ description: "📄 Exports table data to CSV format with filtering, pagination, and sorting. Requires both utility and read permissions.",
1329
1329
  inputSchema: {
1330
1330
  type: "object",
1331
1331
  properties: {
@@ -1381,7 +1381,7 @@ const TOOLS = [
1381
1381
  },
1382
1382
  {
1383
1383
  name: "export_query_to_csv",
1384
- description: "📄 Executes a SELECT query and exports results to CSV format. Supports complex queries with JOINs and aggregations. For sensitive data, consider using safe_export_table or adding manual data masking.",
1384
+ description: "📄 Executes a SELECT query and exports results to CSV format. Requires both utility and read permissions. Supports complex queries with JOINs and aggregations.",
1385
1385
  inputSchema: {
1386
1386
  type: "object",
1387
1387
  properties: {
@@ -2306,6 +2306,15 @@ const getRuntimeToolCatalog = () => {
2306
2306
  serverVersion: SERVER_VERSION,
2307
2307
  };
2308
2308
  };
2309
+ const assertToolEnabled = (toolName) => {
2310
+ const tool = TOOLS.find((candidate) => candidate.name === toolName);
2311
+ if (!tool) {
2312
+ throw new Error(`Unknown tool: ${toolName}`);
2313
+ }
2314
+ if (!(0, toolRegistry_js_1.isToolEnabled)(mysqlMCP, tool)) {
2315
+ throw new Error(`Permission denied: Tool '${toolName}' is disabled by the active permissions or categories.`);
2316
+ }
2317
+ };
2309
2318
  const getCursorRequestFilePath = () => {
2310
2319
  const configuredPath = process.env.MYSQL_MCP_CURSOR_REQUEST_FILE ||
2311
2320
  process.env.MCP_MYSQL_REQUEST_FILE ||
@@ -2341,6 +2350,7 @@ const executeToolByName = async (toolName, args = {}) => {
2341
2350
  if (toolName === "cursor_execute_request") {
2342
2351
  throw new Error("cursor_execute_request cannot dispatch to itself");
2343
2352
  }
2353
+ assertToolEnabled(toolName);
2344
2354
  const validation = (0, toolArgumentValidation_js_1.validateToolArguments)(toolName, args);
2345
2355
  if (!validation.valid) {
2346
2356
  throw new Error(`Validation Error: ${validation.errors?.join(", ") || "Invalid arguments"}`);
@@ -2356,6 +2366,7 @@ const executeToolByName = async (toolName, args = {}) => {
2356
2366
  return await method.call(mysqlMCP, args);
2357
2367
  };
2358
2368
  const executeCursorRequest = async () => {
2369
+ assertToolEnabled("cursor_execute_request");
2359
2370
  const requestFilePath = getCursorRequestFilePath();
2360
2371
  if (!fs_1.default.existsSync(requestFilePath)) {
2361
2372
  return {
@@ -2408,6 +2419,7 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
2408
2419
  };
2409
2420
  }
2410
2421
  try {
2422
+ assertToolEnabled(name);
2411
2423
  let result;
2412
2424
  switch (name) {
2413
2425
  case "list_databases":
@@ -14,8 +14,17 @@ export declare class SecurityLayer {
14
14
  isToolEnabled(toolName: string): boolean;
15
15
  /**
16
16
  * Check if a query is a read-only information query (SHOW, DESCRIBE, EXPLAIN, etc.)
17
+ * Note: EXPLAIN ANALYZE is handled separately by validateQuery because MySQL
18
+ * executes the wrapped statement, so it is authorized as the inner statement type.
17
19
  */
18
20
  private isInformationQuery;
21
+ /**
22
+ * Authorize the SQL operation separately from the enclosing tool.
23
+ */
24
+ validateQueryPermissions(queryType: string): {
25
+ valid: boolean;
26
+ error?: string;
27
+ };
19
28
  /**
20
29
  * Validate input against a JSON schema
21
30
  */
@@ -33,9 +42,9 @@ export declare class SecurityLayer {
33
42
  /**
34
43
  * Enhanced SQL query validation for security issues
35
44
  * @param query - The SQL query to validate
36
- * @param bypassDangerousCheck - If true, skips dangerous keyword check (for users with 'execute' permission)
45
+ * @param allowAdvancedQueries - Allows advanced SELECT features, never dangerous operations
37
46
  */
38
- validateQuery(query: string, bypassDangerousCheck?: boolean): {
47
+ validateQuery(query: string, allowAdvancedQueries?: boolean): {
39
48
  valid: boolean;
40
49
  error?: string;
41
50
  queryType?: string;
@@ -71,7 +80,7 @@ export declare class SecurityLayer {
71
80
  /**
72
81
  * Check if a query is a read-only SELECT query or information query (SHOW, DESCRIBE, etc.)
73
82
  */
74
- isReadOnlyQuery(query: string, bypassDangerousCheck?: boolean): boolean;
83
+ isReadOnlyQuery(query: string, allowAdvancedQueries?: boolean): boolean;
75
84
  /**
76
85
  * Check if a query contains dangerous operations
77
86
  */
@@ -45,11 +45,39 @@ class SecurityLayer {
45
45
  }
46
46
  /**
47
47
  * Check if a query is a read-only information query (SHOW, DESCRIBE, EXPLAIN, etc.)
48
+ * Note: EXPLAIN ANALYZE is handled separately by validateQuery because MySQL
49
+ * executes the wrapped statement, so it is authorized as the inner statement type.
48
50
  */
49
51
  isInformationQuery(query) {
50
- const trimmedQuery = query.trim().toUpperCase();
51
- const readOnlyCommands = ["SHOW", "DESCRIBE", "DESC", "EXPLAIN", "HELP"];
52
- return readOnlyCommands.some((cmd) => trimmedQuery.startsWith(cmd));
52
+ return /^(SHOW|DESCRIBE|DESC|EXPLAIN|HELP)\b/i.test(query.trim());
53
+ }
54
+ /**
55
+ * Authorize the SQL operation separately from the enclosing tool.
56
+ */
57
+ validateQueryPermissions(queryType) {
58
+ if (this.ddlOperations.includes(queryType)) {
59
+ return this.featureConfig.isToolEnabled("executeDdl")
60
+ ? { valid: true }
61
+ : { valid: false, error: this.featureConfig.getPermissionError("executeDdl") };
62
+ }
63
+ const requiredPermissions = {
64
+ SELECT: [featureConfig_js_1.ToolCategory.READ],
65
+ INSERT: [featureConfig_js_1.ToolCategory.CREATE, featureConfig_js_1.ToolCategory.EXECUTE],
66
+ UPDATE: [featureConfig_js_1.ToolCategory.UPDATE, featureConfig_js_1.ToolCategory.EXECUTE],
67
+ DELETE: [featureConfig_js_1.ToolCategory.DELETE],
68
+ INFORMATION: [featureConfig_js_1.ToolCategory.LIST, featureConfig_js_1.ToolCategory.READ],
69
+ };
70
+ const permissions = requiredPermissions[queryType];
71
+ if (!permissions) {
72
+ return { valid: false, error: "Query type not allowed" };
73
+ }
74
+ if (!permissions.some((permission) => this.featureConfig.isCategoryEnabled(permission))) {
75
+ return {
76
+ valid: false,
77
+ error: `Permission denied: ${queryType} requires ${permissions.map((permission) => `'${permission}'`).join(" or ")} permission.`,
78
+ };
79
+ }
80
+ return { valid: true };
53
81
  }
54
82
  /**
55
83
  * Validate input against a JSON schema
@@ -132,9 +160,9 @@ class SecurityLayer {
132
160
  /**
133
161
  * Enhanced SQL query validation for security issues
134
162
  * @param query - The SQL query to validate
135
- * @param bypassDangerousCheck - If true, skips dangerous keyword check (for users with 'execute' permission)
163
+ * @param allowAdvancedQueries - Allows advanced SELECT features, never dangerous operations
136
164
  */
137
- validateQuery(query, bypassDangerousCheck = false) {
165
+ validateQuery(query, allowAdvancedQueries = false) {
138
166
  if (!query || typeof query !== "string") {
139
167
  return { valid: false, error: "Query must be a non-empty string" };
140
168
  }
@@ -155,21 +183,28 @@ class SecurityLayer {
155
183
  }
156
184
  // Remove trailing semicolon for analysis
157
185
  const cleanQuery = trimmedQuery.replace(/;$/, "");
158
- // Check if it's an information query (SHOW, DESCRIBE, EXPLAIN, etc.) - these are always allowed
159
- if (this.isInformationQuery(trimmedQuery)) {
160
- return { valid: true, queryType: "INFORMATION" };
186
+ const dangerousCheck = this.detectDangerousKeywords(cleanQuery, allowAdvancedQueries);
187
+ if (!dangerousCheck.valid) {
188
+ return dangerousCheck;
189
+ }
190
+ // MySQL 8.0.18+ actually executes the statement wrapped by EXPLAIN ANALYZE,
191
+ // including multi-table UPDATE/DELETE. Such queries are authorized as the
192
+ // inner statement instead of being treated as read-only information queries.
193
+ const explainAnalyzeMatch = cleanQuery.match(/^(?:EXPLAIN|DESCRIBE|DESC)\s+ANALYZE\s+(?:FORMAT\s*=\s*TREE\s+)?(.+)$/is);
194
+ // Information queries still require permission and mandatory safety checks.
195
+ if (!explainAnalyzeMatch && this.isInformationQuery(trimmedQuery)) {
196
+ const permissionCheck = this.validateQueryPermissions("INFORMATION");
197
+ return permissionCheck.valid
198
+ ? { valid: true, queryType: "INFORMATION" }
199
+ : permissionCheck;
161
200
  }
162
- // Enhanced query type detection with better parsing
163
- const queryTypeResult = this.detectQueryType(cleanQuery);
201
+ // Enhanced query type detection with better parsing.
202
+ // EXPLAIN ANALYZE is classified by the inner statement it executes.
203
+ const queryTypeResult = this.detectQueryType(explainAnalyzeMatch ? explainAnalyzeMatch[1].trim() : cleanQuery);
164
204
  if (!queryTypeResult.valid) {
165
205
  return queryTypeResult;
166
206
  }
167
- // Enhanced dangerous keyword detection
168
- if (!bypassDangerousCheck) {
169
- const dangerousCheck = this.detectDangerousKeywords(cleanQuery);
170
- if (!dangerousCheck.valid) {
171
- return dangerousCheck;
172
- }
207
+ if (!allowAdvancedQueries) {
173
208
  // Additional checks for specific query types
174
209
  if (queryTypeResult.queryType === "SELECT") {
175
210
  const selectCheck = this.validateSelectQuery(cleanQuery);
@@ -264,23 +299,9 @@ class SecurityLayer {
264
299
  ];
265
300
  for (const { type, pattern } of queryTypePatterns) {
266
301
  if (pattern.test(cleanQuery)) {
267
- // Check DDL permissions
268
- if (this.ddlOperations.includes(type)) {
269
- if (!this.featureConfig.isCategoryEnabled(featureConfig_js_1.ToolCategory.DDL)) {
270
- return {
271
- valid: false,
272
- error: `DDL operation '${type}' requires 'ddl' permission. Add 'ddl' to your permissions configuration.`,
273
- };
274
- }
275
- }
276
- // DELETE requires explicit delete permission (execute alone is not sufficient)
277
- if (type === "DELETE") {
278
- if (!this.featureConfig.isCategoryEnabled(featureConfig_js_1.ToolCategory.DELETE)) {
279
- return {
280
- valid: false,
281
- error: "DELETE operation requires 'delete' permission. Add 'delete' to your permissions configuration, or use delete_record / bulk_delete.",
282
- };
283
- }
302
+ const permissionCheck = this.validateQueryPermissions(type);
303
+ if (!permissionCheck.valid) {
304
+ return permissionCheck;
284
305
  }
285
306
  return { valid: true, queryType: type };
286
307
  }
@@ -290,16 +311,18 @@ class SecurityLayer {
290
311
  /**
291
312
  * Enhanced dangerous keyword detection
292
313
  */
293
- detectDangerousKeywords(cleanQuery) {
314
+ detectDangerousKeywords(cleanQuery, allowAdvancedQueries) {
294
315
  // Remove string literals to avoid false positives
295
- const queryWithoutStrings = cleanQuery.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g, '');
316
+ const queryWithoutStrings = cleanQuery
317
+ .replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g, '')
318
+ .replace(/`([^`]*)`/g, "$1");
296
319
  for (const keyword of this.dangerousKeywords) {
297
320
  // Enhanced regex with word boundaries and case insensitivity
298
321
  const keywordRegex = new RegExp(`\\b${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
299
322
  if (keywordRegex.test(queryWithoutStrings)) {
300
323
  return {
301
324
  valid: false,
302
- error: `Dangerous keyword detected: ${keyword}. This requires 'execute' permission.`,
325
+ error: `Dangerous keyword detected: ${keyword}. This operation is not allowed.`,
303
326
  };
304
327
  }
305
328
  }
@@ -307,7 +330,6 @@ class SecurityLayer {
307
330
  const dangerousPatterns = [
308
331
  /\b(LOAD_FILE|INTO\s+OUTFILE|INTO\s+DUMPFILE)\b/i,
309
332
  /\b(GRANT|REVOKE|CREATE\s+USER|DROP\s+USER|ALTER\s+USER|SET\s+PASSWORD|RENAME\s+USER)\b/i,
310
- /\b(INFORMATION_SCHEMA\.|MYSQL\.|PERFORMANCE_SCHEMA\.|SYS\.)\b/i,
311
333
  /\b(SLEEP|BENCHMARK|GET_LOCK|RELEASE_LOCK)\b/i,
312
334
  /\b(PREPARE|EXECUTE|DEALLOCATE\s+PREPARE)\b/i,
313
335
  /\b(LOAD\s+DATA|SELECT\s+.*\s+INTO\s+OUTFILE|SELECT\s+.*\s+INTO\s+DUMPFILE)\b/i,
@@ -320,10 +342,16 @@ class SecurityLayer {
320
342
  if (pattern.test(queryWithoutStrings)) {
321
343
  return {
322
344
  valid: false,
323
- error: "Dangerous operation detected. This requires 'execute' permission.",
345
+ error: "Dangerous operation detected. This operation is not allowed.",
324
346
  };
325
347
  }
326
348
  }
349
+ if (!allowAdvancedQueries && /\b(INFORMATION_SCHEMA\.|MYSQL\.|PERFORMANCE_SCHEMA\.|SYS\.)\b/i.test(queryWithoutStrings)) {
350
+ return {
351
+ valid: false,
352
+ error: "System schema queries require 'execute' permission.",
353
+ };
354
+ }
327
355
  return { valid: true };
328
356
  }
329
357
  /**
@@ -413,14 +441,9 @@ class SecurityLayer {
413
441
  /**
414
442
  * Check if a query is a read-only SELECT query or information query (SHOW, DESCRIBE, etc.)
415
443
  */
416
- isReadOnlyQuery(query, bypassDangerousCheck = false) {
417
- // Check if it's an information query first (SHOW, DESCRIBE, EXPLAIN, etc.)
418
- if (this.isInformationQuery(query)) {
419
- return true;
420
- }
421
- // Check if it's a SELECT query
422
- const validation = this.validateQuery(query, bypassDangerousCheck);
423
- return validation.valid && validation.queryType === "SELECT";
444
+ isReadOnlyQuery(query, allowAdvancedQueries = false) {
445
+ const validation = this.validateQuery(query, allowAdvancedQueries);
446
+ return validation.valid && (validation.queryType === "SELECT" || validation.queryType === "INFORMATION");
424
447
  }
425
448
  /**
426
449
  * Check if a query contains dangerous operations
@@ -40,7 +40,7 @@ class AiTools {
40
40
  // 2. Validate query generally (security check)
41
41
  // We assume this tool is used by an agent who might have 'read' permissions at least.
42
42
  // If the query is unsafe (e.g. injection), we return that.
43
- const validation = this.security.validateQuery(query, true); // validate with execute permission simulation to check structure
43
+ const validation = this.security.validateQuery(query, this.security.hasExecutePermission());
44
44
  if (!validation.valid) {
45
45
  return {
46
46
  status: "error",
@@ -94,6 +94,10 @@ class DataExportTools {
94
94
  */
95
95
  async exportTableToCSV(params) {
96
96
  try {
97
+ const readPermission = this.security.validateQueryPermissions("SELECT");
98
+ if (!readPermission.valid) {
99
+ return { status: "error", error: readPermission.error };
100
+ }
97
101
  const { table_name, filters = [], pagination, sorting, include_headers = true, } = params;
98
102
  // Validate table name
99
103
  const tableValidation = this.security.validateIdentifier(table_name);
@@ -224,6 +228,10 @@ class DataExportTools {
224
228
  }
225
229
  async exportQueryToCSV(queryParams) {
226
230
  try {
231
+ const readPermission = this.security.validateQueryPermissions("SELECT");
232
+ if (!readPermission.valid) {
233
+ return { status: "error", error: readPermission.error };
234
+ }
227
235
  const { query, params = [], include_headers = true, } = queryParams;
228
236
  const queryValidation = this.security.validateQuery(query, this.security.hasExecutePermission());
229
237
  if (!queryValidation.valid) {
@@ -35,7 +35,7 @@ export declare class QueryTools {
35
35
  /**
36
36
  * Execute write operations (INSERT, UPDATE) with validation.
37
37
  * DELETE requires the separate delete permission and is validated in the security layer.
38
- * Note: DDL operations are blocked by the security layer for safety
38
+ * DDL and information queries must use their dedicated tools.
39
39
  */
40
40
  executeWriteQuery(queryParams: {
41
41
  query: string;
@@ -27,10 +27,10 @@ class QueryTools {
27
27
  error: `Query validation failed: ${queryValidationResult.errors?.join(', ') || 'Invalid query parameters'}`,
28
28
  };
29
29
  }
30
- // Check if user has execute permission to bypass dangerous keyword checks
30
+ // Execute permission allows advanced SELECT features, not dangerous operations.
31
31
  const hasExecutePermission = this.security.hasExecutePermission();
32
32
  // Validate query using security layer
33
- // If user has execute permission, allow advanced SQL features
33
+ // Mandatory safety checks apply regardless of execute permission.
34
34
  const securityQueryValidation = this.security.validateQuery(query, hasExecutePermission);
35
35
  if (!securityQueryValidation.valid) {
36
36
  return {
@@ -120,7 +120,7 @@ class QueryTools {
120
120
  /**
121
121
  * Execute write operations (INSERT, UPDATE) with validation.
122
122
  * DELETE requires the separate delete permission and is validated in the security layer.
123
- * Note: DDL operations are blocked by the security layer for safety
123
+ * DDL and information queries must use their dedicated tools.
124
124
  */
125
125
  async executeWriteQuery(queryParams) {
126
126
  try {
@@ -134,7 +134,7 @@ class QueryTools {
134
134
  };
135
135
  }
136
136
  // Validate query using security layer
137
- // Pass true for bypassDangerousCheck since this is executeWriteQuery (requires 'execute' permission)
137
+ // Execute permission does not bypass mandatory safety restrictions.
138
138
  const securityQueryValidation = this.security.validateQuery(query, true);
139
139
  if (!securityQueryValidation.valid) {
140
140
  return {
@@ -142,11 +142,10 @@ class QueryTools {
142
142
  error: `Query validation failed: ${securityQueryValidation.error}`,
143
143
  };
144
144
  }
145
- // Ensure it's not a SELECT query (use runSelectQuery for that)
146
- if (securityQueryValidation.queryType === "SELECT") {
145
+ if (!["INSERT", "UPDATE", "DELETE"].includes(securityQueryValidation.queryType || "")) {
147
146
  return {
148
147
  status: "error",
149
- error: "SELECT queries should use run_select_query method instead of execute_write_query.",
148
+ error: "Only INSERT, UPDATE, and DELETE are allowed with execute_write_query. Use run_select_query for SELECT and execute_ddl for schema changes.",
150
149
  };
151
150
  }
152
151
  // Validate parameters
@@ -116,7 +116,7 @@ class TransactionTools {
116
116
  };
117
117
  }
118
118
  // SECURITY VALIDATION: Check if user has execute permission
119
- const hasExecutePermission = this.security.isToolEnabled("executeWriteQuery");
119
+ const hasExecutePermission = this.security.hasExecutePermission();
120
120
  // SECURITY VALIDATION: Validate the query before execution
121
121
  const queryValidation = this.security.validateQuery(params.query, hasExecutePermission);
122
122
  if (!queryValidation.valid) {
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.43.2",
4
+ "version": "1.43.5",
5
5
  "tools": [
6
6
  {
7
7
  "name": "list_databases",
@@ -1383,7 +1383,7 @@
1383
1383
  },
1384
1384
  {
1385
1385
  "name": "cursor_execute_request",
1386
- "description": "Cursor compatibility bridge for clients that can call MCP tools but cannot send arguments. Reads .cursor/mysql-mcp-request.json (or MYSQL_MCP_CURSOR_REQUEST_FILE) and dispatches to the requested MySQL MCP tool. The request file supports {\"tool\":\"execute_ddl\",\"arguments\":{\"query\":\"DROP TABLE IF EXISTS t;\"}} or direct SQL with {\"query\":\"...\",\"mode\":\"auto\"}.",
1386
+ "description": "Cursor compatibility bridge for clients that can call MCP tools but cannot send arguments. Requires utility permission and an enabled destination tool. Reads .cursor/mysql-mcp-request.json (or MYSQL_MCP_CURSOR_REQUEST_FILE) and dispatches to the requested MySQL MCP tool. The request file supports {\"tool\":\"execute_ddl\",\"arguments\":{\"query\":\"DROP TABLE IF EXISTS t;\"}} or direct SQL with {\"query\":\"...\",\"mode\":\"auto\"}.",
1387
1387
  "input_schema": {
1388
1388
  "type": "object",
1389
1389
  "properties": {}
@@ -1517,7 +1517,7 @@
1517
1517
  },
1518
1518
  {
1519
1519
  "name": "execute_in_transaction",
1520
- "description": "Executes a SQL query within an existing transaction context. The query becomes part of the transaction and will be committed or rolled back with it. Use after begin_transaction.",
1520
+ "description": "Executes a SQL query within an existing transaction context. Requires transaction plus the SQL operation permission: read for SELECT, create or execute for INSERT, update or execute for UPDATE, delete for DELETE. DDL requires an enabled execute_ddl tool and may implicitly commit. EXPLAIN ANALYZE requires the permission of the statement it executes. Use after begin_transaction.",
1521
1521
  "input_schema": {
1522
1522
  "type": "object",
1523
1523
  "properties": {
@@ -1726,7 +1726,7 @@
1726
1726
  },
1727
1727
  {
1728
1728
  "name": "export_table_to_csv",
1729
- "description": "📄 Exports table data to CSV format with filtering, pagination, and sorting. For sensitive data, use safe_export_table instead which includes automatic data masking.",
1729
+ "description": "📄 Exports table data to CSV format with filtering, pagination, and sorting. Requires both utility and read permissions.",
1730
1730
  "input_schema": {
1731
1731
  "type": "object",
1732
1732
  "properties": {
@@ -1811,7 +1811,7 @@
1811
1811
  },
1812
1812
  {
1813
1813
  "name": "export_query_to_csv",
1814
- "description": "📄 Executes a SELECT query and exports results to CSV format. Supports complex queries with JOINs and aggregations. For sensitive data, consider using safe_export_table or adding manual data masking.",
1814
+ "description": "📄 Executes a SELECT query and exports results to CSV format. Requires both utility and read permissions. Supports complex queries with JOINs and aggregations.",
1815
1815
  "input_schema": {
1816
1816
  "type": "object",
1817
1817
  "properties": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@berthojoris/mcp-mysql-server",
3
- "version": "1.43.2",
3
+ "version": "1.43.5",
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",