@berthojoris/mcp-mysql-server 1.43.5 → 1.45.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/DOCUMENTATIONS.md +674 -508
  3. package/README.md +468 -376
  4. package/bin/mcp-mysql.js +214 -168
  5. package/dist/cache/queryCache.js +1 -1
  6. package/dist/config/config.js +2 -1
  7. package/dist/config/featureConfig.d.ts +5 -0
  8. package/dist/config/featureConfig.js +11 -13
  9. package/dist/config/runtimeConfig.d.ts +50 -0
  10. package/dist/config/runtimeConfig.js +173 -0
  11. package/dist/db/connection.d.ts +40 -1
  12. package/dist/db/connection.js +188 -22
  13. package/dist/mcp-server.js +248 -375
  14. package/dist/security/grantInspector.d.ts +5 -0
  15. package/dist/security/grantInspector.js +32 -0
  16. package/dist/security/securityLayer.d.ts +21 -2
  17. package/dist/security/securityLayer.js +151 -21
  18. package/dist/server/auditLogger.d.ts +24 -0
  19. package/dist/server/auditLogger.js +60 -0
  20. package/dist/server/auth.d.ts +56 -0
  21. package/dist/server/auth.js +274 -0
  22. package/dist/server/httpServer.d.ts +22 -0
  23. package/dist/server/httpServer.js +320 -0
  24. package/dist/server/rateLimiter.d.ts +15 -0
  25. package/dist/server/rateLimiter.js +41 -0
  26. package/dist/server/requestContext.d.ts +12 -0
  27. package/dist/server/requestContext.js +9 -0
  28. package/dist/tools/toolAnnotations.d.ts +4 -0
  29. package/dist/tools/toolAnnotations.js +73 -0
  30. package/dist/tools/toolArgumentValidation.js +22 -22
  31. package/dist/tools/toolRegistry.d.ts +1 -1
  32. package/dist/tools/toolRegistry.js +7 -1
  33. package/manifest.json +1 -1
  34. package/package.json +86 -78
  35. package/dist/auth/authService.d.ts +0 -29
  36. package/dist/auth/authService.js +0 -114
  37. package/dist/tools/backupRestoreTools.d.ts +0 -18
  38. package/dist/tools/backupRestoreTools.js +0 -70
  39. package/dist/tools/documentationGeneratorTools.d.ts +0 -145
  40. package/dist/tools/documentationGeneratorTools.js +0 -820
  41. package/dist/tools/forecastingTools.d.ts +0 -36
  42. package/dist/tools/forecastingTools.js +0 -256
  43. package/dist/tools/functionTools.d.ts +0 -87
  44. package/dist/tools/functionTools.js +0 -358
  45. package/dist/tools/indexRecommendationTools.d.ts +0 -50
  46. package/dist/tools/indexRecommendationTools.js +0 -451
  47. package/dist/tools/intelligentQueryTools.d.ts +0 -94
  48. package/dist/tools/intelligentQueryTools.js +0 -713
  49. package/dist/tools/performanceTools.d.ts +0 -76
  50. package/dist/tools/performanceTools.js +0 -505
  51. package/dist/tools/processTools.d.ts +0 -61
  52. package/dist/tools/processTools.js +0 -181
  53. package/dist/tools/queryVisualizationTools.d.ts +0 -22
  54. package/dist/tools/queryVisualizationTools.js +0 -155
  55. package/dist/tools/schemaDesignTools.d.ts +0 -67
  56. package/dist/tools/schemaDesignTools.js +0 -359
  57. package/dist/tools/schemaPatternTools.d.ts +0 -19
  58. package/dist/tools/schemaPatternTools.js +0 -253
  59. package/dist/tools/schemaVersioningTools.d.ts +0 -138
  60. package/dist/tools/schemaVersioningTools.js +0 -1008
  61. package/dist/tools/securityAuditTools.d.ts +0 -39
  62. package/dist/tools/securityAuditTools.js +0 -319
  63. package/dist/tools/smartDiscoveryTools.d.ts +0 -163
  64. package/dist/tools/smartDiscoveryTools.js +0 -750
  65. package/dist/tools/testDataTools.d.ts +0 -26
  66. package/dist/tools/testDataTools.js +0 -325
