#!/usr/bin/env python3
"""
MCP server for: Create a test MCP with a single hello_world tool that returns a greeting message
Generated by KEN-MCP on 2025-06-27

TODO: Claude, please customize this MCP server based on these requirements:
Create a test MCP with a single hello_world tool that returns a greeting message
Analysis Results:
- Domain: communication
- Primary actions: create, validate, send
- Key entities: message
- Operations: filtering

Instructions:
1. Rename the placeholder tools to match the actual functionality needed
2. Update tool descriptions and parameters based on requirements
3. Implement the actual logic in each tool function
4. Add/remove tools, resources, and prompts as needed
5. Update dependencies in pyproject.toml if additional packages are required

IMPORTANT: If the MCP fails to load in Claude:
- Run: python diagnose.py to check for common issues
- Never use print() statements - use logger.info() instead
- Ensure all output goes to stderr, not stdout
"""

from fastmcp import FastMCP, Context
from fastmcp.exceptions import ToolError
from typing import Dict, List, Any, Optional
from pathlib import Path
import json
import os
import sys
import logging

# CRITICAL: Configure logging to use stderr ONLY - stdout is reserved for MCP protocol
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    stream=sys.stderr  # All logs MUST go to stderr, never stdout!
)
logger = logging.getLogger(__name__)

# Silence any stdout from imported libraries during initialization
_original_stdout = sys.stdout
sys.stdout = sys.stderr  # Temporarily redirect stdout to stderr

# Initialize the MCP server
mcp = FastMCP(
    name="test-ken-hello",
    instructions="""
    MCP server for: Create a test MCP with a single hello_world tool that returns a greeting message
    
    Original Requirements:
    Create a test MCP with a single hello_world tool that returns a greeting message
Analysis Results:
- Domain: communication
- Primary actions: create, validate, send
- Key entities: message
- Operations: filtering
    
    TODO: Claude should update these instructions based on the actual implementation.
    """
)

# Restore stdout for MCP protocol communication
sys.stdout = _original_stdout

# IMPORTANT: From this point on, NEVER use print() statements!
# Use logger.info(), logger.debug(), etc. instead
# Any output to stdout will break the MCP protocol


@mcp.tool
async def create_message(
    ctx: Context,
    message_data: Dict[str, Any],
    validate: bool = True
) -> Dict[str, Any]:
    """Create operation for message.

Domain: communication
Related operations: filtering

TODO: Claude, implement this tool based on the requirements:
Create a test MCP with a single hello_world tool that returns a greeting message

Consider:
- What specific message operations are needed
- What validation should be performed
- What error cases to handle
- What response format makes sense"""
    # Implementation for creating/adding
    try:
        await ctx.info(f"Creating new item...")
        
        # TODO: Validate input data
        # TODO: Create the resource
        # TODO: Return created item with ID
        
        return {
            "status": "success",
            "message": f"Created successfully",
            "id": "generated-id",
            "data": {}
        }
    except Exception as e:
        raise ToolError(f"Failed to create: {e}")

@mcp.tool
async def list_all(
    ctx: Context,
    filter: Optional[Dict[str, Any]]
) -> Dict[str, Any]:
    """List all items in the communication system

TODO: Claude, implement based on requirements"""
    # Implementation for listing/fetching multiple items
    try:
        await ctx.info(f"Fetching items...")
        
        # TODO: Apply filters if provided
        # TODO: Implement pagination
        # TODO: Fetch from data source
        
        items = []  # TODO: Fetch actual items
        
        return {
            "status": "success",
            "count": len(items),
            "items": items,
            "total": len(items)
        }
    except Exception as e:
        raise ToolError(f"Failed to list items: {e}")

@mcp.tool
async def get_status(
    ctx: Context,
    detailed: bool = False
) -> Dict[str, Any]:
    """Get status information for communication

TODO: Claude, implement based on requirements"""
    # Implementation for getting a specific item
    try:
        await ctx.info(f"Fetching item...")
        
        # TODO: Validate ID format
        # TODO: Fetch from data source
        # TODO: Handle not found case
        
        item = {}  # TODO: Fetch actual item
        
        if not item:
            raise ToolError("Item not found")
            
        return {
            "status": "success",
            "data": item
        }
    except Exception as e:
        raise ToolError(f"Failed to get item: {e}")

# Resources - TODO: Claude, implement these based on requirements

@mcp.resource("data://messages")
async def resource_messages() -> List[Dict[str, Any]]:
    """Collection of messages - TODO: Implement based on requirements"""
    # TODO: Implement this resource based on requirements
    # Consider what data should be exposed here
    return [{
        "status": "not_implemented", 
        "message": "TODO: Implement resource for data://messages",
        "description": "Collection of messages - TODO: Implement based on requirements"
    }]

@mcp.resource("data://message/{id}")
async def resource_message_id(id: str) -> List[Dict[str, Any]]:
    """Individual message by ID - TODO: Implement based on requirements"""
    # TODO: Implement this resource based on requirements
    # Consider what data should be exposed here
    return [{
        "status": "not_implemented", 
        "message": "TODO: Implement resource for data://message/{id}",
        "description": "Individual message by ID - TODO: Implement based on requirements"
    }]

@mcp.resource("channels://list")
async def resource_list() -> List[Dict[str, Any]]:
    """Available communication channels - TODO: Implement based on requirements"""
    # TODO: Implement this resource based on requirements
    # Consider what data should be exposed here
    return [{
        "status": "not_implemented", 
        "message": "TODO: Implement resource for channels://list",
        "description": "Available communication channels - TODO: Implement based on requirements"
    }]

@mcp.resource("users://active")
async def resource_active() -> List[Dict[str, Any]]:
    """Active users in the system - TODO: Implement based on requirements"""
    # TODO: Implement this resource based on requirements
    # Consider what data should be exposed here
    return [{
        "status": "not_implemented", 
        "message": "TODO: Implement resource for users://active",
        "description": "Active users in the system - TODO: Implement based on requirements"
    }]

@mcp.resource("system://status")
async def resource_status() -> List[Dict[str, Any]]:
    """System status for communication - TODO: Implement health checks"""
    # TODO: Implement this resource based on requirements
    # Consider what data should be exposed here
    return [{
        "status": "not_implemented", 
        "message": "TODO: Implement resource for system://status",
        "description": "System status for communication - TODO: Implement health checks"
    }]

# Prompts - TODO: Claude, implement these based on requirements

@mcp.prompt
def help(topic: Optional[str]) -> str:
    """Get help with communication operations - TODO: Customize for this MCP"""
    # TODO: Implement this prompt based on requirements
    # Return a string that will be converted to a user message
    # or return a PromptMessage object for more control
    return f"TODO: Implement help prompt - {locals()}"


if __name__ == "__main__":
    mcp.run()
