-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmysql_server.py
More file actions
8553 lines (7342 loc) · 273 KB
/
Copy pathmysql_server.py
File metadata and controls
8553 lines (7342 loc) · 273 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MCP MySQL Server
A Model Context Protocol server that provides MySQL database access.
Allows LLMs to query databases, inspect schemas, and execute SQL commands.
"""
import asyncio
import json
import logging
import re
from contextlib import asynccontextmanager
from typing import Any, Dict, List, Optional, AsyncIterator, Union
from dataclasses import dataclass
try:
import mysql.connector
from mysql.connector import Error as MySQLError
except ImportError:
print("mysql-connector-python is required. Install with: pip install mysql-connector-python")
exit(1)
try:
from mcp.server.fastmcp import FastMCP, Context
except ImportError:
print("MCP SDK is required. Install with: pip install 'mcp[cli]'")
exit(1)
@dataclass
class DatabaseConfig:
"""Database configuration."""
host: str = "localhost"
port: int = 3306
user: str = "root"
password: str = ""
database: str = ""
class MySQLConnection:
"""MySQL database connection manager."""
def __init__(self, config: DatabaseConfig):
self.config = config
self.connection = None
# Read-only query patterns for security
self.read_only_patterns = [
r'^\s*SELECT\s+',
r'^\s*SHOW\s+',
r'^\s*DESCRIBE\s+',
r'^\s*DESC\s+',
r'^\s*EXPLAIN\s+',
r'^\s*WITH\s+.*SELECT\s+'
]
async def connect(self):
"""Connect to MySQL database."""
try:
self.connection = mysql.connector.connect(
host=self.config.host,
port=self.config.port,
user=self.config.user,
password=self.config.password,
database=self.config.database,
autocommit=True
)
logging.info(f"Connected to MySQL database: {self.config.host}:{self.config.port}")
return self
except MySQLError as e:
logging.error(f"Failed to connect to MySQL: {e}")
raise
async def disconnect(self):
"""Disconnect from MySQL database."""
if self.connection and self.connection.is_connected():
self.connection.close()
logging.info("Disconnected from MySQL database")
def execute_query(self, query: str):
"""Execute a SQL query and return results."""
if not self.connection or not self.connection.is_connected():
raise RuntimeError("Not connected to database")
cursor = self.connection.cursor(dictionary=True)
try:
cursor.execute(query)
if cursor.description: # SELECT query
results = cursor.fetchall()
return results
else: # INSERT, UPDATE, DELETE, etc.
affected_rows = cursor.rowcount
return [{"affected_rows": affected_rows, "message": "Query executed successfully"}]
finally:
cursor.close()
def get_tables(self):
"""Get list of tables in the database."""
query = "SHOW TABLES"
results = self.execute_query(query)
return [{"table_name": list(row.values())[0]} for row in results]
def get_table_schema(self, table_name: str):
"""Get schema information for a specific table."""
query = f"DESCRIBE `{table_name}`"
return self.execute_query(query)
def get_databases(self):
"""Get list of all databases."""
query = "SHOW DATABASES"
results = self.execute_query(query)
return [{"database_name": list(row.values())[0]} for row in results]
def is_read_only_query(self, query: str) -> bool:
"""Check if a query is read-only using regex patterns."""
query_upper = query.upper().strip()
return any(re.match(pattern, query_upper, re.IGNORECASE) for pattern in self.read_only_patterns)
def quote_identifier(self, identifier: str) -> str:
"""Quote a MySQL identifier (table/column name) to prevent injection."""
return f"`{identifier.replace('`', '``')}`"
def validate_table_name(self, table_name: str) -> str:
"""Validate and sanitize table name to prevent injection."""
# Remove any dangerous characters and validate format
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', table_name):
raise ValueError(f"Invalid table name: {table_name}")
return table_name
def execute_prepared_query(self, query: str, params: Optional[List] = None):
"""Execute a prepared statement query with parameters."""
if not self.connection or not self.connection.is_connected():
raise RuntimeError("Not connected to database")
cursor = self.connection.cursor(dictionary=True)
try:
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
if cursor.description:
results = cursor.fetchall()
return results
else:
affected_rows = cursor.rowcount
return [{"affected_rows": affected_rows, "message": "Query executed successfully"}]
finally:
cursor.close()
# Add async context manager for MySQL connections
import os
@asynccontextmanager
async def get_mysql_connection():
config = DatabaseConfig(
host=os.getenv("MYSQL_HOST", "localhost"),
port=int(os.getenv("MYSQL_PORT", "3306")),
user=os.getenv("MYSQL_USER", "root"),
password=os.getenv("MYSQL_PASSWORD", ""),
database=os.getenv("MYSQL_DATABASE", "")
)
conn = MySQLConnection(config)
await conn.connect()
try:
yield conn
finally:
await conn.disconnect()
@asynccontextmanager
async def database_lifespan(server: FastMCP) -> AsyncIterator[Dict[str, Any]]:
"""Manage database connection lifecycle."""
try:
async with get_mysql_connection() as conn:
yield {"db": conn, "config": conn.config}
except Exception as e:
logging.warning(f"Database connection failed: {e}. Server will start without active connection.")
yield {"db": None, "config": None}
# Create FastMCP server with database lifespan management
mcp = FastMCP("MySQL MCP Server", lifespan=database_lifespan)
@mcp.tool()
def mysql_fragmentation_extensive_analysis(ctx: Context, database_name: Optional[str] = None):
"""Provide a detailed analysis and defragmentation recommendations for tables."""
try:
db = ctx.lifespan["db"]
if database_name:
query = """SELECT
table_name,
engine,
table_rows,
data_length,
index_length,
data_free,
ROUND(data_free / IFNULL(NULLIF((data_length + index_length), 0), 1) * 100, 2) AS fragmentation_pct
FROM information_schema.tables
WHERE table_schema = %s
AND data_free > 0
ORDER BY fragmentation_pct DESC"""
fragmentation_info = db.execute_prepared_query(query, [database_name])
else:
query = """SELECT
table_schema,
table_name,
engine,
table_rows,
data_length,
index_length,
data_free,
ROUND(data_free / IFNULL(NULLIF((data_length + index_length), 0), 1) * 100, 2) AS fragmentation_pct
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND data_free > 0
ORDER BY fragmentation_pct DESC"""
fragmentation_info = db.execute_query(query)
# Identify tables with high fragmentation
high_fragmentation = []
for table in fragmentation_info:
if table.get('fragmentation_pct', 0) > 10: # More than 10% fragmented
high_fragmentation.append({
"table_name": table['table_name'],
"fragmentation_pct": table['fragmentation_pct'],
"engine": table['engine'],
"recommendation": f"OPTIMIZE TABLE {table['table_name']}" if table['engine'] == 'MyISAM' else f"ALTER TABLE {table['table_name']} ENGINE=InnoDB"
})
return {
"success": True,
"fragmentation_analysis": fragmentation_info,
"high_fragmentation": high_fragmentation,
"total_tables": len(fragmentation_info),
"optimization_needed": len(high_fragmentation)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_index_optimization_suggestions(ctx: Context):
"""Suggest optimal indexing strategies and potential consolidations."""
try:
db = ctx.lifespan["db"]
query = """SELECT
table_name,
index_name,
seq_in_index,
column_name
FROM information_schema.statistics
WHERE table_schema = DATABASE()
ORDER BY table_name, index_name, seq_in_index"""
indexes = db.execute_query(query)
# Suggestion structure
suggestions = []
# Sample suggestion logic (needs enhancement for production)
for index in indexes:
suggestions.append({
"table_name": index['table_name'],
"index_name": index['index_name'],
"column_name": index['column_name'],
"suggestion": "Consider consolidating indexes where possible"
})
return {
"success": True,
"indexes": indexes,
"suggestions": suggestions,
"count": len(suggestions)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_historical_slow_query_analysis(ctx: Context, min_duration: Optional[float] = None):
"""Analyze and aggregate historical slow query patterns."""
try:
db = ctx.lifespan["db"]
min_time = min_duration if min_duration is not None else 1.0
query = """SELECT
sql_text,
COUNT(*) as execution_count,
AVG(timer_wait)/1000000000000 AS avg_exec_time_sec
FROM performance_schema.events_statements_history_long
WHERE timer_wait/1000000000000 > %s
GROUP BY sql_text
ORDER BY execution_count DESC"""
slow_queries = db.execute_prepared_query(query, [min_time])
return {
"success": True,
"slow_queries": slow_queries,
"count": len(slow_queries),
"min_duration": min_time
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_buffer_pool_cache_diagnostics(ctx: Context):
"""Detailed diagnostics for buffer pool and cache tuning."""
try:
db = ctx.lifespan["db"]
query = "SHOW ENGINE INNODB STATUS"
innodb_status = db.execute_query(query)
# Example of parsing the InnoDB status
diagnostics = {
"buffer_pool_pages": None,
"cache_hit_ratio": None
}
for line in innodb_status:
if "Buffer pool size" in line["Status"]:
diagnostics["buffer_pool_pages"] = line["Status"].split("=")[1].strip()
if "Buffer pool hit rate" in line["Status"]:
diagnostics["cache_hit_ratio"] = line["Status"].split("=")[1].strip()
return {
"success": True,
"innodb_status": diagnostics
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_advanced_deadlock_detection(ctx: Context):
"""Enhanced detection and reporting of deadlock issues."""
try:
db = ctx.lifespan["db"]
# Get enhanced deadlock information
query = "SHOW ENGINE INNODB STATUS"
status = db.execute_query(query)
# Example: Parsing deadlock information (simplified)
deadlock_info = {}
for line in status:
if "LATEST DETECTED DEADLOCK" in line["Status"]:
deadlock_info["latest_deadlock"] = line["Status"]
return {
"success": True,
"deadlock_info": deadlock_info
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_cross_database_fk_analysis(ctx: Context):
"""Analyze foreign key issues across databases."""
try:
db = ctx.lifespan["db"]
query = """SELECT * FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL"""
fk_issues = db.execute_query(query)
return {
"success": True,
"foreign_key_issues": fk_issues,
"count": len(fk_issues)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_statistical_anomaly_detection(ctx: Context):
"""Detect statistical anomalies in column distributions."""
try:
db = ctx.lifespan["db"]
query = "SELECT column_name, AVG(value), STDDEV(value) FROM some_table GROUP BY column_name"
anomalies = db.execute_query(query)
return {
"success": True,
"anomalies": anomalies,
"count": len(anomalies)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_audit_log_summary(ctx: Context):
"""Summarize and detect anomalies within audit logs."""
try:
db = ctx.lifespan["db"]
query = """SELECT * FROM mysql.audit_log WHERE event_name LIKE '%error%'"""
audit_log = db.execute_query(query)
return {
"success": True,
"audit_log_summary": audit_log,
"count": len(audit_log)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_replication_lag_monitoring(ctx: Context):
"""Monitor replication lag over a time series."""
try:
db = ctx.lifespan["db"]
query = "SHOW SLAVE STATUS"
slave_status = db.execute_query(query)
lag = None
if slave_status and "Seconds_Behind_Master" in slave_status[0]:
lag = slave_status[0]["Seconds_Behind_Master"]
return {
"success": True,
"replication_lag": lag
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_privileges_security_audit(ctx: Context):
"""Audit user privileges and recommend policy improvements."""
try:
db = ctx.lifespan["db"]
query = "SELECT user, host FROM mysql.user WHERE is_role = 'N' AND user != 'root'"
user_privileges = db.execute_query(query)
return {
"success": True,
"user_privileges": user_privileges,
"recommendations": "Consider revising user privileges"
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_real_time_query_perf_metrics(ctx: Context):
"""Provide real-time metrics on query performance and bottlenecks."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM performance_schema.events_waits_summary_by_instance"
performance_metrics = db.execute_query(query)
return {
"success": True,
"performance_metrics": performance_metrics,
"count": len(performance_metrics)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_adaptive_index_improvements(ctx: Context):
"""Suggest adaptive index improvements based on query patterns."""
try:
db = ctx.lifespan["db"]
query = "SHOW INDEX FROM information_schema.tables WHERE Seq_in_index > 1"
index_improvements = db.execute_query(query)
return {
"success": True,
"index_improvements": index_improvements,
"count": len(index_improvements)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_server_health_dashboard(ctx: Context):
"""Create a dashboard displaying server health metrics."""
try:
db = ctx.lifespan["db"]
query = "SELECT variable_name, value FROM performance_schema.global_status"
server_health = db.execute_query(query)
return {
"success": True,
"server_health": server_health,
"count": len(server_health)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_backup_health_check(ctx: Context):
"""Perform a health check of backup strategies and configurations."""
try:
db = ctx.lifespan["db"]
backup_status = "OK" # Placeholder for actual status-checking logic
return {
"success": True,
"backup_status": backup_status
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_partition_management_recommendations(ctx: Context):
"""Recommend partition management techniques."""
try:
db = ctx.lifespan["db"]
partition_advice = []
query = "SHOW TABLE STATUS WHERE Comment LIKE '%partitioned%'"
partitions = db.execute_query(query)
for partition in partitions:
partition_advice.append({
"table_name": partition['Name'],
"recommendation": "Consider altering partition strategy"
})
return {
"success": True,
"partition_advice": partition_advice,
"count": len(partition_advice)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_dynamic_configuration_tuning(ctx: Context):
"""Analyze and suggest dynamic configuration changes."""
try:
db = ctx.lifespan["db"]
config_tuning_recs = []
query = "SELECT * FROM performance_schema.global_variables"
global_vars = db.execute_query(query)
for var in global_vars:
config_tuning_recs.append({
"variable_name": var['Variable_name'],
"recommendation": "Review and possibly adjust value"
})
return {
"success": True,
"config_tuning_recs": config_tuning_recs,
"count": len(config_tuning_recs)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_innodb_metrics_analysis(ctx: Context):
"""Deep analysis of InnoDB metrics for performance tuning."""
try:
db = ctx.lifespan["db"]
query = "SHOW ENGINE INNODB STATUS"
innodb_metrics = db.execute_query(query)
return {
"success": True,
"innodb_metrics": innodb_metrics
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_multi_tenancy_performance_insights(ctx: Context):
"""Insights and recommendations for multi-tenant databases."""
try:
db = ctx.lifespan["db"]
tenant_stats = []
query = "SELECT table_schema, sum(table_rows) as tenant_rows FROM information_schema.tables GROUP BY table_schema"
tenant_data = db.execute_query(query)
for tenant in tenant_data:
tenant_stats.append({
"schema": tenant['table_schema'],
"rows": tenant['tenant_rows'],
"recommendation": "Optimize for tenant isolation"
})
return {
"success": True,
"tenant_stats": tenant_stats,
"count": len(tenant_stats)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_ssl_tls_configuration_audit(ctx: Context):
"""Audit and improve SSL/TLS security configurations."""
try:
db = ctx.lifespan["db"]
query = "SHOW STATUS LIKE 'Ssl_cipher'"
ssl_status = db.execute_query(query)
recommendations = []
if not ssl_status or not ssl_status[0].get('Value'):
recommendations.append({
"issue": "SSL/TLS not configured",
"recommendation": "Enable SSL/TLS for secure connections"
})
return {
"success": True,
"ssl_status": ssl_status,
"recommendations": recommendations
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
def mysql_auto_index_rebuild_scheduler(ctx: Context):
"""Automatically schedule index rebuilds based on usage patterns."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM performance_schema.events_waits_summary_by_instance WHERE event_name LIKE 'index/%'"
index_usage = db.execute_query(query)
rebuild_schedule = []
for usage in index_usage:
if usage.get('SUM_TIMER_WAIT') > 10000000: # Arbitrary threshold
rebuild_schedule.append({
"index_name": usage['OBJECT_NAME'],
"recommendation": "Schedule index rebuild"
})
return {
"success": True,
"rebuild_schedule": rebuild_schedule,
"count": len(rebuild_schedule)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"error_type": type(e).__name__
}
@mcp.tool()
async def mysql_user_statistics(ctx: Context):
"""Show detailed user statistics like query counts and connection duration."""
try:
db = ctx.lifespan["db"]
query = "SELECT USER, TOTAL_CONNECTIONS, CONCURRENT_CONNECTIONS, CONNECTED_TIME, BUSY_TIME, CPU_TIME, BYTES_RECEIVED, BYTES_SENT, SELECT_COMMANDS, UPDATE_COMMANDS, OTHER_COMMANDS FROM performance_schema.user_summary"
user_stats = db.execute_query(query)
return {
"success": True,
"user_stats": user_stats,
"count": len(user_stats)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_list_open_transactions(ctx: Context):
"""List current open transactions and their states."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM information_schema.innodb_trx"
transactions = db.execute_query(query)
return {
"success": True,
"transactions": transactions,
"count": len(transactions)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_lock_wait_status(ctx: Context):
"""Display status of locks and waits in the database."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM information_schema.innodb_locks"
locks = db.execute_query(query)
return {
"success": True,
"locks": locks,
"count": len(locks)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_fragmentation_analysis(ctx: Context):
"""Show table and index fragmentation analysis."""
try:
db = ctx.lifespan["db"]
query = "SHOW TABLE STATUS"
fragmentation = db.execute_query(query)
return {
"success": True,
"fragmentation": fragmentation,
"count": len(fragmentation)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_index_usage_statistics(ctx: Context):
"""Provide index usage statistics and suggestions for optimization."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM sys.indexes_usage"
index_usage = db.execute_query(query)
return {
"success": True,
"index_usage": index_usage,
"count": len(index_usage)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_slow_query_analysis(ctx: Context, limit: int = 10):
"""Analyze queries from the slow query log with summaries."""
try:
db = ctx.lifespan["db"]
query = f"SELECT * FROM mysql.slow_log ORDER BY query_time DESC LIMIT %s"
slow_queries = db.execute_prepared_query(query, [limit])
return {
"success": True,
"slow_queries": slow_queries,
"count": len(slow_queries)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_stored_functions_procedures(ctx: Context):
"""List all stored functions and procedures with metadata details."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM information_schema.routines"
routines = db.execute_query(query)
return {
"success": True,
"routines": routines,
"count": len(routines)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_audit_logs(ctx: Context):
"""Show audit logs if enabled or recent security events."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM audit_log ORDER BY event_time DESC"
audit_logs = db.execute_query(query)
return {
"success": True,
"audit_logs": audit_logs,
"count": len(audit_logs)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_running_events(ctx: Context):
"""List all currently running events with schedules and status."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM information_schema.events WHERE status = 'ENABLED'"
events = db.execute_query(query)
return {
"success": True,
"events": events,
"count": len(events)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_triggers_by_event(ctx: Context):
"""Show triggers grouped by event type or action."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM information_schema.triggers ORDER BY event_manipulation"
triggers = db.execute_query(query)
return {
"success": True,
"triggers": triggers,
"count": len(triggers)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_connection_monitor(ctx: Context):
"""Provide live monitoring of connections and resource usage."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM information_schema.processlist"
processes = db.execute_query(query)
return {
"success": True,
"processes": processes,
"count": len(processes)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_stored_views_info(ctx: Context):
"""Display information about stored views in the database."""
try:
db = ctx.lifespan["db"]
query = "SELECT TABLE_NAME, VIEW_DEFINITION FROM information_schema.views"
views = db.execute_query(query)
return {
"success": True,
"views": views,
"count": len(views)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_roles_and_privileges(ctx: Context):
"""List database roles and their privileges."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM mysql.roles_mapping"
roles = db.execute_query(query)
return {
"success": True,
"roles": roles,
"count": len(roles)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_grants_for_entities(ctx: Context):
"""Show grants assigned to roles and users."""
try:
db = ctx.lifespan["db"]
query = "SHOW GRANTS"
grants = db.execute_query(query)
return {
"success": True,
"grants": grants,
"count": len(grants)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_unused_duplicate_indexes(ctx: Context):
"""Identify unused or duplicate indexes that could be dropped."""
try:
db = ctx.lifespan["db"]
query = "SELECT * FROM sys.schema_unused_indexes"
unused_indexes = db.execute_query(query)
return {
"success": True,
"unused_indexes": unused_indexes,
"count": len(unused_indexes)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_tables_without_primary_keys(ctx: Context):
"""List tables without primary keys and recommendations."""
try:
db = ctx.lifespan["db"]
query = "SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name NOT IN (SELECT table_name FROM information_schema.columns WHERE column_key = 'PRI')"
tables_no_pk = db.execute_query(query)
return {
"success": True,
"tables_no_pk": tables_no_pk,
"count": len(tables_no_pk)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_table_statistics(ctx: Context):
"""Provide info about table statistics like row counts and sizes."""
try:
db = ctx.lifespan["db"]
query = "SELECT table_name, table_rows, avg_row_length, data_length, index_length FROM information_schema.tables WHERE table_schema = DATABASE()"
tables_stats = db.execute_query(query)
return {
"success": True,
"tables_stats": tables_stats,
"count": len(tables_stats)
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_replication_binary_log_status(ctx: Context):
"""Show replication and binary log status details."""
try:
db = ctx.lifespan["db"]
replication_status = db.execute_query("SHOW MASTER STATUS")
binary_log_status = db.execute_query("SHOW BINARY LOGS")
return {
"success": True,
"replication_status": replication_status,
"binary_log_status": binary_log_status
}
except Exception as e:
return {"success": False, "error": str(e), "error_type": type(e).__name__}
@mcp.tool()
async def mysql_buffer_pool_statistics(ctx: Context):
"""Display buffer pool and cache usage statistics."""
try:
db = ctx.lifespan["db"]
query = "SHOW STATUS LIKE 'Innodb_buffer_pool_%'"
buffer_pool_stats = db.execute_query(query)
return {