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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
"""
Sentiment Evolution Tracker MCP Server
Analyzes sentiment trajectories in conversations to detect opinion changes and predict risks.

Key MCP Protocol Requirements:
1. MUST use stdio_server() for communication with Claude Desktop
2. MUST NOT log to stdout (reserved for protocol messages)
3. MUST log to stderr or file only
4. MUST return TextContent with proper formatting
5. MUST handle async/await correctly
"""

import json
import logging
import asyncio
import sys
import os
from typing import Any

# MCP imports - CRITICAL: correct imports for MCP protocol
from mcp.server import Server
from mcp.server.lowlevel import NotificationOptions
from mcp.server.models import InitializationOptions
from mcp.types import Tool, TextContent
from mcp.server.stdio import stdio_server

# Import analysis modules
from sentiment_analyzer import SentimentAnalyzer
from pattern_detector import PatternDetector
from risk_predictor import RiskPredictor
from database_manager import AnalysisDatabase

# ============================================================================
# LOGGING SETUP - CRITICAL FOR DEBUGGING
# Log to file and stderr ONLY (never stdout - that's for MCP protocol)
# ============================================================================

# Get absolute path for log file
log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'mcp_server.log')

# Configure logging to file
logging.basicConfig(
    filename=log_file,
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Also send errors to stderr (Claude Desktop will capture these)
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
stderr_handler.setFormatter(formatter)
logger.addHandler(stderr_handler)

logger.info("=" * 80)
logger.info("MCP Server starting up")
logger.info(f"Python executable: {sys.executable}")
logger.info(f"Log file: {log_file}")
logger.info("=" * 80)

# ============================================================================
# INITIALIZE MCP SERVER
# ============================================================================

server = Server("sentiment-evolution-tracker")

# Initialize analysis modules - CRITICAL: do this before accepting connections
logger.info("Initializing analysis modules...")
try:
    sentiment_analyzer = SentimentAnalyzer()
    pattern_detector = PatternDetector()
    risk_predictor = RiskPredictor()
    db = AnalysisDatabase()
    logger.info("βœ“ All analysis modules initialized successfully")
    logger.info(f"βœ“ Database: {db.db_path}")
except Exception as e:
    error_msg = f"FATAL: Failed to initialize modules: {str(e)}"
    logger.error(error_msg, exc_info=True)
    sys.stderr.write(error_msg + "\n")
    sys.exit(1)

# ============================================================================
# TOOL DEFINITIONS
# ============================================================================

@server.list_tools()
async def list_tools() -> list[Tool]:
    """List all available tools."""
    logger.debug("list_tools() called by Claude")
    
    tools = [
        Tool(
            name="analyze_sentiment_evolution",
            description="Analyzes sentiment evolution across a series of messages to detect trending patterns (improving, declining, or stable sentiment)",
            inputSchema={
                "type": "object",
                "properties": {
                    "messages": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of messages to analyze, ordered chronologically"
                    }
                },
                "required": ["messages"]
            }
        ),
        Tool(
            name="detect_risk_signals",
            description="Detects risk signals in conversations (competitor mentions, frustration, disengagement, pricing concerns)",
            inputSchema={
                "type": "object",
                "properties": {
                    "messages": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of messages to analyze for risk signals"
                    },
                    "context_type": {
                        "type": "string",
                        "enum": ["customer", "employee", "email"],
                        "description": "Type of conversation context"
                    }
                },
                "required": ["messages", "context_type"]
            }
        ),
        Tool(
            name="predict_next_action",
            description="Predicts the likely next action or outcome based on sentiment and signals (CHURN, RESOLUTION, ESCALATION)",
            inputSchema={
                "type": "object",
                "properties": {
                    "messages": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of messages for analysis"
                    },
                    "context_type": {
                        "type": "string",
                        "enum": ["customer", "employee", "email"],
                        "description": "Type of conversation context"
                    }
                },
                "required": ["messages", "context_type"]
            }
        ),
        Tool(
            name="get_customer_history",
            description="Retrieves historical analysis data for a specific customer, including all previous analyses, trends, and active alerts. THIS REQUIRES DATABASE ACCESS - Claude cannot do this alone!",
            inputSchema={
                "type": "object",
                "properties": {
                    "customer_id": {
                        "type": "string",
                        "description": "Unique customer identifier"
                    }
                },
                "required": ["customer_id"]
            }
        ),
        Tool(
            name="get_high_risk_customers",
            description="Returns list of all customers currently at high risk of churn. THIS REQUIRES DATABASE ACCESS - Claude cannot do this alone!",
            inputSchema={
                "type": "object",
                "properties": {
                    "threshold": {
                        "type": "number",
                        "description": "Risk threshold (0-1, default 0.75)",
                        "default": 0.75
                    }
                },
                "required": []
            }
        ),
        Tool(
            name="get_database_statistics",
            description="Returns overall statistics about analyzed customers and alerts. THIS REQUIRES DATABASE ACCESS - Claude cannot do this alone!",
            inputSchema={
                "type": "object",
                "properties": {}
            }
        ),
        Tool(
            name="save_analysis",
            description="Explicitly save a sentiment analysis with a customer name to the database. Use this to save analysis results with a specific customer identifier.",
            inputSchema={
                "type": "object",
                "properties": {
                    "customer_id": {
                        "type": "string",
                        "description": "Unique customer identifier (e.g., 'LUIS_RAMIREZ', 'CUST_001_ACME')"
                    },
                    "customer_name": {
                        "type": "string",
                        "description": "Customer display name (optional)"
                    },
                    "messages": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of messages in the conversation"
                    },
                    "sentiment_score": {
                        "type": "number",
                        "description": "Overall sentiment score (0-100)"
                    },
                    "trend": {
                        "type": "string",
                        "enum": ["RISING", "DECLINING", "STABLE"],
                        "description": "Sentiment trend"
                    },
                    "risk_level": {
                        "type": "string",
                        "description": "Risk classification (LOW, MEDIUM, HIGH)"
                    },
                    "predicted_action": {
                        "type": "string",
                        "description": "Recommended action (CHURN, RESOLUTION, ESCALATION)"
                    },
                    "confidence": {
                        "type": "number",
                        "description": "Confidence level (0-1.0)"
                    },
                    "context_type": {
                        "type": "string",
                        "enum": ["customer", "employee", "email"],
                        "description": "Type of conversation",
                        "default": "customer"
                    }
                },
                "required": ["customer_id", "messages", "sentiment_score", "trend", "predicted_action", "confidence"]
            }
        )
    ]
    
    logger.info(f"βœ“ Returning {len(tools)} tools to Claude")
    return tools