package/DOCUMENTATIONS.md CHANGED
@@ -1,508 +1,674 @@
1
- # MySQL MCP Server - Documentation
2
-
3
- **Last Updated:** 2026-10-12 21:16:54
4
- **Version:** 1.43.5
5
- **Total Tools:** 88
6
-
7
- Comprehensive documentation for the MySQL MCP Server. For quick start, see [README.md](README.md).
8
-
9
- ---
10
-
11
- ## Table of Contents
12
-
13
- 1. [Configuration](#configuration)
14
- 2. [Tools Overview](#tools-overview)
15
- 3. [Permission System](#permission-system)
16
- 4. [Tool Categories](#tool-categories)
17
- 5. [Core Operations](#core-operations)
18
- 6. [Advanced Features](#advanced-features)
19
- 7. [Security Features](#security-features)
20
-
21
- ---
22
-
23
- ## Configuration
24
-
25
- ### Dual-Layer Access Control
26
-
27
- Configure MySQL MCP with two access-control layers:
28
-
29
- ```json
30
- {
31
- "mcpServers": {
32
- "mysql": {
33
- "command": "npx",
34
- "type": "stdio",
35
- "args": [
36
- "-y",
37
- "@berthojoris/mcp-mysql-server",
38
- "mysql://user:password@localhost:3306/database",
39
- "list,read,utility",
40
- "database_discovery,custom_queries,analysis"
41
- ]
42
- }
43
- }
44
- }
45
- ```
46
-
47
- **Layer 1 (Permissions)**: Broad operation control
48
- **Layer 2 (Categories)**: Fine-grained tool filtering
49
-
50
- > **Credentials with special characters**: if the username or password in the connection string contains URL-reserved characters (`@`, `:`, `/`, `?`, `#`, `%`, `&`, etc.), URL-encode them — e.g. the password `p@ss:w0rd` becomes `p%40ss%3Aw0rd`, giving `mysql://user:p%40ss%3Aw0rd@host:3306/db`. The server passes both the username and password through `decodeURIComponent()` before connecting, including when only one of the two is set.
51
-
52
- ### Environment Variables
53
-
54
- ```json
55
- {
56
- "env": {
57
- "DB_HOST": "localhost",
58
- "DB_PORT": "3306",
59
- "DB_USER": "root",
60
- "DB_PASSWORD": "your_password",
61
- "DB_NAME": "your_database",
62
- "MCP_PERMISSIONS": "list,read,utility",
63
- "MCP_CATEGORIES": "database_discovery,custom_queries,analysis"
64
- }
65
- }
66
- ```
67
-
68
- ---
69
-
70
- ### Cursor Compatibility Bridge
71
-
72
- Some Cursor MCP wrappers can call a tool by name but cannot pass `arguments`. For that flow, write a request file at `.cursor/mysql-mcp-request.json` and call the no-argument `cursor_execute_request` tool.
73
-
74
- Execute any existing MCP tool:
75
-
76
- ```json
77
- {
78
- "tool": "execute_ddl",
79
- "arguments": {
80
- "query": "DROP TABLE IF EXISTS spark_processes;"
81
- }
82
- }
83
- ```
84
-
85
- Or execute SQL directly with automatic routing:
86
-
87
- ```json
88
- {
89
- "query": "DROP TABLE IF EXISTS spark_processes;",
90
- "mode": "auto"
91
- }
92
- ```
93
-
94
- Supported `mode` values are `auto`, `select`, `write`, and `ddl`. Set `MYSQL_MCP_CURSOR_REQUEST_FILE` to override the request file path.
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
-
98
- ---
99
-
100
- ### AI Agent Tool Discovery
101
-
102
- Use `list_all_tools` first when connecting from Codex, Claude Code CLI, Cursor, Droid CLI, or other MCP agents. It returns the live runtime catalog from the server, enabled/disabled status for each tool, the active permission/category profile, and recommended workflows for common agent tasks.
103
-
104
- For CSV exports, use `export_table_to_csv` for table-based exports and `export_query_to_csv` for SELECT query exports.
105
-
106
- ---
107
-
108
- ## Permission System
109
-
110
- ### Available Permissions
111
-
112
- | Permission | Operations | Example Tools |
113
- |------------|------------|---------------|
114
- | `list` | List/discover objects | `list_databases`, `list_tables` |
115
- | `read` | Read data | `read_records`, `run_select_query` |
116
- | `create` | Insert records and seed data | `create_record`, `bulk_insert`, `execute_seed_plan` |
117
- | `update` | Update records | `update_record`, `bulk_update` |
118
- | `delete` | Delete records | `delete_record`, `bulk_delete`, DELETE via `execute_write_query` (requires both `execute` and `delete`) |
119
- | `execute` | Custom SQL (INSERT/UPDATE; not DELETE without `delete`) | `execute_write_query` |
120
- | `ddl` | Schema changes | `create_table`, `alter_table` |
121
- | `utility` | Utility operations | `test_connection`, `analyze_table` |
122
- | `transaction` | Transaction management | `begin_transaction`, `commit_transaction` |
123
- | `procedure` | Stored procedures | `create_stored_procedure`, `execute_stored_procedure` |
124
-
125
- ### Filtering Logic
126
-
127
- ```
128
- Tool enabled = (Has Permission) AND (Has Category OR No categories specified)
129
- ```
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
-
141
- ---
142
-
143
- ## Tool Categories
144
-
145
- ### 1. Database Discovery (4 tools)
146
- - `list_databases` - List all databases
147
- - `list_tables` - List tables in database
148
- - `read_table_schema` - Get table structure
149
- - `get_all_tables_relationships` - Get all FK relationships
150
-
151
- ### 2. Analysis (7 tools)
152
- - `get_database_summary` - Database overview with statistics
153
- - `get_schema_erd` - Generate Mermaid.js ER diagram
154
- - `get_schema_rag_context` - Compact schema for LLM context, with optional comments and keyword filtering
155
- - `get_column_statistics` - Column data profiling
156
- - `find_tables_by_keyword` - Ranked schema keyword search across table names, column names, and comments
157
- - `search_schema` - Unified discovery for “where is X?” questions using schema metadata and optional sample-data search
158
- - `search_data_across_tables` - Guarded read-only keyword search across text-like data columns
159
-
160
- ### 3. Data Operations (7 tools)
161
- - `create_record` - Insert single record
162
- - `read_records` - Query with filtering/pagination
163
- - `update_record` - Update records
164
- - `delete_record` - Delete records
165
- - `bulk_insert` - Batch insert (performance)
166
- - `bulk_update` - Batch update (performance)
167
- - `bulk_delete` - Batch delete (performance)
168
-
169
- ### 4. Seed Operations (6 tools)
170
- - `plan_seed_data` - Build FK-aware relational seed plans
171
- - `generate_seed_preview` - Preview deterministic dummy rows without writing
172
- - `execute_seed_plan` - Execute confirmed seed plans with transaction and rollback safety
173
- - `validate_seed_integrity` - Validate row counts, FK orphans, required columns, and unique collisions
174
- - `infer_seed_rules` - Infer advanced generators from schema, samples, unique indexes, and domain presets
175
- - `seed_from_template` - Create reusable plan-first seed workflows for ecommerce, POS, and CRM domains
176
-
177
- ### 5. Query Management (2 tools)
178
- - `run_select_query` - Execute SELECT queries
179
- - `execute_write_query` - Execute INSERT/UPDATE (DELETE requires the `delete` permission)
180
-
181
- ### 6. Schema Management (4 tools)
182
- - `create_table` - Create new tables
183
- - `alter_table` - Modify table structure
184
- - `drop_table` - Delete tables
185
- - `execute_ddl` - Execute raw DDL
186
-
187
- ### 7. Data Export (2 tools)
188
- - `export_table_to_csv` - Export table data to CSV
189
- - `export_query_to_csv` - Export SELECT query results to CSV
190
-
191
- ### 8. Index Management (11 tools)
192
- - `list_indexes` - List table indexes
193
- - `get_index_info` - Get index details
194
- - `create_index` - Create indexes
195
- - `drop_index` - Drop indexes
196
- - `analyze_index` - Analyze and update index statistics
197
- - `create_fulltext_index` - Create FULLTEXT indexes for text search
198
- - `fulltext_search` - Perform full-text search with MATCH AGAINST
199
- - `get_fulltext_info` - Get FULLTEXT index information
200
- - `drop_fulltext_index` - Drop FULLTEXT indexes
201
- - `get_fulltext_stats` - Get FULLTEXT index statistics
202
- - `optimize_fulltext` - Optimize FULLTEXT indexes
203
-
204
- ### 9. Constraint Management (7 tools)
205
- - `list_foreign_keys` - List foreign keys
206
- - `list_constraints` - List all constraints
207
- - `add_foreign_key` - Add foreign key
208
- - `drop_foreign_key` - Remove foreign key
209
- - `add_unique_constraint` - Add unique constraint
210
- - `drop_constraint` - Remove constraint
211
- - `add_check_constraint` - Add check constraint
212
-
213
- ### 10. Stored Procedures (6 tools)
214
- - `list_stored_procedures` - List procedures
215
- - `get_stored_procedure_info` - Get procedure details
216
- - `execute_stored_procedure` - Execute procedures
217
- - `create_stored_procedure` - Create procedures
218
- - `drop_stored_procedure` - Remove procedures
219
- - `show_create_procedure` - Show CREATE statement
220
-
221
- ### 11. Views Management (6 tools)
222
- - `list_views` - List views
223
- - `get_view_info` - Get view details
224
- - `create_view` - Create views
225
- - `alter_view` - Modify views
226
- - `drop_view` - Remove views
227
- - `show_create_view` - Show CREATE statement
228
-
229
- ### 12. Triggers Management (5 tools)
230
- - `list_triggers` - List triggers
231
- - `get_trigger_info` - Get trigger details
232
- - `create_trigger` - Create triggers
233
- - `drop_trigger` - Remove triggers
234
- - `show_create_trigger` - Show CREATE statement
235
-
236
- ### 13. Table Maintenance (8 tools)
237
- - `analyze_table` - Update statistics
238
- - `optimize_table` - Reclaim space
239
- - `check_table` - Check for errors
240
- - `repair_table` - Repair corrupted tables
241
- - `truncate_table` - Remove all rows
242
- - `get_table_status` - Get table statistics
243
- - `flush_table` - Close/reopen table
244
- - `get_table_size` - Get size information
245
-
246
- ### 14. Transaction Management (5 tools)
247
- - `begin_transaction` - Start transaction
248
- - `commit_transaction` - Commit transaction
249
- - `rollback_transaction` - Rollback transaction
250
- - `get_transaction_status` - Check transaction state
251
- - `execute_in_transaction` - Execute within transaction
252
-
253
- ### 15. Query Optimization (3 tools)
254
- - `analyze_query` - Analyze query performance
255
- - `get_optimization_hints` - Get optimizer hints
256
- - `repair_query` - Repair broken SQL queries
257
-
258
- ### 16. Utilities (5 tools)
259
- - `test_connection` - Test connectivity
260
- - `describe_connection` - Connection info
261
- - `read_changelog` - Read changelog
262
- - `cursor_execute_request` - Execute a file-backed request for clients that cannot send MCP arguments
263
- - `list_all_tools` - Runtime tool catalog with agent guidance
264
-
265
- ---
266
-
267
- ## Core Operations
268
-
269
- ### Database Discovery
270
-
271
- Start with these tools to explore any database:
272
-
273
- ```javascript
274
- // List all databases
275
- await mcp.call("list_databases", {});
276
-
277
- // List tables in current database
278
- await mcp.call("list_tables", {});
279
-
280
- // Get comprehensive overview
281
- await mcp.call("get_database_summary", {
282
- max_tables: 50,
283
- include_relationships: true
284
- });
285
-
286
- // Visualize relationships
287
- await mcp.call("get_schema_erd", {});
288
- ```
289
-
290
- ### Schema & Data Discovery
291
-
292
- Use these tools when users ask natural-language questions like “which table stores survey data?” or “where is customer feedback saved?”:
293
-
294
- ```javascript
295
- // Fast metadata search across table names, column names, and comments
296
- await mcp.call("find_tables_by_keyword", {
297
- keyword: "survey",
298
- search_in: "all",
299
- limit: 20
300
- });
301
-
302
- // Unified discovery with optional guarded sample-data scan
303
- await mcp.call("search_schema", {
304
- query: "survey",
305
- modes: ["table_names", "column_names", "comments", "sample_data"],
306
- max_results: 20
307
- });
308
-
309
- // Direct bounded data scan when the keyword may only exist in row values
310
- await mcp.call("search_data_across_tables", {
311
- keyword: "survey",
312
- max_tables: 20,
313
- limit_per_table: 3
314
- });
315
- ```
316
-
317
- `find_tables_by_keyword` requires `list`; `search_data_across_tables` requires `read`; `search_schema` uses `list` and requires `read` only when `sample_data` mode is enabled.
318
-
319
- ### Data Operations
320
-
321
- Basic CRUD operations:
322
-
323
- ```javascript
324
- // Create record
325
- await mcp.call("create_record", {
326
- table_name: "users",
327
- data: { name: "John", email: "john@example.com" }
328
- });
329
-
330
- // Read with filtering
331
- await mcp.call("read_records", {
332
- table_name: "users",
333
- filters: [{ field: "status", operator: "eq", value: "active" }],
334
- pagination: { page: 1, limit: 10 }
335
- });
336
-
337
- // Update records
338
- await mcp.call("update_record", {
339
- table_name: "users",
340
- data: { status: "inactive" },
341
- conditions: [{ field: "last_login", operator: "lt", value: "2024-01-01" }]
342
- });
343
-
344
- // Delete records
345
- await mcp.call("delete_record", {
346
- table_name: "users",
347
- conditions: [{ field: "status", operator: "eq", value: "deleted" }]
348
- });
349
- ```
350
-
351
- ### Performance Operations
352
-
353
- ```javascript
354
- // Analyze slow query
355
- await mcp.call("analyze_query", {
356
- query: "SELECT * FROM users WHERE email LIKE '%@gmail.com'"
357
- });
358
-
359
- // Get optimization hints
360
- await mcp.call("get_optimization_hints", {
361
- goal: "SPEED"
362
- });
363
- ```
364
-
365
- ---
366
-
367
- ## Advanced Features
368
-
369
- ### Analysis
370
-
371
- The server includes analysis tools for database insights:
372
-
373
- - **Database Summary**: Provides readable overviews with statistics
374
- - **ER Diagram Generation**: Automatic Mermaid.js diagrams
375
- - **RAG Context**: Compact schema for LLM prompts, with optional `TABLE_COMMENT` / `COLUMN_COMMENT` inclusion and keyword filtering
376
- - **Column Profiling**: Data quality and distribution analysis
377
- - **Schema Keyword Discovery**: Ranked search for concepts across table names, column names, and metadata comments
378
- - **Unified Search**: One entry point for schema and bounded sample-data discovery
379
- - **Guarded Data Search**: Read-only LIKE scans across text-like columns with strict table/result limits
380
-
381
- ### Bulk Operations
382
-
383
- For high-performance operations with large datasets:
384
-
385
- - **Bulk Insert**: Handle thousands of records efficiently
386
- - **Bulk Update**: Update multiple records with different conditions
387
- - **Bulk Delete**: Delete multiple record sets in batches
388
-
389
- ### Relational Data Seeder
390
-
391
- For dummy data on related tables, use the seed workflow:
392
-
393
- ```javascript
394
- const plan = await mcp.call("plan_seed_data", {
395
- target_tables: ["orders"],
396
- rows_per_table: 20,
397
- include_dependencies: true,
398
- include_children: true,
399
- random_seed: 42
400
- });
401
-
402
- await mcp.call("generate_seed_preview", {
403
- plan_id: plan.plan_id,
404
- max_preview_rows_per_table: 3
405
- });
406
-
407
- await mcp.call("execute_seed_plan", {
408
- plan_id: plan.plan_id,
409
- dry_run: false,
410
- confirm_token: plan.confirm_token
411
- });
412
-
413
- await mcp.call("validate_seed_integrity", {
414
- plan_id: plan.plan_id
415
- });
416
- ```
417
-
418
- `execute_seed_plan` defaults to dry-run, requires confirmation for writes, blocks production-like database names unless explicitly allowed, and uses transaction rollback on errors.
419
-
420
- Composite FK/PK support resolves multi-column parent tuples together, so relations such as `(tenant_id, region_id)` or `(tenant_id, region_id, order_id)` are not mixed across different parent rows.
421
-
422
- Advanced rule inference and templates:
423
-
424
- ```javascript
425
- await mcp.call("infer_seed_rules", {
426
- tables: ["orders", "order_items"],
427
- domain: "ecommerce",
428
- sample_size: 25
429
- });
430
-
431
- await mcp.call("seed_from_template", {
432
- template: "ecommerce",
433
- scale: "small",
434
- random_seed: 42
435
- });
436
- ```
437
-
438
- `seed_from_template` is plan-first and does not write data directly. Review its plan/preview, then execute with `execute_seed_plan`.
439
-
440
- ### Transaction Management
441
-
442
- Full ACID transaction support:
443
-
444
- ```javascript
445
- await mcp.call("begin_transaction", {});
446
- await mcp.call("create_record", { table_name: "orders", data: {...} });
447
- await mcp.call("update_record", { table_name: "inventory", data: {...} });
448
- await mcp.call("commit_transaction", {});
449
- ```
450
-
451
- ---
452
-
453
- ## Security Features
454
-
455
- ### Permission-Based Access Control
456
-
457
- - **Layer 1**: Broad permission categories (list, read, create, etc.)
458
- - **Layer 2**: Fine-grained tool category filtering
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).
466
-
467
- ### Data Protection
468
-
469
- - **PII Masking**: Automatic sensitive data redaction in exports
470
- - **Query Validation**: Input validation and SQL injection prevention
471
-
472
- ### Connection Security
473
-
474
- - **Environment Variables**: Secure credential management
475
- - **Connection Testing**: Validation before operations
476
- - **Error Handling**: Comprehensive error reporting
477
-
478
- ---
479
-
480
- ---
481
-
482
- ## Troubleshooting
483
-
484
- ### Common Issues
485
-
486
- 1. **Permission Denied**: Check both permission layers in error messages
487
- 2. **Connection Failed**: Verify database credentials and network
488
- 3. **Query Errors**: Use `repair_query` for diagnosis
489
- 4. **Performance Issues**: Use `analyze_query` and optimization hints
490
-
491
- ### MCP error `-32000: Connection closed` (local server)
492
-
493
- If your client reports `MCP error -32000: Connection closed`, the server process is usually crashing on startup.
494
-
495
- If you see `ReferenceError: exports is not defined in ES module scope` in the server stderr logs, update to **v1.33.2+** (fixes an ESM/CJS mismatch that caused the MCP process to exit immediately).
496
-
497
- ### Error Messages
498
-
499
- The system provides detailed error messages indicating:
500
-
501
- - Which permission layer blocked access
502
- - Required permissions vs current permissions
503
- - Specific category requirements
504
- - SQL syntax and logic errors
505
-
506
- ---
507
-
508
- *For detailed examples and advanced usage patterns, see the project README.md.*
1
+ # MySQL MCP Server - Documentation
2
+
3
+ **Last Updated:** 2026-10-26 15:57:37
4
+ **Version:** 1.45.2
5
+ **Total Tools:** 88
6
+
7
+ Comprehensive documentation for the MySQL MCP Server. For quick start, see [README.md](README.md).
8
+
9
+ ---
10
+
11
+ ## Table of Contents
12
+
13
+ 1. [Configuration](#configuration)
14
+ 2. [Remote Access: Streamable HTTP Transport](#remote-access-streamable-http-transport-v1450-2026-10-26-144606)
15
+ 3. [Permission System](#permission-system)
16
+ 4. [Tool Categories](#tool-categories)
17
+ 5. [Core Operations](#core-operations)
18
+ 6. [Advanced Features](#advanced-features)
19
+ 7. [Security Features](#security-features)
20
+ 8. [Troubleshooting](#troubleshooting)
21
+
22
+ ---
23
+
24
+ ## Configuration
25
+
26
+ ### Dual-Layer Access Control
27
+
28
+ Configure MySQL MCP with two access-control layers:
29
+
30
+ ```json
31
+ {
32
+ "mcpServers": {
33
+ "mysql": {
34
+ "command": "npx",
35
+ "type": "stdio",
36
+ "args": [
37
+ "-y",
38
+ "@berthojoris/mcp-mysql-server",
39
+ "mysql://user:password@localhost:3306/database",
40
+ "list,read,utility",
41
+ "database_discovery,custom_queries,analysis"
42
+ ]
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ **Layer 1 (Permissions)**: Broad operation control
49
+ **Layer 2 (Categories)**: Fine-grained tool filtering
50
+
51
+ > **Credentials with special characters**: if the username or password in the connection string contains URL-reserved characters (`@`, `:`, `/`, `?`, `#`, `%`, `&`, etc.), URL-encode them — e.g. the password `p@ss:w0rd` becomes `p%40ss%3Aw0rd`, giving `mysql://user:p%40ss%3Aw0rd@host:3306/db`. The server passes both the username and password through `decodeURIComponent()` before connecting, including when only one of the two is set.
52
+
53
+ ### Environment Variables
54
+
55
+ ```json
56
+ {
57
+ "env": {
58
+ "DB_HOST": "localhost",
59
+ "DB_PORT": "3306",
60
+ "DB_USER": "root",
61
+ "DB_PASSWORD": "your_password",
62
+ "DB_NAME": "your_database",
63
+ "MCP_PERMISSIONS": "list,read,utility",
64
+ "MCP_CATEGORIES": "database_discovery,custom_queries,analysis"
65
+ }
66
+ }
67
+ ```
68
+
69
+ ### Defaults (v1.44.0, 2026-10-26 13:35:39)
70
+
71
+ - **Permissions**: when neither permissions nor categories are given, the server starts **read-only** with `list,read,utility`. Earlier versions enabled every tool. To enable everything, pass the full list: `list,read,create,update,delete,execute,ddl,utility,transaction,procedure`.
72
+ - **Database**: when the connection string has no database and `DB_NAME` is unset, no database is selected and database-scoped tools return "No database specified". Earlier versions fell back to the `mysql` system schema.
73
+ - **Query cache**: disabled by default. Set `CACHE_ENABLED=true` to opt in (`CACHE_TTL_MS`, default `60000`; `CACHE_MAX_SIZE`, default `100`; `CACHE_MAX_MEMORY_MB`, default `50`). When enabled, any statement that can change data (outside or inside a transaction) and every transaction commit clears the whole cache. Writes made by other clients are not detected, so cached results can lag by up to the TTL.
74
+
75
+ ---
76
+
77
+ ### Remote Access: Streamable HTTP Transport (v1.45.0, 2026-10-26 14:46:06)
78
+
79
+ The server uses **stdio by default**. A remote transport (MCP Streamable HTTP) for ChatGPT connectors / developer mode and other remote MCP clients is **opt-in**. Turn it on and off the same way as permissions, with a CLI argument or an environment variable. If you leave it unset, existing stdio setups keep working exactly as before.
80
+
81
+ | Setting | CLI flag | Values |
82
+ |---------|----------|--------|
83
+ | `MCP_TRANSPORT` | `--transport=stdio\|http` (or `--http`) | `stdio` (default) or `http` |
84
+ | `MCP_HTTP_HOST` | `--host=<addr>` | Bind address, default `127.0.0.1` |
85
+ | `MCP_HTTP_PORT` | `--port=<n>` | Default `3000` |
86
+
87
+ Flags can go anywhere on the command line. They are not mistaken for the positional permissions/categories arguments, and an unknown `--` option stops startup with an error. A CLI flag overrides the matching environment variable (including values from `.env`).
88
+
89
+ When the transport is `stdio`, every `MCP_HTTP_*` and `MCP_OAUTH_*` variable is ignored, so even an invalid value cannot affect a stdio setup. In HTTP mode, an invalid or unsafe value stops startup with a message that names the variable.
90
+
91
+ ```bash
92
+ # Enable HTTP via CLI
93
+ npx -y @berthojoris/mcp-mysql-server mysql://reader:pass@localhost:3306/app "list,read,utility" --transport=http --port=3000
94
+
95
+ # Enable HTTP via environment; unset MCP_TRANSPORT (or set it to "stdio") to disable
96
+ MCP_TRANSPORT=http MCP_HTTP_AUTH=token MCP_HTTP_AUTH_TOKENS=<64-hex-token> \
97
+ npx -y @berthojoris/mcp-mysql-server mysql://reader:pass@localhost:3306/app
98
+ ```
99
+
100
+ The MCP endpoint is `http://<host>:<port>/mcp` (set by `MCP_HTTP_PATH`). `GET /health` returns `{"status":"ok"}` and needs no authentication.
101
+
102
+ #### HTTP settings
103
+
104
+ | Variable | Default | Description |
105
+ |----------|---------|-------------|
106
+ | `MCP_HTTP_PATH` | `/mcp` | Endpoint path |
107
+ | `MCP_HTTP_PUBLIC_URL` | – | Public base URL as clients see it, e.g. `https://mcp.example.com`. Required for `oauth`. Its host is added to the allowed hosts |
108
+ | `MCP_HTTP_AUTH` | `none` | `none`, `token`, or `oauth` |
109
+ | `MCP_HTTP_AUTH_TOKENS` | – | For `token` mode: comma-separated bearer tokens, each at least 32 characters (`openssl rand -hex 32`) |
110
+ | `MCP_OAUTH_ISSUER` | – | For `oauth` mode: issuer of the external authorization server (Auth0, Keycloak, Okta, Entra ID, ...) |
111
+ | `MCP_OAUTH_AUDIENCE` | resource URL | Expected `aud` claim. Defaults to `MCP_HTTP_PUBLIC_URL` + `MCP_HTTP_PATH` |
112
+ | `MCP_OAUTH_JWKS_URI` | discovered | JWKS URL. When unset, it is discovered from the issuer's OpenID / OAuth metadata |
113
+ | `MCP_OAUTH_REQUIRED_SCOPES` | – | Comma-separated scopes that every token must carry |
114
+ | `MCP_HTTP_ALLOWED_HOSTS` | see description | Comma-separated `Host` header names (without port), for DNS-rebinding protection. Requests with any other `Host` get `403`. When unset and bound to a loopback address, `localhost`, `127.0.0.1`, and `[::1]` are allowed. When unset and bound to another address (e.g. `0.0.0.0`) with no `MCP_HTTP_PUBLIC_URL`, the check is off and a startup warning is logged |
115
+ | `MCP_HTTP_ALLOWED_ORIGINS` | see description | Comma-separated browser `Origin` values (e.g. `https://app.example.com`). A request with any other `Origin` gets `403`. When unset, loopback origins are allowed if the server is bound to loopback, and every `Origin` is rejected otherwise. Requests without `Origin` (server-to-server, such as ChatGPT's backend) are always allowed |
116
+ | `MCP_HTTP_TRUST_PROXY` | `false` | Use the first `X-Forwarded-For` address as the client IP for audit logs and rate limits. Enable only behind a trusted reverse proxy |
117
+ | `MCP_HTTP_ALLOW_UNAUTHENTICATED` | `false` | Allow `MCP_HTTP_AUTH=none` on a non-loopback bind address or with non-loopback allowed hosts. Not recommended |
118
+ | `MCP_HTTP_MAX_SESSIONS` | `100` | Maximum concurrent sessions. New sessions get `503` with `Retry-After: 60` once the limit is reached. `0` means no limit |
119
+ | `MCP_HTTP_SESSION_IDLE_TIMEOUT_MS` | `1800000` | Idle sessions are closed after this time, and their open transactions are rolled back. `0` disables expiry |
120
+ | `MCP_HTTP_MAX_BODY_BYTES` | `1048576` | Maximum request body size. Larger bodies get `413`. `0` means no limit |
121
+
122
+ `GET /health` skips the `Host` check, so load balancers can probe the server by IP.
123
+
124
+ The server does not terminate TLS. Put it behind a reverse proxy or tunnel that serves HTTPS (ChatGPT only connects to public HTTPS URLs), and set `MCP_HTTP_PUBLIC_URL` to that HTTPS address.
125
+
126
+ #### Authentication
127
+
128
+ - **`none`**: no authentication. The server only starts in this mode when it is bound to a loopback address and every allowed host is a loopback name. A tunnel that forwards a public hostname is then rejected by the `Host` check. `MCP_HTTP_ALLOW_UNAUTHENTICATED=true` overrides this rule.
129
+ - **`token`**: static bearer tokens (`Authorization: Bearer <token>`), compared in constant time. Use this for clients that can send a custom header, such as Claude Code, Cursor, or scripts. Each token gets a stable client id `token-<sha256 prefix>`, used in audit logs and rate limits.
130
+ - **`oauth`** (OAuth 2.1 resource server): the server validates JWT access tokens issued by an external authorization server. It does not issue tokens itself.
131
+ - Supported algorithms are RS256/384/512, PS256/384/512, ES256/384/512, and EdDSA. `none` and HMAC algorithms are rejected.
132
+ - The server checks the token's claims. `iss` must equal `MCP_OAUTH_ISSUER` (a trailing slash is ignored), and `aud` must contain the audience. `exp` is required, and `exp`/`nbf` allow 60 seconds of clock skew. Every scope in `MCP_OAUTH_REQUIRED_SCOPES` must appear in `scope` or `scp`; a missing scope returns `403` with `error="insufficient_scope"`.
133
+ - The client id used for sessions, audit logs, and rate limits is taken from `client_id`, then `azp`, then `sub`.
134
+ - Signing keys come from `MCP_OAUTH_JWKS_URI`, or else from `jwks_uri` in `<issuer>/.well-known/openid-configuration`, then from the RFC 8414 `oauth-authorization-server` document. Keys are cached for 10 minutes. A token with an unknown `kid` triggers a refetch, at most once every 30 seconds, so key rotation is picked up.
135
+ - In `oauth` mode only, the server publishes Protected Resource Metadata (RFC 9728) at `/.well-known/oauth-protected-resource` and `/.well-known/oauth-protected-resource<path>`. `401` responses carry `WWW-Authenticate: Bearer resource_metadata="..."` so clients can discover the authorization server.
136
+ - For ChatGPT, the authorization server must support the flow ChatGPT uses: authorization code + PKCE, typically with dynamic client registration.
137
+
138
+ ```bash
139
+ MCP_TRANSPORT=http
140
+ MCP_HTTP_HOST=127.0.0.1
141
+ MCP_HTTP_PUBLIC_URL=https://mcp.example.com
142
+ MCP_HTTP_AUTH=oauth
143
+ MCP_OAUTH_ISSUER=https://your-tenant.auth0.com/
144
+ MCP_OAUTH_REQUIRED_SCOPES=mysql:read
145
+ ```
146
+
147
+ #### Sessions
148
+
149
+ - Each client gets its own MCP session (`Mcp-Session-Id`), created by an `initialize` request. A session is bound to the identity that created it, and a request that presents another identity's session id is rejected with `403`. Other requests without a session id get `400`, and an unknown or expired session id gets `404`. `DELETE /mcp` ends a session.
150
+ - Transactions belong to the session that began them. Other sessions cannot see, use, commit, or roll them back; to them the transaction id does not exist. Transactions are rolled back when the session closes, expires, or the server shuts down (`SIGINT`/`SIGTERM`).
151
+ - A transaction id that is already in use is rejected instead of silently replacing the open transaction.
152
+ - Over stdio there is only one session, so behaviour does not change.
153
+
154
+ #### Protection settings (both transports)
155
+
156
+ These settings also apply to stdio, but there they default to **off**, so existing setups behave as before.
157
+
158
+ | Variable | stdio default | http default | Description |
159
+ |----------|---------------|--------------|-------------|
160
+ | `MCP_QUERY_TIMEOUT_MS` | `0` (off) | `30000` | Every SQL statement a tool runs is cancelled on the MySQL server with `KILL QUERY` once it runs longer than this. The tool returns `Query exceeded the <n> ms timeout and was cancelled`. If the statement is inside a transaction, that transaction is rolled back |
161
+ | `MCP_RATE_LIMIT_PER_MINUTE` | `0` (off) | `60` | Tool calls allowed per client in any 60-second window. The client is the auth identity, or the client IP when there is none (over stdio all calls share one bucket). Extra calls return a tool error with the retry delay |
162
+ | `MCP_MAX_RESULT_BYTES` | `0` (off) | `524288` | Maximum size of a tool result (its JSON text). Row arrays are cut to fit and wrapped as `{ rows, truncated, returned_rows, total_rows, message }`. Other oversized results return an error that asks for a narrower query |
163
+ | `MCP_AUDIT_LOG` | `off` | `stderr` | `off`, `stderr`, or a file path (relative paths resolve from the working directory; missing directories are created). See [Audit log](#audit-log) |
164
+ | `MCP_REQUIRE_READONLY_DB_USER` | `false` | `false` | When `true`, startup fails if the MySQL user holds any privilege beyond `SELECT`, `SHOW VIEW`, `SHOW DATABASES`, `PROCESS`, or `USAGE`. `WITH GRANT OPTION` and granted roles count as write privileges, because a role's privileges cannot be resolved |
165
+
166
+ In HTTP mode the server always runs `SHOW GRANTS` at startup and logs a warning if the MySQL user can write.
167
+
168
+ Query timeout details: the timed-out statement is cancelled through a separate short-lived connection that uses the same MySQL account (MySQL allows an account to kill its own threads). The pooled connection that ran the statement is then discarded rather than reused. With the timeout off, queries run on the pool exactly as before.
169
+
170
+ #### Audit log
171
+
172
+ Each line is a JSON object with a `time` and an `event`. Over `stderr`, lines are prefixed with `[audit] `. Nothing is ever written to stdout.
173
+
174
+ | Event | Fields |
175
+ |-------|--------|
176
+ | `tool_call` | `transport`, `session`, `client`, `ip`, `tool`, `args` (`names` of all arguments, plus `sql` truncated to 1000 characters when the call has a `query`/`sql` argument), `status` (`success`, `error`, `invalid`, `denied`, `rate_limited`), `durationMs`, `error` |
177
+ | `auth_failed` | `ip`, `reason` |
178
+ | `session_opened` | `session`, `client`, `ip` |
179
+ | `session_closed` | `session`, `client`, `reason` (`deleted by client`, `idle timeout`, `transport closed`, `server shutdown`) |
180
+
181
+ Argument values other than SQL text are not logged, because they can contain row data.
182
+
183
+ #### Recommended read-only database user
184
+
185
+ Permissions limit which tools are exposed. A read-only MySQL account limits what any SQL can do, even if a tool is misconfigured. For remote AI clients, connect with a dedicated account and keep the default `list,read,utility` permissions:
186
+
187
+ ```sql
188
+ CREATE USER 'mcp_reader'@'%' IDENTIFIED BY '<strong password>';
189
+ GRANT SELECT, SHOW VIEW ON app.* TO 'mcp_reader'@'%';
190
+ ```
191
+
192
+ #### Tool annotations
193
+
194
+ Every tool advertises MCP tool annotations: `title`, `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint: false`. They appear in `tools/list` and in the `list_all_tools` catalog. Clients use them to tell read-only tools apart from tools that write or destroy data. ChatGPT uses `readOnlyHint` to decide when to ask the user for confirmation. Annotations are only hints and do not replace permissions.
195
+
196
+ | Class | Hints | Tools |
197
+ |-------|-------|-------|
198
+ | Read-only | `readOnlyHint: true` | Discovery, analysis, `read_records`, `run_select_query`, exports, `show_*`/`list_*`/`get_*`, `check_table`, `fulltext_search`, seed planning/preview tools |
199
+ | Write | `readOnlyHint: false`, `destructiveHint: false` | `create_record`, `bulk_insert`, `execute_seed_plan`, `begin_transaction`, `rollback_transaction`, `create_table`/`create_index`/`create_trigger`/`create_stored_procedure`/`create_fulltext_index`, `add_*` constraints; idempotent maintenance: `analyze_table`, `analyze_index`, `optimize_table`, `flush_table`, `optimize_fulltext` |
200
+ | Destructive | `destructiveHint: true` | `update_record`, `delete_record`, `bulk_update`, `bulk_delete`, `execute_write_query`, `execute_ddl`, `execute_in_transaction`, `commit_transaction`, `execute_stored_procedure`, `cursor_execute_request`, `alter_*`, `drop_*`, `create_view` (can replace a view), `repair_table`, `truncate_table` |
201
+
202
+ The full mapping is in `src/tools/toolAnnotations.ts`.
203
+
204
+ ---
205
+
206
+ ### Cursor Compatibility Bridge
207
+
208
+ Some Cursor MCP wrappers can call a tool by name but cannot pass `arguments`. For that flow, write a request file at `.cursor/mysql-mcp-request.json` and call the no-argument `cursor_execute_request` tool.
209
+
210
+ Execute any existing MCP tool:
211
+
212
+ ```json
213
+ {
214
+ "tool": "execute_ddl",
215
+ "arguments": {
216
+ "query": "DROP TABLE IF EXISTS spark_processes;"
217
+ }
218
+ }
219
+ ```
220
+
221
+ Or execute SQL directly with automatic routing:
222
+
223
+ ```json
224
+ {
225
+ "query": "DROP TABLE IF EXISTS spark_processes;",
226
+ "mode": "auto"
227
+ }
228
+ ```
229
+
230
+ Supported `mode` values are `auto`, `select`, `write`, and `ddl`. Set `MYSQL_MCP_CURSOR_REQUEST_FILE` (or its alias `MCP_MYSQL_REQUEST_FILE`) to override the request file path; relative paths resolve from the working directory.
231
+
232
+ 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.
233
+
234
+ ---
235
+
236
+ ### AI Agent Tool Discovery
237
+
238
+ Use `list_all_tools` first when connecting from Codex, Claude Code CLI, Cursor, Droid CLI, or other MCP agents. It returns the live runtime catalog from the server, enabled/disabled status for each tool, the active permission/category profile, and recommended workflows for common agent tasks.
239
+
240
+ For CSV exports, use `export_table_to_csv` for table-based exports and `export_query_to_csv` for SELECT query exports.
241
+
242
+ ---
243
+
244
+ ## Permission System
245
+
246
+ ### Available Permissions
247
+
248
+ | Permission | Operations | Example Tools |
249
+ |------------|------------|---------------|
250
+ | `list` | List/discover objects | `list_databases`, `list_tables` |
251
+ | `read` | Read data | `read_records`, `run_select_query` |
252
+ | `create` | Insert records and seed data | `create_record`, `bulk_insert`, `execute_seed_plan` |
253
+ | `update` | Update records | `update_record`, `bulk_update` |
254
+ | `delete` | Delete records | `delete_record`, `bulk_delete`, DELETE via `execute_write_query` (requires both `execute` and `delete`) |
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` |
258
+ | `transaction` | Transaction management | `begin_transaction`, `commit_transaction` |
259
+ | `procedure` | Stored procedures | `create_stored_procedure`, `execute_stored_procedure` |
260
+
261
+ ### Filtering Logic
262
+
263
+ ```
264
+ Tool enabled = (Has Permission) AND (Has Category OR No categories specified)
265
+ ```
266
+
267
+ With no permissions and no categories configured, the effective permissions are `list,read,utility` (read-only default since v1.44.0). Categories alone keep all permissions and filter by category.
268
+
269
+ CSV exports require both `utility` and `read` permissions; their category remains `utilities`.
270
+
271
+ `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.
272
+
273
+ Information queries such as SHOW/DESCRIBE/EXPLAIN require `list` or `read`. MySQL DDL may implicitly commit, even when called through a transaction tool.
274
+
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
+
277
+ `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
+
279
+ ---
280
+
281
+ ## Tool Categories
282
+
283
+ ### 1. Database Discovery (4 tools)
284
+ - `list_databases` - List all databases
285
+ - `list_tables` - List tables in database
286
+ - `read_table_schema` - Get table structure
287
+ - `get_all_tables_relationships` - Get all FK relationships
288
+
289
+ ### 2. Analysis (7 tools)
290
+ - `get_database_summary` - Database overview with statistics
291
+ - `get_schema_erd` - Generate Mermaid.js ER diagram
292
+ - `get_schema_rag_context` - Compact schema for LLM context, with optional comments and keyword filtering
293
+ - `get_column_statistics` - Column data profiling
294
+ - `find_tables_by_keyword` - Ranked schema keyword search across table names, column names, and comments
295
+ - `search_schema` - Unified discovery for “where is X?” questions using schema metadata and optional sample-data search
296
+ - `search_data_across_tables` - Guarded read-only keyword search across text-like data columns
297
+
298
+ ### 3. Data Operations (7 tools)
299
+ - `create_record` - Insert single record
300
+ - `read_records` - Query with filtering/pagination
301
+ - `update_record` - Update records
302
+ - `delete_record` - Delete records
303
+ - `bulk_insert` - Batch insert (performance)
304
+ - `bulk_update` - Batch update (performance)
305
+ - `bulk_delete` - Batch delete (performance)
306
+
307
+ ### 4. Seed Operations (6 tools)
308
+ - `plan_seed_data` - Build FK-aware relational seed plans
309
+ - `generate_seed_preview` - Preview deterministic dummy rows without writing
310
+ - `execute_seed_plan` - Execute confirmed seed plans with transaction and rollback safety
311
+ - `validate_seed_integrity` - Validate row counts, FK orphans, required columns, and unique collisions
312
+ - `infer_seed_rules` - Infer advanced generators from schema, samples, unique indexes, and domain presets
313
+ - `seed_from_template` - Create reusable plan-first seed workflows for ecommerce, POS, and CRM domains
314
+
315
+ ### 5. Query Management (2 tools)
316
+ - `run_select_query` - Execute SELECT queries
317
+ - `execute_write_query` - Execute INSERT/UPDATE (DELETE requires the `delete` permission)
318
+
319
+ ### 6. Schema Management (4 tools)
320
+ - `create_table` - Create new tables
321
+ - `alter_table` - Modify table structure
322
+ - `drop_table` - Delete tables
323
+ - `execute_ddl` - Execute raw DDL
324
+
325
+ ### 7. Data Export (2 tools)
326
+ - `export_table_to_csv` - Export table data to CSV
327
+ - `export_query_to_csv` - Export SELECT query results to CSV
328
+
329
+ ### 8. Index Management (11 tools)
330
+ - `list_indexes` - List table indexes
331
+ - `get_index_info` - Get index details
332
+ - `create_index` - Create indexes
333
+ - `drop_index` - Drop indexes
334
+ - `analyze_index` - Analyze and update index statistics
335
+ - `create_fulltext_index` - Create FULLTEXT indexes for text search
336
+ - `fulltext_search` - Perform full-text search with MATCH AGAINST
337
+ - `get_fulltext_info` - Get FULLTEXT index information
338
+ - `drop_fulltext_index` - Drop FULLTEXT indexes
339
+ - `get_fulltext_stats` - Get FULLTEXT index statistics
340
+ - `optimize_fulltext` - Optimize FULLTEXT indexes
341
+
342
+ ### 9. Constraint Management (7 tools)
343
+ - `list_foreign_keys` - List foreign keys
344
+ - `list_constraints` - List all constraints
345
+ - `add_foreign_key` - Add foreign key
346
+ - `drop_foreign_key` - Remove foreign key
347
+ - `add_unique_constraint` - Add unique constraint
348
+ - `drop_constraint` - Remove constraint
349
+ - `add_check_constraint` - Add check constraint
350
+
351
+ ### 10. Stored Procedures (6 tools)
352
+ - `list_stored_procedures` - List procedures
353
+ - `get_stored_procedure_info` - Get procedure details
354
+ - `execute_stored_procedure` - Execute procedures
355
+ - `create_stored_procedure` - Create procedures
356
+ - `drop_stored_procedure` - Remove procedures
357
+ - `show_create_procedure` - Show CREATE statement
358
+
359
+ ### 11. Views Management (6 tools)
360
+ - `list_views` - List views
361
+ - `get_view_info` - Get view details
362
+ - `create_view` - Create views
363
+ - `alter_view` - Modify views
364
+ - `drop_view` - Remove views
365
+ - `show_create_view` - Show CREATE statement
366
+
367
+ ### 12. Triggers Management (5 tools)
368
+ - `list_triggers` - List triggers
369
+ - `get_trigger_info` - Get trigger details
370
+ - `create_trigger` - Create triggers
371
+ - `drop_trigger` - Remove triggers
372
+ - `show_create_trigger` - Show CREATE statement
373
+
374
+ ### 13. Table Maintenance (8 tools)
375
+ - `analyze_table` - Update statistics
376
+ - `optimize_table` - Reclaim space
377
+ - `check_table` - Check for errors
378
+ - `repair_table` - Repair corrupted tables
379
+ - `truncate_table` - Remove all rows
380
+ - `get_table_status` - Get table statistics
381
+ - `flush_table` - Close/reopen table
382
+ - `get_table_size` - Get size information
383
+
384
+ ### 14. Transaction Management (5 tools)
385
+ - `begin_transaction` - Start transaction
386
+ - `commit_transaction` - Commit transaction
387
+ - `rollback_transaction` - Rollback transaction
388
+ - `get_transaction_status` - Check transaction state
389
+ - `execute_in_transaction` - Execute within transaction
390
+
391
+ ### 15. Query Optimization (3 tools)
392
+ - `analyze_query` - Analyze query performance
393
+ - `get_optimization_hints` - Get optimizer hints
394
+ - `repair_query` - Repair broken SQL queries
395
+
396
+ ### 16. Utilities (5 tools)
397
+ - `test_connection` - Test connectivity
398
+ - `describe_connection` - Connection info
399
+ - `read_changelog` - Read changelog
400
+ - `cursor_execute_request` - Execute a file-backed request for clients that cannot send MCP arguments
401
+ - `list_all_tools` - Runtime tool catalog with agent guidance
402
+
403
+ ---
404
+
405
+ ## Core Operations
406
+
407
+ ### Database Discovery
408
+
409
+ Start with these tools to explore any database:
410
+
411
+ ```javascript
412
+ // List all databases
413
+ await mcp.call("list_databases", {});
414
+
415
+ // List tables in current database
416
+ await mcp.call("list_tables", {});
417
+
418
+ // Get comprehensive overview
419
+ await mcp.call("get_database_summary", {
420
+ max_tables: 50,
421
+ include_relationships: true
422
+ });
423
+
424
+ // Visualize relationships
425
+ await mcp.call("get_schema_erd", {});
426
+ ```
427
+
428
+ ### Schema & Data Discovery
429
+
430
+ Use these tools when users ask natural-language questions like “which table stores survey data?” or “where is customer feedback saved?”:
431
+
432
+ ```javascript
433
+ // Fast metadata search across table names, column names, and comments
434
+ await mcp.call("find_tables_by_keyword", {
435
+ keyword: "survey",
436
+ search_in: "all",
437
+ limit: 20
438
+ });
439
+
440
+ // Unified discovery with optional guarded sample-data scan
441
+ await mcp.call("search_schema", {
442
+ query: "survey",
443
+ modes: ["table_names", "column_names", "comments", "sample_data"],
444
+ max_results: 20
445
+ });
446
+
447
+ // Direct bounded data scan when the keyword may only exist in row values
448
+ await mcp.call("search_data_across_tables", {
449
+ keyword: "survey",
450
+ max_tables: 20,
451
+ limit_per_table: 3
452
+ });
453
+ ```
454
+
455
+ `find_tables_by_keyword` requires `list`; `search_data_across_tables` requires `read`; `search_schema` uses `list` and requires `read` only when `sample_data` mode is enabled.
456
+
457
+ ### Data Operations
458
+
459
+ Basic CRUD operations:
460
+
461
+ ```javascript
462
+ // Create record
463
+ await mcp.call("create_record", {
464
+ table_name: "users",
465
+ data: { name: "John", email: "john@example.com" }
466
+ });
467
+
468
+ // Read with filtering
469
+ await mcp.call("read_records", {
470
+ table_name: "users",
471
+ filters: [{ field: "status", operator: "eq", value: "active" }],
472
+ pagination: { page: 1, limit: 10 }
473
+ });
474
+
475
+ // Update records
476
+ await mcp.call("update_record", {
477
+ table_name: "users",
478
+ data: { status: "inactive" },
479
+ conditions: [{ field: "last_login", operator: "lt", value: "2024-01-01" }]
480
+ });
481
+
482
+ // Delete records
483
+ await mcp.call("delete_record", {
484
+ table_name: "users",
485
+ conditions: [{ field: "status", operator: "eq", value: "deleted" }]
486
+ });
487
+ ```
488
+
489
+ ### Performance Operations
490
+
491
+ ```javascript
492
+ // Analyze slow query
493
+ await mcp.call("analyze_query", {
494
+ query: "SELECT * FROM users WHERE email LIKE '%@gmail.com'"
495
+ });
496
+
497
+ // Get optimization hints
498
+ await mcp.call("get_optimization_hints", {
499
+ goal: "SPEED"
500
+ });
501
+ ```
502
+
503
+ ---
504
+
505
+ ## Advanced Features
506
+
507
+ ### Analysis
508
+
509
+ The server includes analysis tools for database insights:
510
+
511
+ - **Database Summary**: Provides readable overviews with statistics
512
+ - **ER Diagram Generation**: Automatic Mermaid.js diagrams
513
+ - **RAG Context**: Compact schema for LLM prompts, with optional `TABLE_COMMENT` / `COLUMN_COMMENT` inclusion and keyword filtering
514
+ - **Column Profiling**: Data quality and distribution analysis
515
+ - **Schema Keyword Discovery**: Ranked search for concepts across table names, column names, and metadata comments
516
+ - **Unified Search**: One entry point for schema and bounded sample-data discovery
517
+ - **Guarded Data Search**: Read-only LIKE scans across text-like columns with strict table/result limits
518
+
519
+ ### Bulk Operations
520
+
521
+ For high-performance operations with large datasets:
522
+
523
+ - **Bulk Insert**: Handle thousands of records efficiently
524
+ - **Bulk Update**: Update multiple records with different conditions
525
+ - **Bulk Delete**: Delete multiple record sets in batches
526
+
527
+ ### Relational Data Seeder
528
+
529
+ For dummy data on related tables, use the seed workflow:
530
+
531
+ ```javascript
532
+ const plan = await mcp.call("plan_seed_data", {
533
+ target_tables: ["orders"],
534
+ rows_per_table: 20,
535
+ include_dependencies: true,
536
+ include_children: true,
537
+ random_seed: 42
538
+ });
539
+
540
+ await mcp.call("generate_seed_preview", {
541
+ plan_id: plan.plan_id,
542
+ max_preview_rows_per_table: 3
543
+ });
544
+
545
+ await mcp.call("execute_seed_plan", {
546
+ plan_id: plan.plan_id,
547
+ dry_run: false,
548
+ confirm_token: plan.confirm_token
549
+ });
550
+
551
+ await mcp.call("validate_seed_integrity", {
552
+ plan_id: plan.plan_id
553
+ });
554
+ ```
555
+
556
+ `execute_seed_plan` defaults to dry-run, requires confirmation for writes, blocks production-like database names unless explicitly allowed, and uses transaction rollback on errors.
557
+
558
+ Composite FK/PK support resolves multi-column parent tuples together, so relations such as `(tenant_id, region_id)` or `(tenant_id, region_id, order_id)` are not mixed across different parent rows.
559
+
560
+ Advanced rule inference and templates:
561
+
562
+ ```javascript
563
+ await mcp.call("infer_seed_rules", {
564
+ tables: ["orders", "order_items"],
565
+ domain: "ecommerce",
566
+ sample_size: 25
567
+ });
568
+
569
+ await mcp.call("seed_from_template", {
570
+ template: "ecommerce",
571
+ scale: "small",
572
+ random_seed: 42
573
+ });
574
+ ```
575
+
576
+ `seed_from_template` is plan-first and does not write data directly. Review its plan/preview, then execute with `execute_seed_plan`.
577
+
578
+ ### Transaction Management
579
+
580
+ ACID transactions run on a dedicated connection. Run statements inside a transaction with `execute_in_transaction`; other tools such as `create_record` run outside it.
581
+
582
+ ```javascript
583
+ const { transactionId } = await mcp.call("begin_transaction", {});
584
+ await mcp.call("execute_in_transaction", {
585
+ transactionId,
586
+ query: "INSERT INTO orders (customer_id, total) VALUES (?, ?)",
587
+ params: [42, 99.5]
588
+ });
589
+ await mcp.call("execute_in_transaction", {
590
+ transactionId,
591
+ query: "UPDATE inventory SET stock = stock - 1 WHERE product_id = ?",
592
+ params: [7]
593
+ });
594
+ await mcp.call("commit_transaction", { transactionId }); // or rollback_transaction
595
+ ```
596
+
597
+ - `begin_transaction` accepts an optional `transactionId`. An id that is already in use is rejected (v1.45.0).
598
+ - `get_transaction_status` returns `activeTransactions`, the ids open in the caller's session (v1.45.0; earlier versions returned only a count message).
599
+ - Open transactions are rolled back after 30 minutes of inactivity or 1 hour in total. Over HTTP they are also rolled back when their session ends (see [Sessions](#sessions)).
600
+
601
+ ---
602
+
603
+ ## Security Features
604
+
605
+ ### Permission-Based Access Control
606
+
607
+ - **Layer 1**: Broad permission categories (list, read, create, etc.)
608
+ - **Layer 2**: Fine-grained tool category filtering
609
+ - **Tool-level**: Each tool requires specific permissions
610
+ - **Execution-time enforcement**: Tool permissions and categories are checked for every call, including file-backed Cursor requests.
611
+ - **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.
612
+ - **Quoted content (v1.44.0)**: Comment, statement-separator, and keyword checks ignore the contents of string literals and quoted identifiers, so values such as `'#fff'`, `'a;b'`, or `'x -- y'` are accepted. A literal containing a backslash is lexed differently depending on `NO_BACKSLASH_ESCAPES`, so such queries are checked strictly against the raw text.
613
+ - **Common table expressions (v1.44.0)**: `WITH ... SELECT/UPDATE/DELETE` is authorized as its main statement. Like derived tables and UNION, a CTE in a read query requires `execute`. A `WITH` clause that cannot be parsed is rejected.
614
+
615
+ ### Vulnerability Reporting
616
+
617
+ 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).
618
+
619
+ ### Data Protection
620
+
621
+ - **Query Validation**: Input validation and SQL injection prevention
622
+ - **No result masking**: Query and export results are returned unmasked. Restrict sensitive columns with database privileges or views.
623
+
624
+ ### Remote Access Security (v1.45.0)
625
+
626
+ - **Opt-in HTTP**: the Streamable HTTP transport is off unless `MCP_TRANSPORT=http` or `--transport=http` is set. See [Remote Access](#remote-access-streamable-http-transport-v1450-2026-10-26-144606).
627
+ - **Authentication**: bearer tokens or OAuth 2.1 JWT validation. Unauthenticated mode is restricted to loopback.
628
+ - **DNS-rebinding protection**: `Host` and `Origin` headers are checked against allowlists.
629
+ - **Session isolation**: sessions are bound to their identity, and transactions to their session.
630
+ - **Database protection**: query timeout with server-side cancellation, a per-client rate limit, a result size limit, and an audit log.
631
+
632
+ ### Connection Security
633
+
634
+ - **Environment Variables**: Secure credential management
635
+ - **Connection Testing**: Validation before operations
636
+ - **Error Handling**: Comprehensive error reporting
637
+
638
+ ---
639
+
640
+ ---
641
+
642
+ ## Troubleshooting
643
+
644
+ ### Common Issues
645
+
646
+ 1. **Permission Denied**: Check both permission layers in error messages
647
+ 2. **Connection Failed**: Verify database credentials and network
648
+ 3. **Query Errors**: Use `repair_query` for diagnosis
649
+ 4. **Performance Issues**: Use `analyze_query` and optimization hints
650
+
651
+ ### MCP error `-32000: Connection closed` (local server)
652
+
653
+ If your client reports `MCP error -32000: Connection closed`, the server process is usually crashing on startup.
654
+
655
+ If you see `ReferenceError: exports is not defined in ES module scope` in the server stderr logs, update to **v1.33.2+** (fixes an ESM/CJS mismatch that caused the MCP process to exit immediately).
656
+
657
+ ### Development
658
+
659
+ - `npm run build` removes `dist/` before compiling, so files deleted from `src/` are never published.
660
+ - `npm run dev` runs `src/mcp-server.ts` with ts-node (fixed in v1.44.0).
661
+ - `npm test` runs the Jest suite in `src/__tests__/` (SQL validator, permission defaults, cache invalidation; since v1.45.0 also runtime config, bearer/OAuth authentication, the Streamable HTTP server, tool annotations, grant inspection, and rate limiting). None of these tests need a database.
662
+
663
+ ### Error Messages
664
+
665
+ The system provides detailed error messages indicating:
666
+
667
+ - Which permission layer blocked access
668
+ - Required permissions vs current permissions
669
+ - Specific category requirements
670
+ - SQL syntax and logic errors
671
+
672
+ ---
673
+
674
+ *For detailed examples and advanced usage patterns, see the project README.md.*