-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathServer_Tools1.py
More file actions
1233 lines (1056 loc) · 50.6 KB
/
Server_Tools1.py
File metadata and controls
1233 lines (1056 loc) · 50.6 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
import os
import pyodbc
import psycopg2
from typing import Any
# MCP server
from fastmcp import FastMCP
import mysql.connector
from dotenv import load_dotenv
load_dotenv()
def must_get(key: str) -> str:
val = os.getenv(key)
if not val:
raise RuntimeError(f"Missing required env var {key}")
return val
# ————————————————
# 1. MySQL Configuration
# ————————————————
MYSQL_HOST = must_get("MYSQL_HOST")
MYSQL_PORT = int(must_get("MYSQL_PORT"))
MYSQL_USER = must_get("MYSQL_USER")
MYSQL_PASSWORD = must_get("MYSQL_PASSWORD")
MYSQL_DB = must_get("MYSQL_DB")
def get_mysql_conn(db: str | None = MYSQL_DB):
"""If db is None we connect to the server only (needed to CREATE DATABASE)."""
return mysql.connector.connect(
host=MYSQL_HOST,
port=MYSQL_PORT,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
database=db,
ssl_disabled=False, # Aiven requires TLS; keep this False
autocommit=True,
)
# ————————————————
# 2. PostgreSQL Configuration (Products)
# ————————————————
PG_HOST = must_get("PG_HOST")
PG_PORT = int(must_get("PG_PORT"))
PG_DB = os.getenv("PG_DB", "postgres") # db name can default
PG_USER = must_get("PG_USER")
PG_PASS = must_get("PG_PASSWORD")
def get_pg_conn():
return psycopg2.connect(
host=PG_HOST,
port=PG_PORT,
dbname=PG_DB,
user=PG_USER,
password=PG_PASS,
sslmode="require", # Supabase enforces TLS
)
# ————————————————
# 3. PostgreSQL Configuration (Sales)
# ————————————————
PG_SALES_HOST = must_get("PG_SALES_HOST")
PG_SALES_PORT = int(must_get("PG_SALES_PORT"))
PG_SALES_DB = os.getenv("PG_SALES_DB", "sales_db")
PG_SALES_USER = must_get("PG_SALES_USER")
PG_SALES_PASS = must_get("PG_SALES_PASSWORD")
def get_pg_sales_conn():
return psycopg2.connect(
host=PG_SALES_HOST,
port=PG_SALES_PORT,
dbname=PG_SALES_DB,
user=PG_SALES_USER,
password=PG_SALES_PASS,
sslmode="require",
)
# ————————————————
# 4. Instantiate your MCP server
# ————————————————
mcp = FastMCP("CRUDServer")
# ————————————————
# 5. Synchronous Setup: Create & seed tables
# ————————————————
def seed_databases():
# ---------- MySQL (Customers) ----------
root_cnx = get_mysql_conn(db=None)
root_cur = root_cnx.cursor()
root_cur.execute(f"CREATE DATABASE IF NOT EXISTS `{MYSQL_DB}`;")
root_cur.close()
root_cnx.close()
sql_cnx = get_mysql_conn()
sql_cur = sql_cnx.cursor()
# Disable foreign key checks temporarily
sql_cur.execute("SET FOREIGN_KEY_CHECKS = 0;")
# Drop tables in reverse dependency order (Sales first, then referenced tables)
sql_cur.execute("DROP TABLE IF EXISTS Sales;")
sql_cur.execute("DROP TABLE IF EXISTS ProductsCache;")
sql_cur.execute("DROP TABLE IF EXISTS Customers;")
# Re-enable foreign key checks
sql_cur.execute("SET FOREIGN_KEY_CHECKS = 1;")
# Create Customers table with FirstName and LastName
sql_cur.execute("""
CREATE TABLE Customers
(
Id INT AUTO_INCREMENT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(100),
CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
# Insert sample customers with FirstName and LastName
sql_cur.executemany(
"INSERT INTO Customers (FirstName, LastName, Name, Email) VALUES (%s, %s, %s, %s)",
[("Alice", "Johnson", "Alice Johnson", "alice@example.com"),
("Bob", "Smith", "Bob Smith", "bob@example.com"),
("Charlie", "Brown", "Charlie Brown", None)] # Charlie has no email for null handling demo
)
# Create ProductsCache table (copy of PostgreSQL products for easier joins)
sql_cur.execute("""
CREATE TABLE ProductsCache
(
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 4) NOT NULL,
description TEXT
);
""")
# Insert sample products cache
sql_cur.executemany(
"INSERT INTO ProductsCache (id, name, price, description) VALUES (%s, %s, %s, %s)",
[(1, "Widget", 9.99, "A standard widget."),
(2, "Gadget", 14.99, "A useful gadget."),
(3, "Tool", 24.99, None)] # Tool has no description for null handling demo
)
# Create Sales table in MySQL with foreign key constraints
sql_cur.execute("""
CREATE TABLE Sales
(
Id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL DEFAULT 1,
unit_price DECIMAL(10, 4) NOT NULL,
total_price DECIMAL(10, 4) NOT NULL,
sale_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_id) REFERENCES Customers(Id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES ProductsCache(id) ON DELETE CASCADE
);
""")
# Insert sample sales data
sql_cur.executemany(
"INSERT INTO Sales (customer_id, product_id, quantity, unit_price, total_price) VALUES (%s, %s, %s, %s, %s)",
[(1, 1, 2, 9.99, 19.98), # Alice bought 2 Widgets
(2, 2, 1, 14.99, 14.99), # Bob bought 1 Gadget
(3, 3, 3, 24.99, 74.97)] # Charlie bought 3 Tools
)
sql_cnx.close()
# ---------- PostgreSQL (Products) ----------
pg_cnxn = get_pg_conn()
pg_cnxn.autocommit = True
pg_cur = pg_cnxn.cursor()
pg_cur.execute("DROP TABLE IF EXISTS products CASCADE;")
pg_cur.execute("""
CREATE TABLE products
(
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10, 4) NOT NULL,
description TEXT
);
""")
pg_cur.executemany(
"INSERT INTO products (name, price, description) VALUES (%s, %s, %s)",
[("Widget", 9.99, "A standard widget."),
("Gadget", 14.99, "A useful gadget."),
("Tool", 24.99, "A handy tool.")]
)
pg_cnxn.close()
# ---------- PostgreSQL Sales Database ----------
sales_cnxn = get_pg_sales_conn()
sales_cnxn.autocommit = True
sales_cur = sales_cnxn.cursor()
sales_cur.execute("DROP TABLE IF EXISTS sales;")
sales_cur.execute("""
CREATE TABLE sales
(
id SERIAL PRIMARY KEY,
customer_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL DEFAULT 1,
unit_price NUMERIC(10, 4) NOT NULL,
total_amount NUMERIC(10, 4) NOT NULL,
sale_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
# Sample sales data
sales_cur.executemany(
"INSERT INTO sales (customer_id, product_id, quantity, unit_price, total_amount) VALUES (%s, %s, %s, %s, %s)",
[(1, 1, 2, 9.99, 19.98), # Alice bought 2 Widgets
(2, 2, 1, 14.99, 14.99), # Bob bought 1 Gadget
(3, 3, 3, 24.99, 74.97)] # Charlie bought 3 Tools
)
sales_cnxn.close()
# ————————————————
# 6. Helper Functions for Cross-Database Queries and Name Resolution
# ————————————————
def get_customer_name(customer_id: int) -> str:
"""Fetch customer name from MySQL database"""
try:
mysql_cnxn = get_mysql_conn()
mysql_cur = mysql_cnxn.cursor()
mysql_cur.execute("SELECT Name FROM Customers WHERE Id = %s", (customer_id,))
result = mysql_cur.fetchone()
mysql_cnxn.close()
return result[0] if result else f"Unknown Customer ({customer_id})"
except Exception:
return f"Unknown Customer ({customer_id})"
def get_product_details(product_id: int) -> dict:
"""Fetch product name and price from PostgreSQL products database"""
try:
pg_cnxn = get_pg_conn()
pg_cur = pg_cnxn.cursor()
pg_cur.execute("SELECT name, price FROM products WHERE id = %s", (product_id,))
result = pg_cur.fetchone()
pg_cnxn.close()
if result:
return {"name": result[0], "price": float(result[1])}
else:
return {"name": f"Unknown Product ({product_id})", "price": 0.0}
except Exception:
return {"name": f"Unknown Product ({product_id})", "price": 0.0}
def validate_customer_exists(customer_id: int) -> bool:
"""Check if customer exists in MySQL database"""
try:
mysql_cnxn = get_mysql_conn()
mysql_cur = mysql_cnxn.cursor()
mysql_cur.execute("SELECT COUNT(*) FROM Customers WHERE Id = %s", (customer_id,))
result = mysql_cur.fetchone()
mysql_cnxn.close()
return result[0] > 0 if result else False
except Exception:
return False
def validate_product_exists(product_id: int) -> bool:
"""Check if product exists in PostgreSQL products database"""
try:
pg_cnxn = get_pg_conn()
pg_cur = pg_cnxn.cursor()
pg_cur.execute("SELECT COUNT(*) FROM products WHERE id = %s", (product_id,))
result = pg_cur.fetchone()
pg_cnxn.close()
return result[0] > 0 if result else False
except Exception:
return False
def find_customer_by_name_enhanced(name: str) -> dict:
"""Enhanced customer search that handles multiple matches intelligently"""
try:
mysql_cnxn = get_mysql_conn()
mysql_cur = mysql_cnxn.cursor()
# Search strategy with priorities:
# 1. Exact full name match (case insensitive)
# 2. Exact first name or last name match
# 3. Partial name matches
all_matches = []
# 1. Try exact full name match (case insensitive)
mysql_cur.execute("SELECT Id, Name, Email FROM Customers WHERE LOWER(Name) = LOWER(%s)", (name,))
exact_matches = mysql_cur.fetchall()
if exact_matches:
# If only one exact match, return it immediately
if len(exact_matches) == 1:
mysql_cnxn.close()
return {
"found": True,
"multiple_matches": False,
"customer_id": exact_matches[0][0],
"customer_name": exact_matches[0][1],
"customer_email": exact_matches[0][2]
}
else:
# Multiple exact matches (rare but possible)
for match in exact_matches:
all_matches.append({
"id": match[0],
"name": match[1],
"email": match[2],
"match_type": "exact_full_name"
})
# 2. Try exact first name or last name match if no exact full name match
if not exact_matches:
mysql_cur.execute("""
SELECT Id, Name, Email FROM Customers
WHERE LOWER(FirstName) = LOWER(%s)
OR LOWER(LastName) = LOWER(%s)
""", (name, name))
name_matches = mysql_cur.fetchall()
for match in name_matches:
all_matches.append({
"id": match[0],
"name": match[1],
"email": match[2],
"match_type": "exact_name_part"
})
# 3. Try partial matches only if no exact matches found
if not all_matches:
mysql_cur.execute("""
SELECT Id, Name, Email FROM Customers
WHERE LOWER(Name) LIKE LOWER(%s)
OR LOWER(FirstName) LIKE LOWER(%s)
OR LOWER(LastName) LIKE LOWER(%s)
""", (f"%{name}%", f"%{name}%", f"%{name}%"))
partial_matches = mysql_cur.fetchall()
for match in partial_matches:
all_matches.append({
"id": match[0],
"name": match[1],
"email": match[2],
"match_type": "partial"
})
mysql_cnxn.close()
# Handle results
if not all_matches:
return {"found": False, "error": f"Customer '{name}' not found"}
if len(all_matches) == 1:
match = all_matches[0]
return {
"found": True,
"multiple_matches": False,
"customer_id": match["id"],
"customer_name": match["name"],
"customer_email": match["email"]
}
# Multiple matches found
return {
"found": True,
"multiple_matches": True,
"matches": all_matches,
"error": f"Multiple customers found matching '{name}'"
}
except Exception as e:
return {"found": False, "error": f"Database error: {str(e)}"}
def find_product_by_name(name: str) -> dict:
"""Find product by name (supports partial matching)"""
try:
pg_cnxn = get_pg_conn()
pg_cur = pg_cnxn.cursor()
# Try exact match first
pg_cur.execute("SELECT id, name FROM products WHERE name = %s", (name,))
result = pg_cur.fetchone()
if result:
pg_cnxn.close()
return {"id": result[0], "name": result[1], "found": True}
# Try case-insensitive exact match
pg_cur.execute("SELECT id, name FROM products WHERE LOWER(name) = LOWER(%s)", (name,))
result = pg_cur.fetchone()
if result:
pg_cnxn.close()
return {"id": result[0], "name": result[1], "found": True}
# Try partial match
pg_cur.execute("SELECT id, name FROM products WHERE LOWER(name) LIKE LOWER(%s)", (f"%{name}%",))
result = pg_cur.fetchone()
if result:
pg_cnxn.close()
return {"id": result[0], "name": result[1], "found": True}
pg_cnxn.close()
return {"found": False, "error": f"Product '{name}' not found"}
except Exception as e:
return {"found": False, "error": f"Database error: {str(e)}"}
# ————————————————
# 7. Enhanced MySQL CRUD Tool (Customers) with Smart Name Resolution
# ————————————————
# Fixed sqlserver_crud function with proper variable initialization
@mcp.tool()
async def sqlserver_crud(
operation: str,
name: str = None,
email: str = None,
limit: int = 10,
customer_id: int = None,
new_email: str = None,
table_name: str = None,
) -> Any:
cnxn = get_mysql_conn()
cur = cnxn.cursor()
if operation == "create":
if not name or not email:
cnxn.close()
return {"sql": None, "result": "❌ 'name' and 'email' required for create."}
# NEW LOGIC: Check if customer with this name already exists
# Search for existing customers with the same first name or full name
search_name = name.strip()
# Check for exact name matches or first name matches
cur.execute("""
SELECT Id, Name, Email FROM Customers
WHERE LOWER(Name) = LOWER(%s)
OR LOWER(FirstName) = LOWER(%s)
OR LOWER(Name) LIKE LOWER(%s)
""", (search_name, search_name, f"%{search_name}%"))
existing_customers = cur.fetchall()
if existing_customers:
# Filter out customers who already have emails
customers_without_email = [c for c in existing_customers if not c[2]] # c[2] is Email
customers_with_email = [c for c in existing_customers if c[2]] # c[2] is Email
if len(existing_customers) == 1:
# Only one customer found
existing_customer = existing_customers[0]
if existing_customer[2]: # Already has email
cnxn.close()
return {"sql": None, "result": f"ℹ️ Customer '{existing_customer[1]}' already has email '{existing_customer[2]}'. If you want to update it, please specify the full name."}
else:
# Customer exists but no email, update with the email
sql_query = "UPDATE Customers SET Email = %s WHERE Id = %s"
cur.execute(sql_query, (email, existing_customer[0]))
cnxn.commit()
cnxn.close()
return {"sql": sql_query, "result": f"✅ Email '{email}' added to existing customer '{existing_customer[1]}'."}
elif len(existing_customers) > 1:
# Multiple customers found - ask for clarification
customer_list = []
for c in existing_customers:
email_status = f"(has email: {c[2]})" if c[2] else "(no email)"
customer_list.append(f"- {c[1]} {email_status}")
customer_details = "\n".join(customer_list)
cnxn.close()
return {"sql": None, "result": f"❓ Multiple customers found with name '{search_name}':\n{customer_details}\n\nPlease specify the full name (first and last name) to identify which customer you want to add the email to, or use a different name if you want to create a new customer."}
# No existing customer found, create new customer
# Split name into first and last name (simple split)
name_parts = name.split(' ', 1)
first_name = name_parts[0]
last_name = name_parts[1] if len(name_parts) > 1 else ""
sql_query = "INSERT INTO Customers (FirstName, LastName, Name, Email) VALUES (%s, %s, %s, %s)"
cur.execute(sql_query, (first_name, last_name, name, email))
cnxn.commit()
cnxn.close()
return {"sql": sql_query, "result": f"✅ New customer '{name}' created with email '{email}'."}
elif operation == "read":
# Handle filtering by name if provided
if name:
sql_query = """
SELECT Id, FirstName, LastName, Name, Email, CreatedAt
FROM Customers
WHERE LOWER(Name) LIKE LOWER(%s)
OR LOWER(FirstName) LIKE LOWER(%s)
OR LOWER(LastName) LIKE LOWER(%s)
ORDER BY Id ASC
LIMIT %s
"""
cur.execute(sql_query, (f"%{name}%", f"%{name}%", f"%{name}%", limit))
else:
sql_query = """
SELECT Id, FirstName, LastName, Name, Email, CreatedAt
FROM Customers
ORDER BY Id ASC
LIMIT %s
"""
cur.execute(sql_query, (limit,))
rows = cur.fetchall()
result = [
{
"Id": r[0],
"FirstName": r[1],
"LastName": r[2],
"Name": r[3],
"Email": r[4],
"CreatedAt": r[5].isoformat()
}
for r in rows
]
cnxn.close()
return {"sql": sql_query, "result": result}
elif operation == "update":
# Initialize customer_name variable
customer_name = None
# Enhanced update: resolve customer_id from name if not provided
if not customer_id and name:
# Use the original find_customer_by_name function if enhanced version not available
try:
customer_info = find_customer_by_name(name)
if not customer_info["found"]:
cnxn.close()
return {"sql": None, "result": f"❌ {customer_info['error']}"}
customer_id = customer_info["id"]
customer_name = customer_info["name"]
except Exception as search_error:
# Fallback to direct database search
cur.execute("""
SELECT Id, Name FROM Customers
WHERE LOWER(Name) = LOWER(%s)
OR LOWER(FirstName) = LOWER(%s)
OR LOWER(LastName) = LOWER(%s)
LIMIT 1
""", (name, name, name))
result = cur.fetchone()
if result:
customer_id = result[0]
customer_name = result[1]
else:
cnxn.close()
return {"sql": None, "result": f"❌ Customer '{name}' not found"}
if not customer_id or not new_email:
cnxn.close()
return {"sql": None, "result": "❌ 'customer_id' (or 'name') and 'new_email' required for update."}
# Check if customer already has this email
cur.execute("SELECT Name, Email FROM Customers WHERE Id = %s", (customer_id,))
existing_customer = cur.fetchone()
if not existing_customer:
cnxn.close()
return {"sql": None, "result": f"❌ Customer with ID {customer_id} not found."}
# Set customer_name if not already set
if not customer_name:
customer_name = existing_customer[0]
if existing_customer[1] == new_email:
cnxn.close()
return {"sql": None, "result": f"ℹ️ Customer '{customer_name}' already has email '{new_email}'."}
sql_query = "UPDATE Customers SET Email = %s WHERE Id = %s"
cur.execute(sql_query, (new_email, customer_id))
cnxn.commit()
cnxn.close()
return {"sql": sql_query, "result": f"✅ Customer '{customer_name}' email updated to '{new_email}'."}
elif operation == "delete":
# Initialize customer_name variable
customer_name = None
# Enhanced delete: resolve customer_id from name if not provided
if not customer_id and name:
try:
customer_info = find_customer_by_name(name)
if not customer_info["found"]:
cnxn.close()
return {"sql": None, "result": f"❌ {customer_info['error']}"}
customer_id = customer_info["id"]
customer_name = customer_info["name"]
except Exception as search_error:
# Fallback to direct database search
cur.execute("""
SELECT Id, Name FROM Customers
WHERE LOWER(Name) = LOWER(%s)
OR LOWER(FirstName) = LOWER(%s)
OR LOWER(LastName) = LOWER(%s)
LIMIT 1
""", (name, name, name))
result = cur.fetchone()
if result:
customer_id = result[0]
customer_name = result[1]
else:
cnxn.close()
return {"sql": None, "result": f"❌ Customer '{name}' not found"}
elif customer_id:
# Get customer name for response
cur.execute("SELECT Name FROM Customers WHERE Id = %s", (customer_id,))
result = cur.fetchone()
customer_name = result[0] if result else f"Customer {customer_id}"
else:
cnxn.close()
return {"sql": None, "result": "❌ 'customer_id' or 'name' required for delete."}
sql_query = "DELETE FROM Customers WHERE Id = %s"
cur.execute(sql_query, (customer_id,))
cnxn.commit()
cnxn.close()
return {"sql": sql_query, "result": f"✅ Customer '{customer_name}' deleted."}
elif operation == "describe":
table = table_name or "Customers"
sql_query = f"DESCRIBE {table}"
cur.execute(sql_query)
rows = cur.fetchall()
result = [
{
"Field": r[0],
"Type": r[1],
"Null": r[2],
"Key": r[3],
"Default": r[4],
"Extra": r[5]
}
for r in rows
]
cnxn.close()
return {"sql": sql_query, "result": result}
else:
cnxn.close()
return {"sql": None, "result": f"❌ Unknown operation '{operation}'."}
# ————————————————
# 8. Enhanced PostgreSQL CRUD Tool (Products) with Smart Name Resolution
# ————————————————
@mcp.tool()
async def postgresql_crud(
operation: str,
name: str = None,
price: float = None,
description: str = None,
limit: int = 10,
product_id: int = None,
new_price: float = None,
table_name: str = None,
) -> Any:
cnxn = get_pg_conn()
cur = cnxn.cursor()
if operation == "create":
if not name or price is None:
cnxn.close()
return {"sql": None, "result": "❌ 'name' and 'price' required for create."}
sql_query = "INSERT INTO products (name, price, description) VALUES (%s, %s, %s)"
cur.execute(sql_query, (name, price, description))
cnxn.commit()
result = f"✅ Product '{name}' added with price ${price:.2f}."
cnxn.close()
return {"sql": sql_query, "result": result}
elif operation == "read":
# Handle filtering by name if provided
if name:
sql_query = """
SELECT id, name, price, description
FROM products
WHERE LOWER(name) LIKE LOWER(%s)
ORDER BY id ASC
LIMIT %s
"""
cur.execute(sql_query, (f"%{name}%", limit))
else:
sql_query = """
SELECT id, name, price, description
FROM products
ORDER BY id ASC
LIMIT %s
"""
cur.execute(sql_query, (limit,))
rows = cur.fetchall()
result = [
{"id": r[0], "name": r[1], "price": float(r[2]), "description": r[3] or ""}
for r in rows
]
cnxn.close()
return {"sql": sql_query, "result": result}
elif operation == "update":
# Enhanced update: resolve product_id from name if not provided
if not product_id and name:
product_info = find_product_by_name(name)
if not product_info["found"]:
cnxn.close()
return {"sql": None, "result": f"❌ {product_info['error']}"}
product_id = product_info["id"]
if not product_id or new_price is None:
cnxn.close()
return {"sql": None, "result": "❌ 'product_id' (or 'name') and 'new_price' required for update."}
sql_query = "UPDATE products SET price = %s WHERE id = %s"
cur.execute(sql_query, (new_price, product_id))
cnxn.commit()
# Get updated product name for response
cur.execute("SELECT name FROM products WHERE id = %s", (product_id,))
product_name = cur.fetchone()
product_name = product_name[0] if product_name else f"Product {product_id}"
cnxn.close()
return {"sql": sql_query, "result": f"✅ Product '{product_name}' price updated to ${new_price:.2f}."}
elif operation == "delete":
# Enhanced delete: resolve product_id from name if not provided
if not product_id and name:
product_info = find_product_by_name(name)
if not product_info["found"]:
cnxn.close()
return {"sql": None, "result": f"❌ {product_info['error']}"}
product_id = product_info["id"]
product_name = product_info["name"]
elif product_id:
# Get product name for response
cur.execute("SELECT name FROM products WHERE id = %s", (product_id,))
result = cur.fetchone()
product_name = result[0] if result else f"Product {product_id}"
else:
cnxn.close()
return {"sql": None, "result": "❌ 'product_id' or 'name' required for delete."}
sql_query = "DELETE FROM products WHERE id = %s"
cur.execute(sql_query, (product_id,))
cnxn.commit()
cnxn.close()
return {"sql": sql_query, "result": f"✅ Product '{product_name}' deleted."}
elif operation == "describe":
table = table_name or "products"
sql_query = f"""
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = %s
ORDER BY ordinal_position
"""
cur.execute(sql_query, (table,))
rows = cur.fetchall()
result = [
{
"Column": r[0],
"Type": r[1],
"Nullable": r[2],
"Default": r[3]
}
for r in rows
]
cnxn.close()
return {"sql": sql_query, "result": result}
else:
cnxn.close()
return {"sql": None, "result": f"❌ Unknown operation '{operation}'."}
# ————————————————
# 9. Sales CRUD Tool with Display Formatting Features (Unchanged)
# ————————————————
# Fixed sales_crud function with proper column selection
# Fixed sales_crud function with proper WHERE clause and column selection
# Fixed sales_crud function with proper WHERE clause and column selection
@mcp.tool()
async def sales_crud(
operation: str,
customer_id: int = None,
product_id: int = None,
quantity: int = 1,
unit_price: float = None,
total_amount: float = None,
sale_id: int = None,
new_quantity: int = None,
table_name: str = None,
display_format: str = None, # Display formatting parameter
customer_name: str = None,
product_name: str = None,
email: str = None,
total_price: float = None,
# Enhanced parameters for column selection and filtering
columns: str = None, # Comma-separated list of columns to display
where_clause: str = None, # WHERE conditions
filter_conditions: dict = None, # Alternative: structured filters
limit: int = None # Row limit
) -> Any:
# For PostgreSQL sales operations (create, update, delete)
if operation in ["create", "update", "delete"]:
sales_cnxn = get_pg_sales_conn()
sales_cur = sales_cnxn.cursor()
if operation == "create":
if not customer_id or not product_id:
sales_cnxn.close()
return {"sql": None, "result": "❌ 'customer_id' and 'product_id' required for create."}
# Validate customer exists
if not validate_customer_exists(customer_id):
sales_cnxn.close()
return {"sql": None, "result": f"❌ Customer with ID {customer_id} not found."}
# Validate product exists and get price
if not validate_product_exists(product_id):
sales_cnxn.close()
return {"sql": None, "result": f"❌ Product with ID {product_id} not found."}
# Get product price if not provided
if not unit_price:
product_details = get_product_details(product_id)
unit_price = product_details["price"]
if not total_amount:
total_amount = unit_price * quantity
sql_query = """
INSERT INTO sales (customer_id, product_id, quantity, unit_price, total_amount)
VALUES (%s, %s, %s, %s, %s)
"""
sales_cur.execute(sql_query, (customer_id, product_id, quantity, unit_price, total_amount))
sales_cnxn.commit()
# Get customer and product names for response
customer_name = get_customer_name(customer_id)
product_details = get_product_details(product_id)
result = f"✅ Sale created: {customer_name} bought {quantity} {product_details['name']}(s) for ${total_amount:.2f}"
sales_cnxn.close()
return {"sql": sql_query, "result": result}
elif operation == "update":
if not sale_id or new_quantity is None:
sales_cnxn.close()
return {"sql": None, "result": "❌ 'sale_id' and 'new_quantity' required for update."}
# Recalculate total amount
sql_query = """
UPDATE sales
SET quantity = %s,
total_amount = unit_price * %s
WHERE id = %s
"""
sales_cur.execute(sql_query, (new_quantity, new_quantity, sale_id))
sales_cnxn.commit()
result = f"✅ Sale id={sale_id} updated to quantity {new_quantity}."
sales_cnxn.close()
return {"sql": sql_query, "result": result}
elif operation == "delete":
if not sale_id:
sales_cnxn.close()
return {"sql": None, "result": "❌ 'sale_id' required for delete."}
sql_query = "DELETE FROM sales WHERE id = %s"
sales_cur.execute(sql_query, (sale_id,))
sales_cnxn.commit()
result = f"✅ Sale id={sale_id} deleted."
sales_cnxn.close()
return {"sql": sql_query, "result": result}
# Enhanced READ operation with FIXED column selection AND WHERE clause filtering
elif operation == "read":
mysql_cnxn = get_mysql_conn()
mysql_cur = mysql_cnxn.cursor()
# Fixed column mappings - standardized naming
available_columns = {
"sale_id": "s.Id",
"first_name": "c.FirstName",
"last_name": "c.LastName",
"customer_name": "c.Name", # Use the Name field which has full name
"product_name": "p.name",
"product_description": "p.description",
"quantity": "s.quantity",
"unit_price": "s.unit_price",
"total_price": "s.total_price",
"amount": "s.total_price", # Alias for total_price
"sale_date": "s.sale_date",
"date": "s.sale_date", # Alias for sale_date
"customer_email": "c.Email",
"email": "c.Email" # Alias for customer_email
}
# FIXED: Process column selection with better parsing
selected_columns = []
column_aliases = []
print(f"DEBUG: Raw columns parameter: '{columns}'")
if columns and columns.strip():
# Clean and split the columns string
columns_clean = columns.strip()
# Handle different input patterns
if "," in columns_clean:
# Comma-separated list
requested_cols = [col.strip().lower().replace(" ", "_") for col in columns_clean.split(",") if col.strip()]
else:
# Space-separated or single column
requested_cols = [col.strip().lower().replace(" ", "_") for col in columns_clean.split() if col.strip()]
print(f"DEBUG: Requested columns after parsing: {requested_cols}")
# Build SELECT clause based on requested columns
for col in requested_cols:
matched = False
# Try exact match first
if col in available_columns:
selected_columns.append(available_columns[col])
column_aliases.append(col)
matched = True
print(f"DEBUG: Exact match found for '{col}': {available_columns[col]}")
else:
# Try fuzzy matching for common variations
for avail_col, db_col in available_columns.items():
if (col in avail_col or avail_col in col or
col.replace("_", "") in avail_col.replace("_", "") or
avail_col.replace("_", "") in col.replace("_", "")):
selected_columns.append(db_col)
column_aliases.append(avail_col)
matched = True
print(f"DEBUG: Fuzzy match found for '{col}' -> '{avail_col}': {db_col}")
break
if not matched:
print(f"DEBUG: No match found for column '{col}'. Skipping...")
# If no valid columns found or no columns specified, use default key columns
if not selected_columns:
print("DEBUG: Using default key columns")
selected_columns = [
"s.Id", "c.Name", "p.name", "s.quantity", "s.unit_price", "s.total_price", "s.sale_date", "c.Email"
]
column_aliases = [
"sale_id", "customer_name", "product_name", "quantity", "unit_price", "total_price", "sale_date", "email"
]
print(f"DEBUG: Final selected columns: {selected_columns}")
print(f"DEBUG: Final column aliases: {column_aliases}")
# Build dynamic SQL query
select_clause = ", ".join([f"{col} AS {alias}" for col, alias in zip(selected_columns, column_aliases)])
# Base query
base_sql = f"""
SELECT {select_clause}
FROM Sales s
JOIN Customers c ON c.Id = s.customer_id
JOIN ProductsCache p ON p.id = s.product_id
"""
# COMPLETELY REWRITTEN WHERE clause processing
where_sql = ""
query_params = []
if where_clause and where_clause.strip():
print(f"DEBUG: Processing WHERE clause: '{where_clause}'")