File size: 2,296 Bytes
bb16d68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
MCP Handler Molecule - MCP server integration for Any2SVG.

Purpose: Handle MCP tool requests and file management
Inputs: MCP tool calls with image data
Outputs: SVG file paths and content
Examples: MCP client calls image_to_svg tool
Edge cases: Large files, network timeouts, invalid URLs
Errors: MCPError, FileNotFoundError, NetworkError
"""

import os
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse

from PIL import Image

from ..atoms.vectorizer import (
    VectorizerConfig,
    image_to_svg_file,
    image_to_svg_string,
)


def get_output_directory() -> Path:
    """
    Get the configured SVG output directory.
    
    Returns:
        Path to output directory (created if needed)
    """
    output_dir = Path(os.environ.get("SVG_OUTPUT_DIR", "./output"))
    output_dir.mkdir(parents=True, exist_ok=True)
    return output_dir


def process_mcp_request(
    image: Image.Image,
    color_mode: str = "color",
    filter_speckle: int = 4,
    color_precision: int = 6,
    save_to_file: bool = True,
) -> dict:
    """
    Process an MCP tool request for image vectorization.
    
    Args:
        image: PIL Image to convert
        color_mode: "color" or "binary"
        filter_speckle: Speckle filter size (1-100)
        color_precision: Color precision bits (1-8)
        save_to_file: Whether to save SVG to file
        
    Returns:
        Dict with 'path' (if saved), 'content', and 'success' keys
    """
    config = VectorizerConfig(
        color_mode=color_mode,
        filter_speckle=filter_speckle,
        color_precision=color_precision,
    )
    
    result = {"success": False, "path": None, "content": None, "error": None}
    
    try:
        if save_to_file:
            output_dir = get_output_directory()
            svg_path = image_to_svg_file(image, output_dir, config=config)
            
            with open(svg_path, "r", encoding="utf-8") as f:
                svg_content = f.read()
            
            result["path"] = str(svg_path)
            result["content"] = svg_content
        else:
            result["content"] = image_to_svg_string(image, config)
        
        result["success"] = True
        
    except Exception as e:
        result["error"] = str(e)
    
    return result