any2svg / dna /molecules /mcp_handler.py
nbiish
Add Any2SVG - Image to SVG vectorization with MCP server support
bb16d68 unverified
"""
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