forked from lokit-s/mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2258 lines (2007 loc) · 88.7 KB
/
main.py
File metadata and controls
2258 lines (2007 loc) · 88.7 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 random
from datetime import datetime, timedelta
from typing import Any, Optional
import mysql.connector
import pandas as pd
import psycopg2
import pyodbc
from dotenv import load_dotenv
from fastmcp import FastMCP
load_dotenv()
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
TSV_FILE = os.path.join(SCRIPT_DIR, "output.tsv")
def must_get(key: str) -> str:
val = os.getenv(key)
if not val:
raise RuntimeError(f"Missing required env var {key}")
return val
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):
return mysql.connector.connect(
host=MYSQL_HOST,
port=MYSQL_PORT,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
database=db,
ssl_disabled=False,
autocommit=True,
)
PG_HOST = must_get("PG_HOST")
PG_PORT = int(must_get("PG_PORT"))
PG_DB = os.getenv("PG_DB", "postgres")
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",
)
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",
)
mcp = FastMCP("CRUDServer")
def generate_call_transcript(
issue_category, resolution_status, sentiment_score, agent_name, duration
):
transcript_templates = {
"billing": {
"positive": [
f"Customer called about billing discrepancy. {agent_name} explained the charges clearly. Customer expressed satisfaction with the detailed breakdown. Issue resolved by applying appropriate credit adjustment. Customer thanked agent for patience.",
f"Inquiry about unexpected charges on account. {agent_name} reviewed billing history, identified duplicate charge. Immediate refund processed. Customer appreciated quick resolution and professional service provided.",
f"Customer confused about new billing format. {agent_name} walked through each line item. Customer now understands charges better. Offered paperless billing option which customer accepted happily.",
],
"negative": [
f"Customer upset about overcharge. {agent_name} attempted to explain but customer remained frustrated. Multiple billing errors found. Escalated to supervisor for resolution. Customer demanded compensation for inconvenience.",
f"Angry customer disputing charges for third month. {agent_name} unable to locate previous adjustment notes. System showing conflicting information. Customer threatened to cancel service. Immediate escalation required.",
f"Customer extremely dissatisfied with billing practices. {agent_name} apologized repeatedly but customer remained hostile. Previous promises not honored. Customer considering legal action. Urgent management intervention needed.",
],
"neutral": [
f"Routine billing inquiry about statement date. {agent_name} explained billing cycle details. Customer requested email confirmation. Standard information provided. Call concluded with no issues identified.",
f"Customer checking on payment processing status. {agent_name} confirmed payment received yesterday. Updated account reflects current balance. Customer satisfied with information. No further action required.",
],
},
"technical": {
"positive": [
f"Customer experiencing connectivity issues. {agent_name} performed remote diagnostics successfully. Issue identified as router configuration problem. Guided customer through reset process. Service restored, customer very grateful.",
f"Software installation problem reported. {agent_name} provided step-by-step guidance. Customer followed instructions carefully. Installation completed successfully. Customer praised agent's clear communication skills.",
f"Customer needed help with new feature setup. {agent_name} shared screen remotely. Configuration completed together. Customer learned valuable tips. Highly satisfied with support received.",
],
"negative": [
f"Recurring technical problem frustrating customer. {agent_name} attempted multiple troubleshooting steps unsuccessfully. Customer lost patience during lengthy process. Previous tickets show unresolved issues. Escalation to technical team required.",
f"Customer angry about service outage. {agent_name} acknowledged ongoing system issues. No immediate resolution available. Customer demanding compensation for business losses. Extremely dissatisfied with response.",
f"Critical system failure affecting customer operations. {agent_name} unable to provide timeline for fix. Customer stressed about impact on business. Multiple failed resolution attempts. Emergency escalation initiated.",
],
"neutral": [
f"Customer inquiring about system maintenance schedule. {agent_name} provided upcoming maintenance windows. Customer noted dates for planning. Standard information exchanged. Call ended cordially.",
f"Routine technical specification question. {agent_name} consulted documentation and provided details. Customer taking notes for internal team. Information delivered as requested. No issues noted.",
],
},
"product_inquiry": {
"positive": [
f"Customer interested in new product features. {agent_name} enthusiastically explained benefits and pricing. Customer impressed with capabilities. Decided to upgrade immediately. Very satisfied with information received.",
f"Inquiry about product compatibility. {agent_name} confirmed full compatibility with customer's setup. Provided additional recommendations. Customer pleased with comprehensive response. Proceeding with purchase.",
f"Customer seeking product recommendations. {agent_name} analyzed needs and suggested perfect solution. Customer excited about features. Order placed during call. Thanked agent for expertise.",
],
"negative": [
f"Customer disappointed with product limitations. {agent_name} explained current capabilities. Customer expected more features for price. Unhappy with value proposition. Considering competitor alternatives.",
f"Product not meeting advertised specifications. {agent_name} acknowledged discrepancy. Customer frustrated with misleading information. Requested full refund. Very dissatisfied with experience.",
],
"neutral": [
f"General product information request. {agent_name} provided standard specifications and pricing. Customer collecting information for comparison. Will discuss with team. Polite interaction throughout.",
f"Customer checking product availability. {agent_name} confirmed stock levels and delivery times. Customer will consider options. Standard inquiry handled efficiently. No commitment made.",
],
},
"complaint": {
"positive": [
f"Customer initially upset about service issue. {agent_name} listened empathetically and apologized sincerely. Offered immediate solution and compensation. Customer attitude improved significantly. Ended call satisfied.",
f"Complaint about previous poor experience. {agent_name} took ownership and implemented corrective measures. Customer appreciated proactive approach. Issue resolved beyond expectations. Relationship restored.",
],
"negative": [
f"Customer extremely angry about repeated problems. {agent_name} struggled to calm situation. Multiple service failures documented. Customer demanding executive contact. Threatening social media exposure.",
f"Serious complaint about staff behavior. {agent_name} attempted damage control unsuccessfully. Customer unwilling to accept apologies. Formal complaint being filed. Legal action mentioned.",
f"Long-standing issue causing major frustration. {agent_name} unable to provide satisfactory resolution. Customer exhausted all patience. Canceling service immediately. Extremely negative experience.",
],
"neutral": [
f"Customer registering formal complaint for records. {agent_name} documented all details carefully. Standard complaint procedure followed. Reference number provided. Professional interaction maintained throughout.",
],
},
"order_status": {
"positive": [
f"Customer checking on recent order. {agent_name} provided tracking information promptly. Delivery on schedule for tomorrow. Customer pleased with quick update. Expressed satisfaction with service.",
f"Inquiry about expedited shipping options. {agent_name} arranged priority delivery at no charge. Customer delighted with accommodation. Order upgraded successfully. Very appreciative of help.",
],
"negative": [
f"Order significantly delayed without notification. {agent_name} found logistics error. Customer upset about lack of communication. Business impact significant. Demanding immediate resolution and compensation.",
f"Wrong items delivered twice. {agent_name} apologized but no immediate fix available. Customer frustrated with repeated errors. Quality control issues evident. Considering canceling all future orders.",
],
"neutral": [
f"Routine order status check. {agent_name} confirmed shipment departed this morning. Tracking number provided via email. Customer satisfied with update. Standard inquiry resolved quickly.",
],
},
"account": {
"positive": [
f"Customer needed password reset assistance. {agent_name} verified identity and reset credentials. Access restored immediately. Customer grateful for quick help. Security tips provided and appreciated.",
f"Account upgrade request. {agent_name} processed changes efficiently. New features activated instantly. Customer excited about enhanced capabilities. Smooth transition completed.",
],
"negative": [
f"Account hacked, unauthorized charges made. {agent_name} initiated security protocol. Customer panicked about data breach. Investigation will take days. Very upset about security failure.",
f"Unable to access account for weeks. {agent_name} found system error. Customer missed important deadlines. Business losses mounting. Extremely frustrated with platform reliability.",
],
"neutral": [
f"Customer updating contact information. {agent_name} processed changes in system. Confirmation email sent. Standard account maintenance completed. No issues encountered.",
],
},
"refund": {
"positive": [
f"Refund request for defective product. {agent_name} approved immediately after verification. Processing within 3-5 days. Customer satisfied with quick approval. Appreciated hassle-free process.",
f"Customer requesting partial refund for service issue. {agent_name} calculated fair adjustment. Credit applied to account instantly. Customer happy with resolution. Thanked agent for understanding.",
],
"negative": [
f"Refund denied despite valid complaint. {agent_name} cited policy restrictions. Customer arguing about unfair treatment. Previous promises not honored. Threatening chargeback through bank.",
f"Multiple refund requests ignored. {agent_name} found processing errors. Customer exhausted and angry. Financial hardship mentioned. Considering legal action for resolution.",
],
"neutral": [
f"Standard refund inquiry about timeline. {agent_name} explained processing procedures. Customer understood requirements. Documentation submitted. Awaiting standard processing time.",
],
},
"general": {
"positive": [
f"Customer calling to praise recent service. {agent_name} accepted compliments graciously. Customer wanted manager to know about excellent experience. Positive feedback documented. Very satisfied customer.",
f"General inquiry about services. {agent_name} provided comprehensive overview. Customer impressed with options available. Interested in learning more. Scheduling follow-up consultation.",
],
"negative": [
f"Customer expressing overall dissatisfaction. {agent_name} listened to multiple concerns. Long list of problems mentioned. Customer considering switching providers. Retention team referral needed.",
f"Vague complaint about service quality. {agent_name} tried identifying specific issues. Customer frustrated with everything. Unable to pinpoint exact problem. General dissatisfaction expressed.",
],
"neutral": [
f"Customer had miscellaneous questions. {agent_name} answered each one patiently. Information gathering for future reference. No immediate action needed. Cordial conversation throughout.",
f"General check-in call about services. {agent_name} reviewed account status. Everything functioning normally. Customer had no concerns. Brief, pleasant interaction.",
],
},
}
if sentiment_score >= 0.3:
sentiment_cat = "positive"
elif sentiment_score <= -0.3:
sentiment_cat = "negative"
else:
sentiment_cat = "neutral"
if issue_category in transcript_templates:
templates = transcript_templates[issue_category].get(
sentiment_cat, transcript_templates[issue_category]["neutral"]
)
else:
templates = transcript_templates["general"][sentiment_cat]
base_transcript = random.choice(templates)
if duration < 120:
base_transcript = "Quick call. " + base_transcript
elif duration > 900:
base_transcript = "Extended call requiring patience. " + base_transcript
if resolution_status == "escalated":
base_transcript += " Supervisor intervention required."
elif resolution_status == "pending":
base_transcript += " Follow-up scheduled."
words = base_transcript.split()
if len(words) > 40:
base_transcript = " ".join(words[:40])
elif len(words) < 30:
padding = [
"Additional notes added.",
"Customer database updated.",
"Ticket created for tracking.",
"Quality assurance reviewed.",
"Standard procedures followed.",
]
while len(words) < 30:
words.extend(random.choice(padding).split())
base_transcript = " ".join(words[:40])
return base_transcript
def seed_databases():
try:
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()
sql_cur.execute("SET FOREIGN_KEY_CHECKS = 0;")
sql_cur.execute("DROP TABLE IF EXISTS Sales;")
sql_cur.execute("DROP TABLE IF EXISTS ProductsCache;")
sql_cur.execute("DROP TABLE IF EXISTS Customers;")
sql_cur.execute("DROP TABLE IF EXISTS CarePlan;")
sql_cur.execute("DROP TABLE IF EXISTS CallLogs;")
sql_cur.execute("SET FOREIGN_KEY_CHECKS = 1;")
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
);
""")
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),
],
)
sql_cur.execute("""
CREATE TABLE ProductsCache
(
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 4) NOT NULL,
description TEXT
);
""")
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),
],
)
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
);
""")
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), (2, 2, 1, 14.99, 14.99), (3, 3, 3, 24.99, 74.97)],
)
sql_cur.execute("""
CREATE TABLE IF NOT EXISTS CarePlan (
ID INT AUTO_INCREMENT PRIMARY KEY,
ActualReleaseDate DATE,
NameOfYouth VARCHAR(255),
RaceEthnicity VARCHAR(100),
MediCalID VARCHAR(50),
ResidentialAddress TEXT,
Telephone VARCHAR(20),
MediCalHealthPlan VARCHAR(100),
HealthScreenings TEXT,
HealthAssessments TEXT,
ChronicConditions TEXT,
PrescribedMedications TEXT,
Notes TEXT,
CarePlanNotes TEXT,
CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UpdatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
""")
if os.path.exists(TSV_FILE):
df = pd.read_csv(TSV_FILE, sep="\t")
df = df.where(pd.notnull(df), None)
insert_sql = """
INSERT INTO CarePlan (
ActualReleaseDate, NameOfYouth, RaceEthnicity, MediCalID,
ResidentialAddress, Telephone, MediCalHealthPlan, HealthScreenings,
HealthAssessments, ChronicConditions, PrescribedMedications,
Notes, CarePlanNotes
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
for _, row in df.iterrows():
sql_cur.execute(
insert_sql,
(
row.get("ActualReleaseDate"),
row.get("NameOfYouth"),
row.get("RaceEthnicity"),
row.get("MediCalID"),
row.get("ResidentialAddress"),
row.get("Telephone"),
row.get("MediCalHealthPlan"),
row.get("HealthScreenings"),
row.get("HealthAssessments"),
row.get("ChronicConditions"),
row.get("PrescribedMedications"),
row.get("Notes"),
row.get("CarePlanNotes"),
),
)
print(f"✓ Seeded {len(df)} care plans")
else:
print(f"⚠ Skipping care plan seeding - {TSV_FILE} not found")
sql_cur.execute("""
CREATE TABLE IF NOT EXISTS CallLogs (
LogID INT AUTO_INCREMENT PRIMARY KEY,
CallDate DATETIME NOT NULL,
CustomerID INT,
AgentName VARCHAR(100),
CallDuration INT,
CallType VARCHAR(50),
CallStatus VARCHAR(50),
IssueCategory VARCHAR(100),
ResolutionStatus VARCHAR(50),
SentimentScore DECIMAL(3,2),
CallNotes TEXT,
CallTranscript TEXT,
WaitTime INT,
TransferCount INT DEFAULT 0,
FOREIGN KEY (CustomerID) REFERENCES Customers(Id) ON DELETE SET NULL,
INDEX idx_call_date (CallDate),
INDEX idx_customer (CustomerID),
INDEX idx_category (IssueCategory),
FULLTEXT INDEX idx_transcript (CallTranscript)
);
""")
call_log_data = []
agents = [
"Sarah Chen",
"Mike Johnson",
"Emily Davis",
"James Wilson",
"Lisa Anderson",
"David Martinez",
"Jennifer Brown",
"Robert Taylor",
]
call_types = ["inbound", "outbound", "transfer"]
call_statuses = ["completed", "dropped", "voicemail"]
issue_categories = [
"billing",
"technical",
"product_inquiry",
"complaint",
"order_status",
"account",
"refund",
"general",
]
resolution_statuses = ["resolved", "escalated", "pending", "follow_up"]
base_date = datetime.now() - timedelta(days=90)
for i in range(300):
call_date = base_date + timedelta(
days=random.randint(0, 89),
hours=random.randint(8, 20),
minutes=random.randint(0, 59),
)
agent = random.choice(agents)
duration = random.randint(30, 1800)
issue = random.choice(issue_categories)
resolution = random.choice(resolution_statuses)
sentiment = round(random.uniform(-0.5, 1.0), 2)
transcript = generate_call_transcript(
issue, resolution, sentiment, agent, duration
)
call_notes = f"Customer called regarding {issue} issue. {random.choice(['Issue resolved successfully.', 'Escalated to supervisor.', 'Follow-up required.', 'Customer satisfied with resolution.'])}"
call_log_data.append(
(
call_date,
random.randint(1, 3),
agent,
duration,
random.choice(call_types),
random.choice(call_statuses),
issue,
resolution,
sentiment,
call_notes,
transcript,
random.randint(0, 300),
random.randint(0, 3),
)
)
sql_cur.executemany(
"""
INSERT INTO CallLogs (CallDate, CustomerID, AgentName, CallDuration, CallType,
CallStatus, IssueCategory, ResolutionStatus, SentimentScore,
CallNotes, CallTranscript, WaitTime, TransferCount)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""",
call_log_data,
)
sql_cnx.close()
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, 2) NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
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()
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
);
""")
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), (2, 2, 1, 14.99, 14.99), (3, 3, 3, 24.99, 74.97)],
)
sales_cnxn.close()
print("✓ MySQL customers seeded")
print("✓ MySQL products cache seeded")
print("✓ MySQL sales seeded")
print("✓ MySQL care plans seeded")
print("✓ MySQL call logs seeded")
print("✓ PostgreSQL products seeded")
print("✓ PostgreSQL sales seeded")
except FileNotFoundError as e:
print(f"❌ SEED FAILED: Missing file - {e}")
raise
except Exception as e:
print(f"❌ SEED FAILED: {e}")
import traceback
traceback.print_exc()
raise
def get_customer_id_by_name(name: str) -> Optional[int]:
conn = get_mysql_conn()
cursor = conn.cursor()
cursor.execute("SELECT Id FROM Customers WHERE Name = %s", (name,))
result = cursor.fetchone()
conn.close()
return result[0] if result else None
def get_product_id_by_name(name: str) -> Optional[int]:
conn = get_pg_conn()
cursor = conn.cursor()
cursor.execute("SELECT id FROM Products WHERE name = %s", (name,))
result = cursor.fetchone()
conn.close()
return result[0] if result else None
def get_customer_name(customer_id: int) -> str:
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:
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:
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:
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:
try:
mysql_cnxn = get_mysql_conn()
mysql_cur = mysql_cnxn.cursor()
all_matches = []
mysql_cur.execute(
"SELECT Id, Name, Email FROM Customers WHERE LOWER(Name) = LOWER(%s)",
(name,),
)
exact_matches = mysql_cur.fetchall()
if exact_matches:
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:
for match in exact_matches:
all_matches.append(
{
"id": match[0],
"name": match[1],
"email": match[2],
"match_type": "exact_full_name",
}
)
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",
}
)
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()
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"],
}
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:
try:
pg_cnxn = get_pg_conn()
pg_cur = pg_cnxn.cursor()
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}
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}
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)}"}
@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."}
search_name = name.strip()
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:
customers_without_email = [c for c in existing_customers if not c[2]]
customers_with_email = [c for c in existing_customers if c[2]]
if len(existing_customers) == 1:
existing_customer = existing_customers[0]
if existing_customer[2]:
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:
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:
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.",
}
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":
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":
customer_name = None
if not customer_id and name:
try:
customer_info = find_customer_by_name_enhanced(name)
if not customer_info["found"]:
cnxn.close()
return {"sql": None, "result": f"❌ {customer_info['error']}"}
customer_id = customer_info["customer_id"]
customer_name = customer_info["customer_name"]
except Exception as search_error:
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.",
}
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.",
}
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":
customer_name = None
if not customer_id and name:
try:
customer_info = find_customer_by_name_enhanced(name)
if not customer_info["found"]:
cnxn.close()
return {"sql": None, "result": f"❌ {customer_info['error']}"}
customer_id = customer_info["customer_id"]
customer_name = customer_info["customer_name"]
except Exception as search_error:
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:
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