# ============================================================================
# TOOL HANDLERS
# ============================================================================

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    """
    Execute tool based on name and arguments.
    ALL ERRORS are logged to stderr and file.
    """
    
    try:
        logger.info(f"Tool call received: {name}")
        logger.debug(f"Arguments: {arguments}")
        
        if name == "analyze_sentiment_evolution":
            # Extract messages - must be non-empty
            messages = arguments.get("messages", [])
            if not messages or not isinstance(messages, list):
                error_msg = "Missing or invalid 'messages' parameter (must be non-empty array)"
                logger.warning(f"analyze_sentiment_evolution: {error_msg}")
                return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
            
            logger.info(f"Analyzing sentiment evolution for {len(messages)} messages")
            result = sentiment_analyzer.analyze_evolution(messages)
            
            # Save to database
            customer_id = arguments.get("customer_id", f"customer_{hash(str(messages))}")
            db.save_analysis(customer_id, "conversation", messages, result)
            logger.info(f"βœ“ analyze_sentiment_evolution completed and saved to database")
            
            return [TextContent(type="text", text=json.dumps(result))]
        
        elif name == "detect_risk_signals":
            messages = arguments.get("messages", [])
            context_type = arguments.get("context_type", "customer")
            
            if not messages or not isinstance(messages, list):
                error_msg = "Missing or invalid 'messages' parameter (must be non-empty array)"
                logger.warning(f"detect_risk_signals: {error_msg}")
                return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
            
            if context_type not in ["customer", "employee", "email"]:
                context_type = "customer"
                logger.info(f"Invalid context_type, defaulting to 'customer'")
            
            logger.info(f"Detecting risk signals for {len(messages)} messages (context: {context_type})")
            result = pattern_detector.detect_signals(messages, context_type)
            
            # Save to database
            customer_id = arguments.get("customer_id", f"customer_{hash(str(messages))}")
            db.save_analysis(customer_id, context_type, messages, result)
            logger.info(f"βœ“ detect_risk_signals completed and saved to database")
            
            return [TextContent(type="text", text=json.dumps(result))]
        
        elif name == "predict_next_action":
            messages = arguments.get("messages", [])
            context_type = arguments.get("context_type", "customer")
            
            if not messages or not isinstance(messages, list):
                error_msg = "Missing or invalid 'messages' parameter (must be non-empty array)"
                logger.warning(f"predict_next_action: {error_msg}")
                return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
            
            if context_type not in ["customer", "employee", "email"]:
                context_type = "customer"
                logger.info(f"Invalid context_type, defaulting to 'customer'")
            
            logger.info(f"Predicting next action for {len(messages)} messages (context: {context_type})")
            result = risk_predictor.predict_action(messages, context_type)
            
            # Save to database
            customer_id = arguments.get("customer_id", f"customer_{hash(str(messages))}")
            db.save_analysis(customer_id, context_type, messages, result)
            logger.info(f"βœ“ predict_next_action completed and saved to database")
            
            return [TextContent(type="text", text=json.dumps(result))]
        
        elif name == "get_customer_history":
            customer_id = arguments.get("customer_id", "")
            if not customer_id:
                error_msg = "Missing 'customer_id' parameter"
                logger.warning(f"get_customer_history: {error_msg}")
                return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
            
            logger.info(f"Retrieving history for customer: {customer_id}")
            result = db.get_customer_history(customer_id)
            logger.info(f"βœ“ get_customer_history completed - found {len(result.get('analyses', []))} analyses")
            
            return [TextContent(type="text", text=json.dumps(result))]
        
        elif name == "get_high_risk_customers":
            threshold = float(arguments.get("threshold", 0.75))
            
            logger.info(f"Retrieving high-risk customers (threshold: {threshold})")
            result = db.get_high_risk_customers(threshold)
            logger.info(f"βœ“ get_high_risk_customers completed - found {len(result)} at-risk customers")
            
            return [TextContent(type="text", text=json.dumps({
                'high_risk_customers': result,
                'count': len(result),
                'threshold': threshold
            }))]
        
        elif name == "get_database_statistics":
            logger.info("Retrieving database statistics")
            result = db.get_statistics()
            logger.info(f"βœ“ get_database_statistics completed")
            
            return [TextContent(type="text", text=json.dumps(result))]
        
        elif name == "save_analysis":
            """Save analysis results explicitly with customer identifier"""
            customer_id = arguments.get("customer_id", "")
            if not customer_id:
                error_msg = "Missing 'customer_id' parameter"
                logger.warning(f"save_analysis: {error_msg}")
                return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
            
            messages = arguments.get("messages", [])
            if not messages or not isinstance(messages, list):
                error_msg = "Missing or invalid 'messages' parameter (must be non-empty array)"
                logger.warning(f"save_analysis: {error_msg}")
                return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
            
            # Build analysis dictionary from parameters
            analysis = {
                "current_sentiment": arguments.get("sentiment_score", 50),
                "trend": arguments.get("trend", "STABLE"),
                "risk_level": arguments.get("risk_level", "MEDIUM"),
                "predicted_action": arguments.get("predicted_action", "UNKNOWN"),
                "confidence": arguments.get("confidence", 0.5)
            }
            
            context_type = arguments.get("context_type", "customer")
            if context_type not in ["customer", "employee", "email"]:
                context_type = "customer"
            
            logger.info(f"Saving analysis for customer: {customer_id}")
            logger.debug(f"Analysis data: {analysis}")
            
            # Save to database
            analysis_id = db.save_analysis(customer_id, context_type, messages, analysis)
            
            logger.info(f"βœ“ Analysis saved successfully - ID: {analysis_id}, Customer: {customer_id}")
            
            return [TextContent(type="text", text=json.dumps({
                "success": True,
                "analysis_id": analysis_id,
                "customer_id": customer_id,
                "message": f"Analysis saved for {customer_id} with {len(messages)} messages"
            }))]
        
        else:
            error_msg = f"Unknown tool: {name}"
            logger.error(error_msg)
            return [TextContent(type="text", text=json.dumps({"error": error_msg}))]
    
    except Exception as e:
        error_msg = f"Error in tool {name}: {str(e)}"
        logger.error(error_msg, exc_info=True)
        sys.stderr.write(f"ERROR: {error_msg}\n")
        return [TextContent(type="text", text=json.dumps({"error": error_msg}))]


