@berthojoris/mcp-mysql-server 1.44.0 → 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.
package/DOCUMENTATIONS.md CHANGED
@@ -1,524 +1,674 @@
1
- # MySQL MCP Server - Documentation
2
-
3
- **Last Updated:** 2026-10-26 13:35:39
4
- **Version:** 1.44.0
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
- ### Defaults (v1.44.0, 2026-10-26 13:35:39)
69
-
70
- - **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`.
71
- - **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.
72
- - **Query cache**: disabled by default. Set `CACHE_ENABLED=true` to opt in (`CACHE_TTL_MS`, default `60000`; `CACHE_MAX_SIZE`, default `100`). 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.
73
-
74
- ---
75
-
76
- ### Cursor Compatibility Bridge
77
-
78
- 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.
79
-
80
- Execute any existing MCP tool:
81
-
82
- ```json
83
- {
84
- "tool": "execute_ddl",
85
- "arguments": {
86
- "query": "DROP TABLE IF EXISTS spark_processes;"
87
- }
88
- }
89
- ```
90
-
91
- Or execute SQL directly with automatic routing:
92
-
93
- ```json
94
- {
95
- "query": "DROP TABLE IF EXISTS spark_processes;",
96
- "mode": "auto"
97
- }
98
- ```
99
-
100
- Supported `mode` values are `auto`, `select`, `write`, and `ddl`. Set `MYSQL_MCP_CURSOR_REQUEST_FILE` to override the request file path.
101
-
102
- 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.
103
-
104
- ---
105
-
106
- ### AI Agent Tool Discovery
107
-
108
- 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.
109
-
110
- For CSV exports, use `export_table_to_csv` for table-based exports and `export_query_to_csv` for SELECT query exports.
111
-
112
- ---
113
-
114
- ## Permission System
115
-
116
- ### Available Permissions
117
-
118
- | Permission | Operations | Example Tools |
119
- |------------|------------|---------------|
120
- | `list` | List/discover objects | `list_databases`, `list_tables` |
121
- | `read` | Read data | `read_records`, `run_select_query` |
122
- | `create` | Insert records and seed data | `create_record`, `bulk_insert`, `execute_seed_plan` |
123
- | `update` | Update records | `update_record`, `bulk_update` |
124
- | `delete` | Delete records | `delete_record`, `bulk_delete`, DELETE via `execute_write_query` (requires both `execute` and `delete`) |
125
- | `execute` | Custom SQL (INSERT/UPDATE; not DELETE without `delete`) | `execute_write_query` |
126
- | `ddl` | Schema changes | `create_table`, `alter_table` |
127
- | `utility` | Utility operations | `test_connection`, `analyze_table` |
128
- | `transaction` | Transaction management | `begin_transaction`, `commit_transaction` |
129
- | `procedure` | Stored procedures | `create_stored_procedure`, `execute_stored_procedure` |
130
-
131
- ### Filtering Logic
132
-
133
- ```
134
- Tool enabled = (Has Permission) AND (Has Category OR No categories specified)
135
- ```
136
-
137
- 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.
138
-
139
- CSV exports require both `utility` and `read` permissions; their category remains `utilities`.
140
-
141
- `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.
142
-
143
- Information queries such as SHOW/DESCRIBE/EXPLAIN require `list` or `read`. MySQL DDL may implicitly commit, even when called through a transaction tool.
144
-
145
- `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).
146
-
147
- `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.
148
-
149
- ---
150
-
151
- ## Tool Categories
152
-
153
- ### 1. Database Discovery (4 tools)
154
- - `list_databases` - List all databases
155
- - `list_tables` - List tables in database
156
- - `read_table_schema` - Get table structure
157
- - `get_all_tables_relationships` - Get all FK relationships
158
-
159
- ### 2. Analysis (7 tools)
160
- - `get_database_summary` - Database overview with statistics
161
- - `get_schema_erd` - Generate Mermaid.js ER diagram
162
- - `get_schema_rag_context` - Compact schema for LLM context, with optional comments and keyword filtering
163
- - `get_column_statistics` - Column data profiling
164
- - `find_tables_by_keyword` - Ranked schema keyword search across table names, column names, and comments
165
- - `search_schema` - Unified discovery for “where is X?” questions using schema metadata and optional sample-data search
166
- - `search_data_across_tables` - Guarded read-only keyword search across text-like data columns
167
-
168
- ### 3. Data Operations (7 tools)
169
- - `create_record` - Insert single record
170
- - `read_records` - Query with filtering/pagination
171
- - `update_record` - Update records
172
- - `delete_record` - Delete records
173
- - `bulk_insert` - Batch insert (performance)
174
- - `bulk_update` - Batch update (performance)
175
- - `bulk_delete` - Batch delete (performance)
176
-
177
- ### 4. Seed Operations (6 tools)
178
- - `plan_seed_data` - Build FK-aware relational seed plans
179
- - `generate_seed_preview` - Preview deterministic dummy rows without writing
180
- - `execute_seed_plan` - Execute confirmed seed plans with transaction and rollback safety
181
- - `validate_seed_integrity` - Validate row counts, FK orphans, required columns, and unique collisions
182
- - `infer_seed_rules` - Infer advanced generators from schema, samples, unique indexes, and domain presets
183
- - `seed_from_template` - Create reusable plan-first seed workflows for ecommerce, POS, and CRM domains
184
-
185
- ### 5. Query Management (2 tools)
186
- - `run_select_query` - Execute SELECT queries
187
- - `execute_write_query` - Execute INSERT/UPDATE (DELETE requires the `delete` permission)
188
-
189
- ### 6. Schema Management (4 tools)
190
- - `create_table` - Create new tables
191
- - `alter_table` - Modify table structure
192
- - `drop_table` - Delete tables
193
- - `execute_ddl` - Execute raw DDL
194
-
195
- ### 7. Data Export (2 tools)
196
- - `export_table_to_csv` - Export table data to CSV
197
- - `export_query_to_csv` - Export SELECT query results to CSV
198
-
199
- ### 8. Index Management (11 tools)
200
- - `list_indexes` - List table indexes
201
- - `get_index_info` - Get index details
202
- - `create_index` - Create indexes
203
- - `drop_index` - Drop indexes
204
- - `analyze_index` - Analyze and update index statistics
205
- - `create_fulltext_index` - Create FULLTEXT indexes for text search
206
- - `fulltext_search` - Perform full-text search with MATCH AGAINST
207
- - `get_fulltext_info` - Get FULLTEXT index information
208
- - `drop_fulltext_index` - Drop FULLTEXT indexes
209
- - `get_fulltext_stats` - Get FULLTEXT index statistics
210
- - `optimize_fulltext` - Optimize FULLTEXT indexes
211
-
212
- ### 9. Constraint Management (7 tools)
213
- - `list_foreign_keys` - List foreign keys
214
- - `list_constraints` - List all constraints
215
- - `add_foreign_key` - Add foreign key
216
- - `drop_foreign_key` - Remove foreign key
217
- - `add_unique_constraint` - Add unique constraint
218
- - `drop_constraint` - Remove constraint
219
- - `add_check_constraint` - Add check constraint
220
-
221
- ### 10. Stored Procedures (6 tools)
222
- - `list_stored_procedures` - List procedures
223
- - `get_stored_procedure_info` - Get procedure details
224
- - `execute_stored_procedure` - Execute procedures
225
- - `create_stored_procedure` - Create procedures
226
- - `drop_stored_procedure` - Remove procedures
227
- - `show_create_procedure` - Show CREATE statement
228
-
229
- ### 11. Views Management (6 tools)
230
- - `list_views` - List views
231
- - `get_view_info` - Get view details
232
- - `create_view` - Create views
233
- - `alter_view` - Modify views
234
- - `drop_view` - Remove views
235
- - `show_create_view` - Show CREATE statement
236
-
237
- ### 12. Triggers Management (5 tools)
238
- - `list_triggers` - List triggers
239
- - `get_trigger_info` - Get trigger details
240
- - `create_trigger` - Create triggers
241
- - `drop_trigger` - Remove triggers
242
- - `show_create_trigger` - Show CREATE statement
243
-
244
- ### 13. Table Maintenance (8 tools)
245
- - `analyze_table` - Update statistics
246
- - `optimize_table` - Reclaim space
247
- - `check_table` - Check for errors
248
- - `repair_table` - Repair corrupted tables
249
- - `truncate_table` - Remove all rows
250
- - `get_table_status` - Get table statistics
251
- - `flush_table` - Close/reopen table
252
- - `get_table_size` - Get size information
253
-
254
- ### 14. Transaction Management (5 tools)
255
- - `begin_transaction` - Start transaction
256
- - `commit_transaction` - Commit transaction
257
- - `rollback_transaction` - Rollback transaction
258
- - `get_transaction_status` - Check transaction state
259
- - `execute_in_transaction` - Execute within transaction
260
-
261
- ### 15. Query Optimization (3 tools)
262
- - `analyze_query` - Analyze query performance
263
- - `get_optimization_hints` - Get optimizer hints
264
- - `repair_query` - Repair broken SQL queries
265
-
266
- ### 16. Utilities (5 tools)
267
- - `test_connection` - Test connectivity
268
- - `describe_connection` - Connection info
269
- - `read_changelog` - Read changelog
270
- - `cursor_execute_request` - Execute a file-backed request for clients that cannot send MCP arguments
271
- - `list_all_tools` - Runtime tool catalog with agent guidance
272
-
273
- ---
274
-
275
- ## Core Operations
276
-
277
- ### Database Discovery
278
-
279
- Start with these tools to explore any database:
280
-
281
- ```javascript
282
- // List all databases
283
- await mcp.call("list_databases", {});
284
-
285
- // List tables in current database
286
- await mcp.call("list_tables", {});
287
-
288
- // Get comprehensive overview
289
- await mcp.call("get_database_summary", {
290
- max_tables: 50,
291
- include_relationships: true
292
- });
293
-
294
- // Visualize relationships
295
- await mcp.call("get_schema_erd", {});
296
- ```
297
-
298
- ### Schema & Data Discovery
299
-
300
- Use these tools when users ask natural-language questions like “which table stores survey data?” or “where is customer feedback saved?”:
301
-
302
- ```javascript
303
- // Fast metadata search across table names, column names, and comments
304
- await mcp.call("find_tables_by_keyword", {
305
- keyword: "survey",
306
- search_in: "all",
307
- limit: 20
308
- });
309
-
310
- // Unified discovery with optional guarded sample-data scan
311
- await mcp.call("search_schema", {
312
- query: "survey",
313
- modes: ["table_names", "column_names", "comments", "sample_data"],
314
- max_results: 20
315
- });
316
-
317
- // Direct bounded data scan when the keyword may only exist in row values
318
- await mcp.call("search_data_across_tables", {
319
- keyword: "survey",
320
- max_tables: 20,
321
- limit_per_table: 3
322
- });
323
- ```
324
-
325
- `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.
326
-
327
- ### Data Operations
328
-
329
- Basic CRUD operations:
330
-
331
- ```javascript
332
- // Create record
333
- await mcp.call("create_record", {
334
- table_name: "users",
335
- data: { name: "John", email: "john@example.com" }
336
- });
337
-
338
- // Read with filtering
339
- await mcp.call("read_records", {
340
- table_name: "users",
341
- filters: [{ field: "status", operator: "eq", value: "active" }],
342
- pagination: { page: 1, limit: 10 }
343
- });
344
-
345
- // Update records
346
- await mcp.call("update_record", {
347
- table_name: "users",
348
- data: { status: "inactive" },
349
- conditions: [{ field: "last_login", operator: "lt", value: "2024-01-01" }]
350
- });
351
-
352
- // Delete records
353
- await mcp.call("delete_record", {
354
- table_name: "users",
355
- conditions: [{ field: "status", operator: "eq", value: "deleted" }]
356
- });
357
- ```
358
-
359
- ### Performance Operations
360
-
361
- ```javascript
362
- // Analyze slow query
363
- await mcp.call("analyze_query", {
364
- query: "SELECT * FROM users WHERE email LIKE '%@gmail.com'"
365
- });
366
-
367
- // Get optimization hints
368
- await mcp.call("get_optimization_hints", {
369
- goal: "SPEED"
370
- });
371
- ```
372
-
373
- ---
374
-
375
- ## Advanced Features
376
-
377
- ### Analysis
378
-
379
- The server includes analysis tools for database insights:
380
-
381
- - **Database Summary**: Provides readable overviews with statistics
382
- - **ER Diagram Generation**: Automatic Mermaid.js diagrams
383
- - **RAG Context**: Compact schema for LLM prompts, with optional `TABLE_COMMENT` / `COLUMN_COMMENT` inclusion and keyword filtering
384
- - **Column Profiling**: Data quality and distribution analysis
385
- - **Schema Keyword Discovery**: Ranked search for concepts across table names, column names, and metadata comments
386
- - **Unified Search**: One entry point for schema and bounded sample-data discovery
387
- - **Guarded Data Search**: Read-only LIKE scans across text-like columns with strict table/result limits
388
-
389
- ### Bulk Operations
390
-
391
- For high-performance operations with large datasets:
392
-
393
- - **Bulk Insert**: Handle thousands of records efficiently
394
- - **Bulk Update**: Update multiple records with different conditions
395
- - **Bulk Delete**: Delete multiple record sets in batches
396
-
397
- ### Relational Data Seeder
398
-
399
- For dummy data on related tables, use the seed workflow:
400
-
401
- ```javascript
402
- const plan = await mcp.call("plan_seed_data", {
403
- target_tables: ["orders"],
404
- rows_per_table: 20,
405
- include_dependencies: true,
406
- include_children: true,
407
- random_seed: 42
408
- });
409
-
410
- await mcp.call("generate_seed_preview", {
411
- plan_id: plan.plan_id,
412
- max_preview_rows_per_table: 3
413
- });
414
-
415
- await mcp.call("execute_seed_plan", {
416
- plan_id: plan.plan_id,
417
- dry_run: false,
418
- confirm_token: plan.confirm_token
419
- });
420
-
421
- await mcp.call("validate_seed_integrity", {
422
- plan_id: plan.plan_id
423
- });
424
- ```
425
-
426
- `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.
427
-
428
- 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.
429
-
430
- Advanced rule inference and templates:
431
-
432
- ```javascript
433
- await mcp.call("infer_seed_rules", {
434
- tables: ["orders", "order_items"],
435
- domain: "ecommerce",
436
- sample_size: 25
437
- });
438
-
439
- await mcp.call("seed_from_template", {
440
- template: "ecommerce",
441
- scale: "small",
442
- random_seed: 42
443
- });
444
- ```
445
-
446
- `seed_from_template` is plan-first and does not write data directly. Review its plan/preview, then execute with `execute_seed_plan`.
447
-
448
- ### Transaction Management
449
-
450
- Full ACID transaction support:
451
-
452
- ```javascript
453
- await mcp.call("begin_transaction", {});
454
- await mcp.call("create_record", { table_name: "orders", data: {...} });
455
- await mcp.call("update_record", { table_name: "inventory", data: {...} });
456
- await mcp.call("commit_transaction", {});
457
- ```
458
-
459
- ---
460
-
461
- ## Security Features
462
-
463
- ### Permission-Based Access Control
464
-
465
- - **Layer 1**: Broad permission categories (list, read, create, etc.)
466
- - **Layer 2**: Fine-grained tool category filtering
467
- - **Tool-level**: Each tool requires specific permissions
468
- - **Execution-time enforcement**: Tool permissions and categories are checked for every call, including file-backed Cursor requests.
469
- - **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.
470
- - **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.
471
- - **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.
472
-
473
- ### Vulnerability Reporting
474
-
475
- 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).
476
-
477
- ### Data Protection
478
-
479
- - **Query Validation**: Input validation and SQL injection prevention
480
- - **No result masking**: Query and export results are returned unmasked. Restrict sensitive columns with database privileges or views.
481
-
482
- ### Connection Security
483
-
484
- - **Environment Variables**: Secure credential management
485
- - **Connection Testing**: Validation before operations
486
- - **Error Handling**: Comprehensive error reporting
487
-
488
- ---
489
-
490
- ---
491
-
492
- ## Troubleshooting
493
-
494
- ### Common Issues
495
-
496
- 1. **Permission Denied**: Check both permission layers in error messages
497
- 2. **Connection Failed**: Verify database credentials and network
498
- 3. **Query Errors**: Use `repair_query` for diagnosis
499
- 4. **Performance Issues**: Use `analyze_query` and optimization hints
500
-
501
- ### MCP error `-32000: Connection closed` (local server)
502
-
503
- If your client reports `MCP error -32000: Connection closed`, the server process is usually crashing on startup.
504
-
505
- 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).
506
-
507
- ### Development
508
-
509
- - `npm run build` removes `dist/` before compiling, so files deleted from `src/` are never published.
510
- - `npm run dev` runs `src/mcp-server.ts` with ts-node (fixed in v1.44.0).
511
- - `npm test` runs the Jest suite in `src/__tests__/` (SQL validator, permission defaults, cache invalidation).
512
-
513
- ### Error Messages
514
-
515
- The system provides detailed error messages indicating:
516
-
517
- - Which permission layer blocked access
518
- - Required permissions vs current permissions
519
- - Specific category requirements
520
- - SQL syntax and logic errors
521
-
522
- ---
523
-
524
- *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.*