-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmysql_mcp_server.py
More file actions
executable file
·442 lines (378 loc) · 15.2 KB
/
mysql_mcp_server.py
File metadata and controls
executable file
·442 lines (378 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#!/usr/bin/env python3
"""
MySQL MCP Server
Provides database operations for Cursor IDE through MCP protocol
"""
import json
import sys
import os
import traceback
from typing import Dict, List, Any, Optional
import mysql.connector
from mysql.connector import Error
# Database configuration from environment variables
DB_CONFIG = {
'host': os.getenv('MYSQL_HOST', 'localhost'),
'port': int(os.getenv('MYSQL_PORT', '3306')),
'database': os.getenv('MYSQL_DATABASE', 'test'),
'user': os.getenv('MYSQL_USER', 'root'),
'password': os.getenv('MYSQL_PASSWORD', ''),
'charset': os.getenv('MYSQL_CHARSET', 'utf8mb4'),
'autocommit': True,
'connection_timeout': int(os.getenv('MYSQL_CONNECTION_TIMEOUT', '10'))
}
class MySQLMCPServer:
def __init__(self):
self.connection = None
# Validate required environment variables
required_vars = ['MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE']
missing_vars = [var for var in required_vars if not os.getenv(var)]
if missing_vars:
raise ValueError(f"Missing required environment variables: {', '.join(missing_vars)}")
self.tools = [
{
"name": "query_database",
"description": "Execute SELECT queries to retrieve data from database",
"inputSchema": {
"type": "object",
"properties": {
"sql": {
"type": "string",
"description": "SQL SELECT query to execute"
},
"limit": {
"type": "integer",
"description": "Maximum number of rows to return (default: 100)",
"default": 100
}
},
"required": ["sql"]
}
},
{
"name": "execute_sql",
"description": "Execute INSERT, UPDATE, DELETE statements",
"inputSchema": {
"type": "object",
"properties": {
"sql": {
"type": "string",
"description": "SQL statement to execute (INSERT, UPDATE, DELETE)"
}
},
"required": ["sql"]
}
},
{
"name": "create_table",
"description": "Create a new table in the database",
"inputSchema": {
"type": "object",
"properties": {
"table_name": {
"type": "string",
"description": "Name of the table to create"
},
"columns": {
"type": "string",
"description": "Column definitions (e.g., 'id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100), email VARCHAR(255)')"
}
},
"required": ["table_name", "columns"]
}
},
{
"name": "add_column",
"description": "Add a new column to an existing table",
"inputSchema": {
"type": "object",
"properties": {
"table_name": {
"type": "string",
"description": "Name of the table to modify"
},
"column_definition": {
"type": "string",
"description": "Column definition (e.g., 'age INT DEFAULT 0', 'created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP')"
}
},
"required": ["table_name", "column_definition"]
}
},
{
"name": "show_tables",
"description": "List all tables in the database",
"inputSchema": {
"type": "object",
"properties": {}
}
},
{
"name": "describe_table",
"description": "Show the structure of a table (columns, types, etc.)",
"inputSchema": {
"type": "object",
"properties": {
"table_name": {
"type": "string",
"description": "Name of the table to describe"
}
},
"required": ["table_name"]
}
},
{
"name": "show_databases",
"description": "List all available databases",
"inputSchema": {
"type": "object",
"properties": {}
}
}
]
def get_connection(self):
"""Get or create database connection"""
try:
if self.connection is None or not self.connection.is_connected():
self.connection = mysql.connector.connect(**DB_CONFIG)
return self.connection
except Error as e:
raise Exception(f"Database connection failed: {e}")
def close_connection(self):
"""Close database connection"""
if self.connection and self.connection.is_connected():
self.connection.close()
def handle_initialize(self, request: Dict) -> Dict:
"""Handle initialize request"""
return {
"jsonrpc": "2.0",
"id": request["id"],
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": {}
},
"serverInfo": {
"name": "mysql-mcp-server",
"version": "1.0.0"
}
}
}
def handle_tools_list(self, request: Dict) -> Dict:
"""Handle tools/list request"""
return {
"jsonrpc": "2.0",
"id": request["id"],
"result": {
"tools": self.tools
}
}
def handle_tools_call(self, request: Dict) -> Dict:
"""Handle tools/call request"""
try:
tool_name = request["params"]["name"]
arguments = request["params"].get("arguments", {})
if tool_name == "query_database":
result = self.query_database(arguments)
elif tool_name == "execute_sql":
result = self.execute_sql(arguments)
elif tool_name == "create_table":
result = self.create_table(arguments)
elif tool_name == "add_column":
result = self.add_column(arguments)
elif tool_name == "show_tables":
result = self.show_tables(arguments)
elif tool_name == "describe_table":
result = self.describe_table(arguments)
elif tool_name == "show_databases":
result = self.show_databases(arguments)
else:
raise ValueError(f"Unknown tool: {tool_name}")
return {
"jsonrpc": "2.0",
"id": request["id"],
"result": {
"content": [
{
"type": "text",
"text": result
}
]
}
}
except Exception as e:
error_msg = f"Error executing {tool_name}: {str(e)}"
return {
"jsonrpc": "2.0",
"id": request["id"],
"error": {
"code": -32000,
"message": error_msg
}
}
def query_database(self, args: Dict) -> str:
"""Execute SELECT query"""
sql = args["sql"].strip()
limit = args.get("limit", 100)
if not sql.upper().startswith("SELECT"):
raise ValueError("Only SELECT queries are allowed for query_database")
# Add LIMIT if not present
if "LIMIT" not in sql.upper():
sql += f" LIMIT {limit}"
conn = self.get_connection()
cursor = conn.cursor(dictionary=True)
try:
cursor.execute(sql)
results = cursor.fetchall()
if not results:
return "Query executed successfully. No rows returned."
# Format results as table
output = f"Query: {sql}\n"
output += f"Rows returned: {len(results)}\n\n"
# Table headers
headers = list(results[0].keys())
output += "| " + " | ".join(headers) + " |\n"
output += "|" + "|".join(["-" * (len(h) + 2) for h in headers]) + "|\n"
# Table rows
for row in results:
values = [str(row[h]) if row[h] is not None else "NULL" for h in headers]
output += "| " + " | ".join(values) + " |\n"
return output
finally:
cursor.close()
def execute_sql(self, args: Dict) -> str:
"""Execute INSERT, UPDATE, DELETE statements"""
sql = args["sql"].strip()
# Security check - only allow specific statements
sql_upper = sql.upper()
allowed_statements = ["INSERT", "UPDATE", "DELETE"]
if not any(sql_upper.startswith(stmt) for stmt in allowed_statements):
raise ValueError("Only INSERT, UPDATE, DELETE statements are allowed")
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(sql)
conn.commit()
affected_rows = cursor.rowcount
return f"SQL executed successfully. Affected rows: {affected_rows}\nSQL: {sql}"
finally:
cursor.close()
def create_table(self, args: Dict) -> str:
"""Create a new table"""
table_name = args["table_name"]
columns = args["columns"]
sql = f"CREATE TABLE {table_name} ({columns})"
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(sql)
conn.commit()
return f"Table '{table_name}' created successfully.\nSQL: {sql}"
finally:
cursor.close()
def add_column(self, args: Dict) -> str:
"""Add column to existing table"""
table_name = args["table_name"]
column_definition = args["column_definition"]
sql = f"ALTER TABLE {table_name} ADD COLUMN {column_definition}"
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(sql)
conn.commit()
return f"Column added to table '{table_name}' successfully.\nSQL: {sql}"
finally:
cursor.close()
def show_tables(self, args: Dict) -> str:
"""List all tables"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
if not tables:
return "No tables found in the database."
output = "Tables in database:\n"
for i, (table,) in enumerate(tables, 1):
output += f"{i}. {table}\n"
return output
finally:
cursor.close()
def describe_table(self, args: Dict) -> str:
"""Describe table structure"""
table_name = args["table_name"]
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute(f"DESCRIBE {table_name}")
columns = cursor.fetchall()
if not columns:
return f"Table '{table_name}' not found or has no columns."
output = f"Structure of table '{table_name}':\n\n"
output += "| Field | Type | Null | Key | Default | Extra |\n"
output += "|-------|------|------|-----|---------|-------|\n"
for col in columns:
field, type_, null, key, default, extra = col
default_str = str(default) if default is not None else "NULL"
output += f"| {field} | {type_} | {null} | {key} | {default_str} | {extra} |\n"
return output
finally:
cursor.close()
def show_databases(self, args: Dict) -> str:
"""List all databases"""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute("SHOW DATABASES")
databases = cursor.fetchall()
output = "Available databases:\n"
for i, (db,) in enumerate(databases, 1):
current = " (current)" if db == DB_CONFIG['database'] else ""
output += f"{i}. {db}{current}\n"
return output
finally:
cursor.close()
def run(self):
"""Main server loop"""
try:
for line in sys.stdin:
try:
request = json.loads(line.strip())
if request["method"] == "initialize":
response = self.handle_initialize(request)
elif request["method"] == "tools/list":
response = self.handle_tools_list(request)
elif request["method"] == "tools/call":
response = self.handle_tools_call(request)
else:
response = {
"jsonrpc": "2.0",
"id": request["id"],
"error": {
"code": -32601,
"message": f"Method not found: {request['method']}"
}
}
print(json.dumps(response))
sys.stdout.flush()
except json.JSONDecodeError:
# Ignore invalid JSON
continue
except Exception as e:
error_response = {
"jsonrpc": "2.0",
"id": request.get("id", None),
"error": {
"code": -32000,
"message": f"Internal error: {str(e)}"
}
}
print(json.dumps(error_response))
sys.stdout.flush()
except KeyboardInterrupt:
pass
finally:
self.close_connection()
if __name__ == "__main__":
server = MySQLMCPServer()
server.run()