# ============================================================================
# MAIN SERVER LOOP
# ============================================================================

async def main():
    """
    Run the MCP server with stdio transport.
    This is the CRITICAL function that handles protocol communication.
    
    IMPORTANT: stdio_server() yields a tuple (read_stream, write_stream)
    """
    logger.info("main() called - entering async loop")
    
    try:
        # Use stdio_server context manager for proper protocol handling
        async with stdio_server() as (read_stream, write_stream):
            logger.info("βœ“ stdio_server initialized - streams ready")
            logger.info("βœ“ Creating InitializationOptions...")
            
            # Create initialization options required by MCP protocol
            init_options = InitializationOptions(
                server_name="sentiment-evolution-tracker",
                server_version="1.0.0",
                capabilities=server.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                )
            )
            
            logger.info("βœ“ Connecting to Claude Desktop...")
            logger.info(f"βœ“ Server capabilities: {init_options.capabilities}")
            
            # Start the server with stdin/stdout streams and initialization options
            # This blocks until connection is closed
            await server.run(read_stream, write_stream, init_options)
            
            logger.info("βœ“ Server loop completed (connection closed)")
    
    except Exception as e:
        error_msg = f"Server error in main(): {str(e)}"
        logger.error(error_msg, exc_info=True)
        sys.stderr.write(f"FATAL ERROR: {error_msg}\n")
        raise


# ============================================================================
# ENTRY POINT
# ============================================================================

if __name__ == "__main__":
    logger.info("=" * 80)
    logger.info("MCP Server Process Starting")
    logger.info("=" * 80)
    
    try:
        # Windows compatibility: set event loop policy
        if sys.platform == "win32":
            logger.info("Windows detected - setting WindowsSelectorEventLoopPolicy")
            asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
        
        # Run the server
        logger.info("Calling asyncio.run(main())")
        asyncio.run(main())
        logger.info("MCP Server exited normally")
    
    except KeyboardInterrupt:
        logger.info("Server stopped by user (KeyboardInterrupt)")
        sys.exit(0)
    
    except Exception as e:
        error_msg = f"FATAL ERROR in main process: {str(e)}"
        logger.critical(error_msg, exc_info=True)
        sys.stderr.write(f"\n{error_msg}\n")
        sys.exit(1)