@berthojoris/mcp-mysql-server 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,1142 @@
1
+ # MySQL MCP Server
2
+
3
+ A fully-featured **Model Context Protocol (MCP)** server for MySQL database integration with AI agents like Claude Desktop, Cline, Windsurf, and other MCP-compatible tools.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@modelcontextprotocol/server-mysql)](https://www.npmjs.com/package/@modelcontextprotocol/server-mysql)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ---
9
+
10
+ ## 🌟 Features
11
+
12
+ - βœ… **Full MCP Protocol Support** - Works with Claude Desktop, Cline, Windsurf, and any MCP-compatible AI agent
13
+ - πŸ”’ **Secure by Default** - Parameterized queries, SQL injection protection, permission-based access control
14
+ - πŸ› οΈ **27 Powerful Tools** - Complete database operations (CRUD, DDL, queries, schema inspection, transactions, stored procedures)
15
+ - πŸŽ›οΈ **Dynamic Per-Project Permissions** - Each AI agent can have different access levels
16
+ - πŸ—οΈ **DDL Support** - Create, alter, and drop tables (when explicitly enabled)
17
+ - πŸ’° **Transaction Support** - Full ACID transaction management (BEGIN, COMMIT, ROLLBACK)
18
+ - 🌐 **Dual Mode** - Run as MCP server OR as REST API
19
+ - πŸ“Š **Rich Metadata** - Table schemas, relationships, connection info
20
+ - ⚑ **TypeScript** - Fully typed with TypeScript definitions
21
+
22
+ ---
23
+
24
+ ## πŸ“¦ Installation
25
+
26
+ ### Option 1: Quick Start (npx)
27
+
28
+ No installation needed! Use directly with npx:
29
+
30
+ ```bash
31
+ npx @modelcontextprotocol/server-mysql mysql://user:pass@localhost:3306/db "list,read,utility"
32
+ ```
33
+
34
+ ### Option 2: Clone and Build
35
+
36
+ ```bash
37
+ git clone <your-repo-url>
38
+ cd mcp_mysql
39
+ npm install
40
+ npm run build
41
+ ```
42
+
43
+ ### Option 3: Global Installation
44
+
45
+ ```bash
46
+ npm install -g @modelcontextprotocol/server-mysql
47
+ mcp-mysql mysql://user:pass@localhost:3306/db "list,read,utility"
48
+ ```
49
+
50
+ ---
51
+
52
+ ## πŸš€ Quick Start
53
+
54
+ ### 1. Set Up Environment
55
+
56
+ Create `.env` file (for local development):
57
+
58
+ ```env
59
+ DB_HOST=localhost
60
+ DB_PORT=3306
61
+ DB_USER=root
62
+ DB_PASSWORD=yourpassword
63
+ DB_NAME=yourdatabase
64
+
65
+ # Optional: Default permissions (can be overridden per-project)
66
+ MCP_CONFIG=list,read,utility
67
+ ```
68
+
69
+ ### 2. Build Project (if cloned)
70
+
71
+ ```bash
72
+ npm run build
73
+ ```
74
+
75
+ ### 3. Configure AI Agent
76
+
77
+ #### Claude Desktop
78
+
79
+ **Location:**
80
+ - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
81
+ - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
82
+
83
+ **Configuration:**
84
+
85
+ ```json
86
+ {
87
+ "mcpServers": {
88
+ "mysql": {
89
+ "command": "node",
90
+ "args": [
91
+ "C:\\path\\to\\mcp_mysql\\bin\\mcp-mysql.js",
92
+ "mysql://user:password@localhost:3306/database",
93
+ "list,read,utility"
94
+ ]
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+ **Or use npx (if published):**
101
+
102
+ ```json
103
+ {
104
+ "mcpServers": {
105
+ "mysql": {
106
+ "command": "npx",
107
+ "args": [
108
+ "-y",
109
+ "@modelcontextprotocol/server-mysql",
110
+ "mysql://user:password@localhost:3306/database",
111
+ "list,read,utility"
112
+ ]
113
+ }
114
+ }
115
+ }
116
+ ```
117
+
118
+ #### Cline (VS Code Extension)
119
+
120
+ Add to Cline MCP settings (same JSON format as Claude Desktop).
121
+
122
+ #### Windsurf
123
+
124
+ Add to Windsurf MCP settings (same JSON format as Claude Desktop).
125
+
126
+ ### 4. Restart AI Agent
127
+
128
+ Completely restart your AI agent application to load the MCP server.
129
+
130
+ ### 5. Test It!
131
+
132
+ Try asking your AI:
133
+ - *"What databases are available?"*
134
+ - *"Show me all tables in my database"*
135
+ - *"What's the structure of the users table?"*
136
+ - *"Show me the first 5 records from users"*
137
+
138
+ ---
139
+
140
+ ## πŸ› οΈ Available Tools
141
+
142
+ The MCP server provides **27 powerful tools**:
143
+
144
+ ### Database Discovery (4 tools)
145
+
146
+ | Tool | Description |
147
+ |------|-------------|
148
+ | `list_databases` | Lists all databases on the MySQL server |
149
+ | `list_tables` | Lists all tables in the current/specified database |
150
+ | `read_table_schema` | Gets detailed schema (columns, types, keys, indexes) |
151
+ | `get_table_relationships` | Discovers foreign key relationships |
152
+
153
+ ### Data Operations - CRUD (4 tools)
154
+
155
+ | Tool | Description |
156
+ |------|-------------|
157
+ | `create_record` | Insert new records with automatic SQL generation |
158
+ | `read_records` | Query records with filtering, pagination, and sorting |
159
+ | `update_record` | Update records based on conditions |
160
+ | `delete_record` | Delete records with safety checks |
161
+
162
+ ### Custom Queries (2 tools)
163
+
164
+ | Tool | Description |
165
+ |------|-------------|
166
+ | `run_query` | Execute read-only SELECT queries |
167
+ | `execute_sql` | Execute write operations (INSERT, UPDATE, DELETE, or DDL with permission) |
168
+
169
+ ### Schema Management - DDL (4 tools)
170
+
171
+ | Tool | Description | Requires |
172
+ |------|-------------|----------|
173
+ | `create_table` | Create new tables with columns and indexes | `ddl` permission |
174
+ | `alter_table` | Modify table structure (add/drop/modify columns, indexes) | `ddl` permission |
175
+ | `drop_table` | Delete tables | `ddl` permission |
176
+ | `execute_ddl` | Execute raw DDL SQL (CREATE, ALTER, DROP, TRUNCATE, RENAME) | `ddl` permission |
177
+
178
+ ### Utilities (2 tools)
179
+
180
+ | Tool | Description |
181
+ |------|-------------|
182
+ | `test_connection` | Test database connectivity and measure latency |
183
+ | `describe_connection` | Get current connection information |
184
+
185
+ ### Transaction Management (5 tools)
186
+
187
+ | Tool | Description |
188
+ |------|-------------|
189
+ | `begin_transaction` | Start a new database transaction |
190
+ | `commit_transaction` | Commit the current transaction |
191
+ | `rollback_transaction` | Rollback the current transaction |
192
+ | `get_transaction_status` | Check if a transaction is active |
193
+ | `execute_in_transaction` | Execute SQL within a transaction context |
194
+
195
+ ### Stored Procedures (5 tools)
196
+
197
+ | Tool | Description | Requires |
198
+ |------|-------------|----------|
199
+ | `list_stored_procedures` | List all stored procedures in a database | `procedure` permission |
200
+ | `create_stored_procedure` | Create new stored procedures with parameters | `procedure` permission |
201
+ | `get_stored_procedure_info` | Get detailed information about a stored procedure | `procedure` permission |
202
+ | `execute_stored_procedure` | Execute stored procedures with IN/OUT/INOUT parameters | `procedure` permission |
203
+ | `drop_stored_procedure` | Delete stored procedures | `procedure` permission |
204
+
205
+ ---
206
+
207
+ ## πŸ” Permission System
208
+
209
+ ### Permission Categories
210
+
211
+ Control access with these permission categories:
212
+
213
+ | Category | Operations | Example Use Case |
214
+ |----------|------------|------------------|
215
+ | **`list`** | List databases, tables, schemas | Database exploration |
216
+ | **`read`** | SELECT queries, read data | Analytics, reporting |
217
+ | **`create`** | INSERT new records | Data entry |
218
+ | **`update`** | UPDATE existing records | Data maintenance |
219
+ | **`delete`** | DELETE records | Data cleanup |
220
+ | **`execute`** | Execute custom SQL (DML) | Complex operations |
221
+ | **`ddl`** | CREATE/ALTER/DROP tables | Schema management |
222
+ | **`procedure`** | CREATE/DROP/EXECUTE stored procedures | Stored procedure management |
223
+ | **`transaction`** | BEGIN, COMMIT, ROLLBACK transactions | ACID operations |
224
+ | **`utility`** | Connection testing, info | Diagnostics |
225
+
226
+ ### Per-Project Configuration
227
+
228
+ **Each project can have different permissions!** Specify as the third argument:
229
+
230
+ ```json
231
+ {
232
+ "args": [
233
+ "mysql://user:pass@localhost:3306/db",
234
+ "list,read,utility" // ← Permissions here
235
+ ]
236
+ }
237
+ ```
238
+
239
+ ### Common Permission Sets
240
+
241
+ **Production Read-Only:**
242
+ ```
243
+ list,read,utility
244
+ ```
245
+
246
+ **Data Entry:**
247
+ ```
248
+ list,read,create,utility
249
+ ```
250
+
251
+ **Full Data Access (No Schema Changes):**
252
+ ```
253
+ list,read,create,update,delete,utility
254
+ ```
255
+
256
+ **Full Data Access with Transactions:**
257
+ ```
258
+ list,read,create,update,delete,transaction,utility
259
+ ```
260
+
261
+ **Development (Full Access):**
262
+ ```
263
+ list,read,create,update,delete,execute,ddl,transaction,utility
264
+ ```
265
+
266
+ **DBA Tasks:**
267
+ ```
268
+ list,ddl,utility
269
+ ```
270
+
271
+ ### Multiple Projects Example
272
+
273
+ You can have different databases with different permissions in the same AI agent:
274
+
275
+ ```json
276
+ {
277
+ "mcpServers": {
278
+ "mysql-prod": {
279
+ "command": "node",
280
+ "args": [
281
+ "C:\\path\\to\\bin\\mcp-mysql.js",
282
+ "mysql://reader:pass@prod-server:3306/prod_db",
283
+ "list,read,utility"
284
+ ]
285
+ },
286
+ "mysql-dev": {
287
+ "command": "node",
288
+ "args": [
289
+ "C:\\path\\to\\bin\\mcp-mysql.js",
290
+ "mysql://root:pass@localhost:3306/dev_db",
291
+ "list,read,create,update,delete,execute,ddl,utility"
292
+ ]
293
+ }
294
+ }
295
+ }
296
+ ```
297
+
298
+ ---
299
+
300
+ ## πŸ—οΈ DDL Operations
301
+
302
+ DDL (Data Definition Language) operations allow AI to create, modify, and delete tables.
303
+
304
+ ### ⚠️ Enable DDL with Caution
305
+
306
+ DDL operations are **disabled by default** for safety. Add `ddl` to permissions to enable:
307
+
308
+ ```json
309
+ {
310
+ "args": [
311
+ "mysql://user:pass@localhost:3306/db",
312
+ "list,read,create,update,delete,ddl,utility"
313
+ ]
314
+ }
315
+ ```
316
+
317
+ ### DDL Tool Examples
318
+
319
+ #### Create Table
320
+
321
+ **User prompt:** *"Create a users table with id, username, email, and created_at"*
322
+
323
+ **AI will execute:**
324
+ ```json
325
+ {
326
+ "tool": "create_table",
327
+ "arguments": {
328
+ "table_name": "users",
329
+ "columns": [
330
+ {"name": "id", "type": "INT", "primary_key": true, "auto_increment": true},
331
+ {"name": "username", "type": "VARCHAR(255)", "nullable": false},
332
+ {"name": "email", "type": "VARCHAR(255)", "nullable": false},
333
+ {"name": "created_at", "type": "DATETIME", "default": "CURRENT_TIMESTAMP"}
334
+ ]
335
+ }
336
+ }
337
+ ```
338
+
339
+ #### Alter Table
340
+
341
+ **User prompt:** *"Add a phone column to the users table"*
342
+
343
+ **AI will execute:**
344
+ ```json
345
+ {
346
+ "tool": "alter_table",
347
+ "arguments": {
348
+ "table_name": "users",
349
+ "operations": [
350
+ {
351
+ "type": "add_column",
352
+ "column_name": "phone",
353
+ "column_type": "VARCHAR(20)",
354
+ "nullable": true
355
+ }
356
+ ]
357
+ }
358
+ }
359
+ ```
360
+
361
+ #### Drop Table
362
+
363
+ **User prompt:** *"Drop the temp_data table"*
364
+
365
+ **AI will execute:**
366
+ ```json
367
+ {
368
+ "tool": "drop_table",
369
+ "arguments": {
370
+ "table_name": "temp_data",
371
+ "if_exists": true
372
+ }
373
+ }
374
+ ```
375
+
376
+ ### DDL Safety Guidelines
377
+
378
+ 1. βœ… **Enable only in development** - Keep DDL disabled for production
379
+ 2. βœ… **Backup before major changes** - DDL operations are usually irreversible
380
+ 3. βœ… **Test in dev first** - Try schema changes in development environment
381
+ 4. βœ… **Use proper MySQL user permissions** - Grant only necessary privileges
382
+
383
+ ---
384
+
385
+ ## πŸ’° Transaction Management
386
+
387
+ The MySQL MCP Server provides full ACID transaction support, allowing you to group multiple database operations into atomic units.
388
+
389
+ ### Transaction Tools Overview
390
+
391
+ - **`begin_transaction`** - Start a new transaction
392
+ - **`execute_in_transaction`** - Execute SQL within transaction context
393
+ - **`commit_transaction`** - Permanently save all changes
394
+ - **`rollback_transaction`** - Discard all changes since transaction start
395
+ - **`get_transaction_status`** - Check if transaction is active
396
+
397
+ ### Transaction Example: Money Transfer
398
+
399
+ **User:** *"Transfer $100 from Alice's account to Bob's account"*
400
+
401
+ **AI executes:**
402
+ ```json
403
+ // Step 1: Begin transaction
404
+ {
405
+ "tool": "begin_transaction"
406
+ }
407
+
408
+ // Step 2: Deduct from Alice's account
409
+ {
410
+ "tool": "execute_in_transaction",
411
+ "arguments": {
412
+ "sql": "UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice'"
413
+ }
414
+ }
415
+
416
+ // Step 3: Add to Bob's account
417
+ {
418
+ "tool": "execute_in_transaction",
419
+ "arguments": {
420
+ "sql": "UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob'"
421
+ }
422
+ }
423
+
424
+ // Step 4: Verify both accounts exist and have sufficient funds
425
+ {
426
+ "tool": "execute_in_transaction",
427
+ "arguments": {
428
+ "sql": "SELECT * FROM accounts WHERE name IN ('Alice', 'Bob')"
429
+ }
430
+ }
431
+
432
+ // Step 5: Commit if everything is valid
433
+ {
434
+ "tool": "commit_transaction"
435
+ }
436
+ ```
437
+
438
+ ### Transaction Safety Features
439
+
440
+ 1. βœ… **Atomic Operations** - All operations succeed or all fail together
441
+ 2. βœ… **Automatic Rollback** - If any operation fails, transaction automatically rolls back
442
+ 3. βœ… **Isolation** - Other sessions see changes only after commit
443
+ 4. βœ… **Status Checking** - Always know if a transaction is active
444
+ 5. βœ… **Error Handling** - Comprehensive error reporting for failed operations
445
+
446
+ ### Transaction Best Practices
447
+
448
+ 1. **Keep transactions short** - Long transactions can block other operations
449
+ 2. **Always commit or rollback** - Don't leave transactions hanging
450
+ 3. **Test transaction logic** - Verify your transaction sequence works correctly
451
+ 4. **Handle errors gracefully** - Check for errors after each operation
452
+ 5. **Use appropriate isolation levels** - Understand your consistency requirements
453
+
454
+ ### Common Transaction Patterns
455
+
456
+ **Pattern 1: Safe Update with Verification**
457
+ ```json
458
+ // Begin transaction
459
+ // Update records
460
+ // Verify changes with SELECT
461
+ // Commit if valid, rollback if not
462
+ ```
463
+
464
+ **Pattern 2: Batch Operations**
465
+ ```json
466
+ // Begin transaction
467
+ // Insert multiple related records
468
+ // Update related tables
469
+ // Commit all changes together
470
+ ```
471
+
472
+ **Pattern 3: Error Recovery**
473
+ ```json
474
+ // Begin transaction
475
+ // Try operations
476
+ // If error occurs: rollback
477
+ // If success: commit
478
+ ```
479
+
480
+ ---
481
+
482
+ ## πŸ”§ Stored Procedures
483
+
484
+ The MySQL MCP Server provides comprehensive stored procedure management, allowing you to create, execute, and manage stored procedures with full parameter support.
485
+
486
+ ### Stored Procedure Tools Overview
487
+
488
+ - **`list_stored_procedures`** - List all stored procedures in a database
489
+ - **`create_stored_procedure`** - Create new stored procedures with IN/OUT/INOUT parameters
490
+ - **`get_stored_procedure_info`** - Get detailed information about parameters and metadata
491
+ - **`execute_stored_procedure`** - Execute procedures with automatic parameter handling
492
+ - **`drop_stored_procedure`** - Delete stored procedures safely
493
+
494
+ ### ⚠️ Enable Stored Procedures
495
+
496
+ Stored procedure operations require the `procedure` permission. Add it to your configuration:
497
+
498
+ ```json
499
+ {
500
+ "args": [
501
+ "mysql://user:pass@localhost:3306/db",
502
+ "list,read,procedure,utility" // ← Include 'procedure'
503
+ ]
504
+ }
505
+ ```
506
+
507
+ ### Creating Stored Procedures
508
+
509
+ **User:** *"Create a stored procedure that calculates tax for a given amount"*
510
+
511
+ **AI will execute:**
512
+ ```json
513
+ {
514
+ "tool": "create_stored_procedure",
515
+ "arguments": {
516
+ "procedure_name": "calculate_tax",
517
+ "parameters": [
518
+ {
519
+ "name": "amount",
520
+ "mode": "IN",
521
+ "data_type": "DECIMAL(10,2)"
522
+ },
523
+ {
524
+ "name": "tax_rate",
525
+ "mode": "IN",
526
+ "data_type": "DECIMAL(5,4)"
527
+ },
528
+ {
529
+ "name": "tax_amount",
530
+ "mode": "OUT",
531
+ "data_type": "DECIMAL(10,2)"
532
+ }
533
+ ],
534
+ "body": "SET tax_amount = amount * tax_rate;",
535
+ "comment": "Calculate tax amount based on amount and tax rate"
536
+ }
537
+ }
538
+ ```
539
+
540
+ ### Executing Stored Procedures
541
+
542
+ **User:** *"Calculate tax for $1000 with 8.5% tax rate"*
543
+
544
+ **AI will execute:**
545
+ ```json
546
+ {
547
+ "tool": "execute_stored_procedure",
548
+ "arguments": {
549
+ "procedure_name": "calculate_tax",
550
+ "parameters": [1000.00, 0.085]
551
+ }
552
+ }
553
+ ```
554
+
555
+ **Result:**
556
+ ```json
557
+ {
558
+ "status": "success",
559
+ "data": {
560
+ "results": { /* execution results */ },
561
+ "outputParameters": {
562
+ "tax_amount": 85.00
563
+ }
564
+ }
565
+ }
566
+ ```
567
+
568
+ ### Parameter Types
569
+
570
+ **IN Parameters** - Input values passed to the procedure
571
+ ```sql
572
+ IN user_id INT
573
+ IN email VARCHAR(255)
574
+ ```
575
+
576
+ **OUT Parameters** - Output values returned by the procedure
577
+ ```sql
578
+ OUT total_count INT
579
+ OUT average_score DECIMAL(5,2)
580
+ ```
581
+
582
+ **INOUT Parameters** - Values that are both input and output
583
+ ```sql
584
+ INOUT running_total DECIMAL(10,2)
585
+ ```
586
+
587
+ ### Complex Stored Procedure Example
588
+
589
+ **User:** *"Create a procedure to process an order with inventory check"*
590
+
591
+ ```json
592
+ {
593
+ "tool": "create_stored_procedure",
594
+ "arguments": {
595
+ "procedure_name": "process_order",
596
+ "parameters": [
597
+ { "name": "product_id", "mode": "IN", "data_type": "INT" },
598
+ { "name": "quantity", "mode": "IN", "data_type": "INT" },
599
+ { "name": "customer_id", "mode": "IN", "data_type": "INT" },
600
+ { "name": "order_id", "mode": "OUT", "data_type": "INT" },
601
+ { "name": "success", "mode": "OUT", "data_type": "BOOLEAN" }
602
+ ],
603
+ "body": "DECLARE available_qty INT; SELECT stock_quantity INTO available_qty FROM products WHERE id = product_id; IF available_qty >= quantity THEN INSERT INTO orders (customer_id, product_id, quantity) VALUES (customer_id, product_id, quantity); SET order_id = LAST_INSERT_ID(); UPDATE products SET stock_quantity = stock_quantity - quantity WHERE id = product_id; SET success = TRUE; ELSE SET order_id = 0; SET success = FALSE; END IF;",
604
+ "comment": "Process order with inventory validation"
605
+ }
606
+ }
607
+ ```
608
+
609
+ ### Getting Procedure Information
610
+
611
+ **User:** *"Show me details about the calculate_tax procedure"*
612
+
613
+ **AI will execute:**
614
+ ```json
615
+ {
616
+ "tool": "get_stored_procedure_info",
617
+ "arguments": {
618
+ "procedure_name": "calculate_tax"
619
+ }
620
+ }
621
+ ```
622
+
623
+ **Returns detailed information:**
624
+ - Procedure metadata (created date, security type, etc.)
625
+ - Parameter details (names, types, modes)
626
+ - Procedure definition
627
+ - Comments and documentation
628
+
629
+ ### Stored Procedure Best Practices
630
+
631
+ 1. βœ… **Use descriptive names** - Make procedure purposes clear
632
+ 2. βœ… **Document with comments** - Add meaningful comments to procedures
633
+ 3. βœ… **Validate inputs** - Check parameter values within procedures
634
+ 4. βœ… **Handle errors** - Use proper error handling in procedure bodies
635
+ 5. βœ… **Test thoroughly** - Verify procedures work with various inputs
636
+ 6. βœ… **Use appropriate data types** - Choose correct types for parameters
637
+ 7. βœ… **Consider security** - Be mindful of SQL injection in dynamic SQL
638
+
639
+ ### Common Stored Procedure Patterns
640
+
641
+ **Pattern 1: Data Validation and Processing**
642
+ ```sql
643
+ -- Validate input, process if valid, return status
644
+ IF input_value > 0 THEN
645
+ -- Process data
646
+ SET success = TRUE;
647
+ ELSE
648
+ SET success = FALSE;
649
+ END IF;
650
+ ```
651
+
652
+ **Pattern 2: Complex Business Logic**
653
+ ```sql
654
+ -- Multi-step business process
655
+ -- Step 1: Validate
656
+ -- Step 2: Calculate
657
+ -- Step 3: Update multiple tables
658
+ -- Step 4: Return results
659
+ ```
660
+
661
+ **Pattern 3: Reporting and Analytics**
662
+ ```sql
663
+ -- Aggregate data from multiple tables
664
+ -- Apply business rules
665
+ -- Return calculated results
666
+ ```
667
+
668
+ ---
669
+
670
+ ## πŸ“‹ Usage Examples
671
+
672
+ ### Example 1: Read Data
673
+
674
+ **User:** *"Show me the first 10 users ordered by created_at"*
675
+
676
+ **AI uses `read_records`:**
677
+ - Queries the users table
678
+ - Applies pagination (limit 10)
679
+ - Sorts by created_at descending
680
+ - Returns results
681
+
682
+ ### Example 2: Filter Data
683
+
684
+ **User:** *"Find all users with email ending in @example.com"*
685
+
686
+ **AI uses `read_records` with filters:**
687
+ - Applies LIKE filter on email column
688
+ - Returns matching records
689
+
690
+ ### Example 3: Create Records
691
+
692
+ **User:** *"Add a new user with username 'john_doe' and email 'john@example.com'"*
693
+
694
+ **AI uses `create_record`:**
695
+ - Inserts new record
696
+ - Returns insert ID
697
+
698
+ ### Example 4: Update Records
699
+
700
+ **User:** *"Update the email for user ID 5 to 'newemail@example.com'"*
701
+
702
+ **AI uses `update_record`:**
703
+ - Updates specific record by ID
704
+ - Returns affected rows
705
+
706
+ ### Example 5: Complex Query
707
+
708
+ **User:** *"Show me the total number of orders per user for the last 30 days"*
709
+
710
+ **AI uses `run_query`:**
711
+ - Constructs JOIN query
712
+ - Applies date filter
713
+ - Groups by user
714
+ - Returns aggregated results
715
+
716
+ ### Example 6: Transaction Management
717
+
718
+ **User:** *"Transfer $100 from account 1 to account 2 in a single transaction"*
719
+
720
+ **AI uses transaction tools:**
721
+ ```json
722
+ {
723
+ "tool": "begin_transaction"
724
+ }
725
+
726
+ {
727
+ "tool": "execute_in_transaction",
728
+ "arguments": {
729
+ "sql": "UPDATE accounts SET balance = balance - 100 WHERE id = 1"
730
+ }
731
+ }
732
+
733
+ {
734
+ "tool": "execute_in_transaction",
735
+ "arguments": {
736
+ "sql": "UPDATE accounts SET balance = balance + 100 WHERE id = 2"
737
+ }
738
+ }
739
+
740
+ {
741
+ "tool": "commit_transaction"
742
+ }
743
+ ```
744
+
745
+ **User:** *"Check if there's an active transaction"*
746
+
747
+ **AI uses `get_transaction_status`:**
748
+ - Returns transaction status and ID if active
749
+
750
+ **User:** *"Rollback the current transaction"*
751
+
752
+ **AI uses `rollback_transaction`:**
753
+ - Cancels all changes in the current transaction
754
+
755
+ ---
756
+
757
+ ## βš™οΈ Configuration
758
+
759
+ ### Connection String Format
760
+
761
+ ```
762
+ mysql://username:password@host:port/database
763
+ ```
764
+
765
+ **Examples:**
766
+ ```
767
+ mysql://root:pass@localhost:3306/myapp
768
+ mysql://user:pass@192.168.1.100:3306/production
769
+ mysql://admin:pass@db.example.com:3306/analytics
770
+ ```
771
+
772
+ **Database name is optional:**
773
+ ```
774
+ mysql://user:pass@localhost:3306/
775
+ ```
776
+
777
+ When omitted, AI can switch between databases using SQL commands.
778
+
779
+ ### Environment Variables
780
+
781
+ Create `.env` file for local development:
782
+
783
+ ```env
784
+ # MySQL Connection
785
+ DB_HOST=localhost
786
+ DB_PORT=3306
787
+ DB_USER=root
788
+ DB_PASSWORD=yourpassword
789
+ DB_NAME=yourdatabase
790
+
791
+ # Default Permissions (optional, can be overridden per-project)
792
+ MCP_CONFIG=list,read,utility
793
+
794
+ # REST API Mode (optional)
795
+ PORT=3000
796
+ JWT_SECRET=your_jwt_secret
797
+ NODE_ENV=development
798
+ ```
799
+
800
+ ---
801
+
802
+ ## πŸ”’ Security Features
803
+
804
+ ### Built-in Security
805
+
806
+ - βœ… **Parameterized Queries** - All queries use prepared statements (SQL injection protection)
807
+ - βœ… **Permission-Based Access** - Fine-grained control over operations
808
+ - βœ… **Read-Only Validation** - `run_query` enforces SELECT-only operations
809
+ - βœ… **DDL Gating** - Schema changes require explicit `ddl` permission
810
+ - βœ… **Condition Requirements** - DELETE operations must include WHERE conditions
811
+ - βœ… **Input Validation** - All inputs validated with JSON schemas
812
+ - βœ… **Connection Pooling** - Efficient database connection management
813
+
814
+ ### Additional Security (REST API Mode)
815
+
816
+ - βœ… **JWT Authentication** - Token-based authentication
817
+ - βœ… **Rate Limiting** - 100 requests per 15 minutes per IP
818
+ - βœ… **CORS Protection** - Configurable CORS policies
819
+ - βœ… **Helmet Security Headers** - HTTP security headers
820
+
821
+ ### Security Best Practices
822
+
823
+ 1. **Use Read-Only for Production**
824
+ ```
825
+ "list,read,utility"
826
+ ```
827
+
828
+ 2. **Create MySQL Users with Limited Permissions**
829
+ ```sql
830
+ CREATE USER 'readonly'@'%' IDENTIFIED BY 'password';
831
+ GRANT SELECT ON myapp.* TO 'readonly'@'%';
832
+ FLUSH PRIVILEGES;
833
+ ```
834
+
835
+ 3. **Never Use Root in Production**
836
+ - Create dedicated users per environment
837
+ - Grant minimal necessary permissions
838
+
839
+ 4. **Never Commit `.env` Files**
840
+ - Add `.env` to `.gitignore`
841
+ - Use environment-specific configs
842
+
843
+ 5. **Enable DDL Only When Needed**
844
+ - Keep DDL disabled by default
845
+ - Only enable for schema migration tasks
846
+
847
+ ---
848
+
849
+ ## 🌐 REST API Mode
850
+
851
+ In addition to MCP protocol, this server can run as a REST API.
852
+
853
+ ### Start API Server
854
+
855
+ ```bash
856
+ npm run start:api
857
+ ```
858
+
859
+ Server runs on `http://localhost:3000` (or configured PORT).
860
+
861
+ ### API Endpoints
862
+
863
+ All endpoints require JWT authentication (except `/health`).
864
+
865
+ **Health Check:**
866
+ ```
867
+ GET /health
868
+ ```
869
+
870
+ **Database Operations:**
871
+ ```
872
+ GET /api/databases # List databases
873
+ GET /api/tables # List tables
874
+ GET /api/tables/:name/schema # Get table schema
875
+ GET /api/tables/:name/records # Read records
876
+ POST /api/tables/:name/records # Create record
877
+ PUT /api/tables/:name/records/:id # Update record
878
+ DELETE /api/tables/:name/records/:id # Delete record
879
+ ```
880
+
881
+ **Query Operations:**
882
+ ```
883
+ POST /api/query # Execute SELECT query
884
+ POST /api/execute # Execute write query
885
+ ```
886
+
887
+ **Utilities:**
888
+ ```
889
+ GET /api/connection # Connection info
890
+ GET /api/connection/test # Test connection
891
+ GET /api/tables/:name/relationships # Get foreign keys
892
+ ```
893
+
894
+ ### Authentication
895
+
896
+ Include JWT token in Authorization header:
897
+
898
+ ```bash
899
+ curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
900
+ http://localhost:3000/api/tables
901
+ ```
902
+
903
+ ---
904
+
905
+ ## πŸ§ͺ Testing
906
+
907
+ ### Test MCP Server Locally
908
+
909
+ ```bash
910
+ # Test connection
911
+ node bin/mcp-mysql.js mysql://user:pass@localhost:3306/test "list,read,utility"
912
+ ```
913
+
914
+ ### Test with Claude Desktop
915
+
916
+ 1. Configure `claude_desktop_config.json`
917
+ 2. Restart Claude Desktop
918
+ 3. Ask: *"What databases are available?"*
919
+
920
+ ### Test REST API
921
+
922
+ ```bash
923
+ # Start API server
924
+ npm run start:api
925
+
926
+ # Test health endpoint
927
+ curl http://localhost:3000/health
928
+ ```
929
+
930
+ ---
931
+
932
+ ## πŸš€ Publishing to npm
933
+
934
+ To make your MCP server available to the world:
935
+
936
+ ### 1. Update package.json
937
+
938
+ ```json
939
+ {
940
+ "name": "@your-username/mcp-mysql",
941
+ "author": "Your Name <your.email@example.com>",
942
+ "repository": {
943
+ "type": "git",
944
+ "url": "https://github.com/your-username/mcp-mysql.git"
945
+ }
946
+ }
947
+ ```
948
+
949
+ ### 2. Build
950
+
951
+ ```bash
952
+ npm run build
953
+ ```
954
+
955
+ ### 3. Publish
956
+
957
+ ```bash
958
+ # Login to npm
959
+ npm login
960
+
961
+ # Publish (for scoped packages)
962
+ npm publish --access public
963
+ ```
964
+
965
+ ### 4. Users Can Install
966
+
967
+ ```bash
968
+ npx @your-username/mcp-mysql mysql://user:pass@localhost:3306/db "list,read,utility"
969
+ ```
970
+
971
+ ---
972
+
973
+ ## πŸ› Troubleshooting
974
+
975
+ ### MCP Server Not Connecting
976
+
977
+ **Problem:** AI agent doesn't see tools
978
+
979
+ **Solutions:**
980
+ 1. Check config file path is correct
981
+ 2. Restart AI agent completely
982
+ 3. Verify bin/mcp-mysql.js exists
983
+ 4. Check for JSON syntax errors
984
+
985
+ **Problem:** Connection fails
986
+
987
+ **Solutions:**
988
+ 1. Test MySQL manually: `mysql -u root -p`
989
+ 2. Verify credentials in connection string
990
+ 3. Check MySQL is running
991
+ 4. Verify network access (host/port)
992
+
993
+ ### Permission Issues
994
+
995
+ **Problem:** "Tool is disabled" error
996
+
997
+ **Solutions:**
998
+ 1. Check permissions in third argument
999
+ 2. Verify permission spelling
1000
+ 3. Add required permission category
1001
+
1002
+ **Problem:** MySQL permission denied
1003
+
1004
+ **Solutions:**
1005
+ ```sql
1006
+ GRANT SELECT, INSERT, UPDATE, DELETE ON db.* TO 'user'@'localhost';
1007
+ FLUSH PRIVILEGES;
1008
+ ```
1009
+
1010
+ ### DDL Operations Not Working
1011
+
1012
+ **Problem:** "DDL operations require 'ddl' permission"
1013
+
1014
+ **Solution:** Add `ddl` to permissions:
1015
+ ```json
1016
+ {
1017
+ "args": [
1018
+ "mysql://...",
1019
+ "list,read,create,update,delete,ddl,utility"
1020
+ ]
1021
+ }
1022
+ ```
1023
+
1024
+ ---
1025
+
1026
+ ## πŸ“š Development
1027
+
1028
+ ### Project Structure
1029
+
1030
+ ```
1031
+ mcp_mysql/
1032
+ β”œβ”€β”€ src/
1033
+ β”‚ β”œβ”€β”€ config/ # Configuration and permissions
1034
+ β”‚ β”œβ”€β”€ db/ # Database connection
1035
+ β”‚ β”œβ”€β”€ security/ # Security layer
1036
+ β”‚ β”œβ”€β”€ tools/ # Tool implementations
1037
+ β”‚ β”‚ β”œβ”€β”€ databaseTools.ts # Database discovery
1038
+ β”‚ β”‚ β”œβ”€β”€ crudTools.ts # CRUD operations
1039
+ β”‚ β”‚ β”œβ”€β”€ queryTools.ts # Query execution
1040
+ β”‚ β”‚ β”œβ”€β”€ ddlTools.ts # DDL operations
1041
+ β”‚ β”‚ └── utilityTools.ts # Utilities
1042
+ β”‚ β”œβ”€β”€ validation/ # Input validation schemas
1043
+ β”‚ β”œβ”€β”€ index.ts # MySQLMCP class
1044
+ β”‚ β”œβ”€β”€ mcp-server.ts # MCP protocol server
1045
+ β”‚ └── server.ts # REST API server
1046
+ β”œβ”€β”€ bin/
1047
+ β”‚ └── mcp-mysql.js # CLI entry point
1048
+ β”œβ”€β”€ dist/ # Compiled JavaScript
1049
+ β”œβ”€β”€ .env # Local environment config
1050
+ β”œβ”€β”€ package.json
1051
+ β”œβ”€β”€ tsconfig.json
1052
+ └── README.md
1053
+ ```
1054
+
1055
+ ### Development Commands
1056
+
1057
+ ```bash
1058
+ # Install dependencies
1059
+ npm install
1060
+
1061
+ # Build TypeScript
1062
+ npm run build
1063
+
1064
+ # Run in development mode (MCP)
1065
+ npm run dev:mcp
1066
+
1067
+ # Run in development mode (API)
1068
+ npm run dev:api
1069
+
1070
+ # Run tests
1071
+ npm test
1072
+ ```
1073
+
1074
+ ---
1075
+
1076
+ ## 🀝 Contributing
1077
+
1078
+ Contributions are welcome!
1079
+
1080
+ 1. Fork the repository
1081
+ 2. Create a feature branch: `git checkout -b feature/my-feature`
1082
+ 3. Make your changes
1083
+ 4. Build and test: `npm run build`
1084
+ 5. Commit: `git commit -m "Add my feature"`
1085
+ 6. Push: `git push origin feature/my-feature`
1086
+ 7. Submit a pull request
1087
+
1088
+ ---
1089
+
1090
+ ## πŸ“„ License
1091
+
1092
+ MIT License - see [LICENSE](LICENSE) file for details.
1093
+
1094
+ ---
1095
+
1096
+ ## πŸ™ Acknowledgments
1097
+
1098
+ - Built with [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk)
1099
+ - Compatible with [Claude Desktop](https://claude.ai/), [Cline](https://github.com/cline/cline), [Windsurf](https://codeium.com/windsurf), and other MCP-compatible tools
1100
+ - Inspired by the Model Context Protocol specification
1101
+
1102
+ ---
1103
+
1104
+ ## πŸ’¬ Support
1105
+
1106
+ - **Issues:** [GitHub Issues](https://github.com/your-username/mcp-mysql/issues)
1107
+ - **Discussions:** [GitHub Discussions](https://github.com/your-username/mcp-mysql/discussions)
1108
+ - **Documentation:** This README
1109
+
1110
+ ---
1111
+
1112
+ ## πŸ—ΊοΈ Roadmap
1113
+
1114
+ ### Core Features
1115
+ - βœ… **Transaction support (BEGIN, COMMIT, ROLLBACK)** - **COMPLETED!**
1116
+ - βœ… **Stored procedure execution** - **COMPLETED!**
1117
+ - [ ] Bulk operations (batch insert/update/delete)
1118
+ - [ ] Query result caching
1119
+ - [ ] Advanced query optimization hints
1120
+
1121
+ ### Enterprise Features
1122
+ - [ ] **Database backup and restore tools**
1123
+ - [ ] **Data export/import utilities** (CSV, JSON, SQL dumps)
1124
+ - [ ] **Performance monitoring and metrics**
1125
+ - [ ] **Query performance analysis**
1126
+ - [ ] **Connection pool monitoring**
1127
+ - [ ] **Audit logging and compliance**
1128
+ - [ ] **Data migration utilities**
1129
+ - [ ] **Schema versioning and migrations**
1130
+
1131
+ ### Database Adapters
1132
+ - [ ] PostgreSQL adapter
1133
+ - [ ] MongoDB adapter
1134
+ - [ ] SQLite adapter
1135
+ - [ ] Oracle Database adapter
1136
+ - [ ] SQL Server adapter
1137
+
1138
+ ---
1139
+
1140
+ **Made with ❀️ for the AI community**
1141
+
1142
+ *Help AI agents interact with MySQL databases safely and efficiently!*