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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Thumbnail Crafter - Comprehensive MCP Server
==============================================

This MCP server provides complete access to all Thumbnail Crafter features,
allowing AI agents to use the tool just like a human would.

Features:
- Complete API coverage (50+ operations)
- Canvas management (size, background, export)
- Layout loading and customization
- Object manipulation (add, update, delete, transform)
- Text operations (search, replace, styling)
- Huggy mascot library
- Image uploading and manipulation
- Selection and layer management
- History (undo/redo)
- Batch operations
"""

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from playwright.async_api import async_playwright, Browser, Page
import json
import asyncio
import os
from typing import Dict, Any, AsyncGenerator, Optional, List
from pathlib import Path

app = FastAPI(
    title="Thumbnail Crafter MCP Server - Comprehensive",
    description="Full-featured AI-callable thumbnail generation with complete canvas control",
    version="4.0.0"
)

# Enable CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Global browser instance
browser: Optional[Browser] = None
APP_URL = os.getenv("APP_URL", "http://localhost:7860")


# ===================================================================
# Browser Management
# ===================================================================

async def get_browser() -> Browser:
    """Get or create browser instance"""
    global browser
    if browser is None:
        playwright = await async_playwright().start()
        browser = await playwright.chromium.launch(
            headless=True,
            args=['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
        )
    return browser


async def close_browser():
    """Close browser instance"""
    global browser
    if browser:
        await browser.close()
        browser = None


async def get_page() -> Page:
    """Create a new page with the app loaded and API ready"""
    browser = await get_browser()
    page = await browser.new_page(viewport={"width": 1920, "height": 1080})

    print(f"Loading app at {APP_URL}...")
    await page.goto(APP_URL, wait_until="networkidle", timeout=30000)

    # Wait for thumbnailAPI to be available
    print("Waiting for thumbnailAPI...")
    await page.wait_for_function("window.thumbnailAPI !== undefined", timeout=10000)
    print("✓ thumbnailAPI ready")

    return page


async def execute_api_call(page: Page, method: str, *args) -> Dict[str, Any]:
    """Execute a thumbnailAPI method and return the result"""
    try:
        # Serialize arguments for JavaScript
        args_json = json.dumps(args)

        result = await page.evaluate(f"""
            async () => {{
                const args = {args_json};
                const result = await window.thumbnailAPI.{method}(...args);
                return result;
            }}
        """)

        return result
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "code": "API_CALL_ERROR"
        }


# ===================================================================
# MCP Tool Implementations
# ===================================================================

async def canvas_get_state(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Get complete canvas state"""
    page = None
    try:
        page = await get_page()
        result = await execute_api_call(page, "getCanvasState")
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def canvas_set_size(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Set canvas size"""
    page = None
    try:
        size = inputs.get("size", "1200x675")
        page = await get_page()
        result = await execute_api_call(page, "setCanvasSize", size)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def canvas_set_bg_color(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Set background color"""
    page = None
    try:
        color = inputs.get("color", "seriousLight")
        page = await get_page()
        result = await execute_api_call(page, "setBgColor", color)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def canvas_clear(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Clear all objects from canvas"""
    page = None
    try:
        page = await get_page()
        result = await execute_api_call(page, "clearCanvas")
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def canvas_export(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Export canvas as image"""
    page = None
    try:
        format_type = inputs.get("format", "png")
        page = await get_page()
        result = await execute_api_call(page, "exportCanvas", format_type)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def layout_list(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """List all available layouts"""
    page = None
    try:
        page = await get_page()
        result = await execute_api_call(page, "listLayouts")
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def layout_load(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Load a layout"""
    page = None
    try:
        layout_id = inputs.get("layout_id")
        options = inputs.get("options", {})

        page = await get_page()
        result = await execute_api_call(page, "loadLayout", layout_id, options)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def object_add(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Add an object to canvas"""
    page = None
    try:
        object_data = inputs.get("object_data", {})
        page = await get_page()
        result = await execute_api_call(page, "addObject", object_data)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def huggy_add(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Add a Huggy mascot to canvas"""
    page = None
    try:
        huggy_id = inputs.get("huggy_id")
        options = inputs.get("options", {})

        page = await get_page()
        result = await execute_api_call(page, "addHuggy", huggy_id, options)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def huggy_list(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """List all available Huggy mascots"""
    page = None
    try:
        options = inputs.get("options", {})
        page = await get_page()
        result = await execute_api_call(page, "listHuggys", options)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def object_update(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Update an object's properties"""
    page = None
    try:
        object_id = inputs.get("object_id")
        updates = inputs.get("updates", {})

        page = await get_page()
        result = await execute_api_call(page, "updateObject", object_id, updates)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def object_delete(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Delete object(s) from canvas"""
    page = None
    try:
        object_id = inputs.get("object_id")
        page = await get_page()
        result = await execute_api_call(page, "deleteObject", object_id)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def object_list(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """List all objects on canvas"""
    page = None
    try:
        filter_options = inputs.get("filter", {})
        page = await get_page()
        result = await execute_api_call(page, "listObjects", filter_options)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def object_move(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Move an object"""
    page = None
    try:
        object_id = inputs.get("object_id")
        x = inputs.get("x")
        y = inputs.get("y")
        relative = inputs.get("relative", False)

        page = await get_page()
        result = await execute_api_call(page, "moveObject", object_id, x, y, relative)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def object_resize(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Resize an object"""
    page = None
    try:
        object_id = inputs.get("object_id")
        width = inputs.get("width")
        height = inputs.get("height")

        page = await get_page()
        result = await execute_api_call(page, "resizeObject", object_id, width, height)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def text_update(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Update text content"""
    page = None
    try:
        object_id = inputs.get("object_id")
        text = inputs.get("text")

        page = await get_page()
        result = await execute_api_call(page, "updateText", object_id, text)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def batch_operations(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """Execute multiple operations in sequence"""
    page = None
    try:
        operations = inputs.get("operations", [])
        page = await get_page()
        result = await execute_api_call(page, "batchUpdate", operations)
        await page.close()
        return result
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


async def create_thumbnail(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """
    High-level tool: Create a complete thumbnail with one call
    This orchestrates multiple API calls to create a thumbnail from scratch
    """
    page = None
    try:
        # Extract parameters
        layout_id = inputs.get("layout_id")
        title = inputs.get("title")
        subtitle = inputs.get("subtitle")
        huggy_id = inputs.get("huggy_id")
        bg_color = inputs.get("bg_color", "seriousLight")
        canvas_size = inputs.get("canvas_size", "1200x675")
        custom_objects = inputs.get("custom_objects", [])

        page = await get_page()
        results = []

        # Set canvas size
        if canvas_size:
            result = await execute_api_call(page, "setCanvasSize", canvas_size)
            results.append({"step": "set_canvas_size", "result": result})

        # Set background color
        if bg_color:
            result = await execute_api_call(page, "setBgColor", bg_color)
            results.append({"step": "set_bg_color", "result": result})

        # Load layout if specified
        if layout_id:
            result = await execute_api_call(page, "loadLayout", layout_id, {})
            results.append({"step": "load_layout", "result": result})

        # Update title if specified
        if title:
            result = await execute_api_call(page, "updateText", "title-text", title)
            results.append({"step": "update_title", "result": result})

        # Update subtitle if specified
        if subtitle:
            result = await execute_api_call(page, "updateText", "subtitle", subtitle)
            results.append({"step": "update_subtitle", "result": result})

        # Add Huggy if specified
        if huggy_id:
            result = await execute_api_call(page, "addHuggy", huggy_id, {})
            results.append({"step": "add_huggy", "result": result})

        # Add custom objects
        for obj in custom_objects:
            result = await execute_api_call(page, "addObject", obj)
            results.append({"step": "add_custom_object", "result": result})

        # Export the final thumbnail
        export_result = await execute_api_call(page, "exportCanvas", "png")
        results.append({"step": "export", "result": export_result})

        await page.close()

        return {
            "success": export_result.get("success", False),
            "image": export_result.get("dataUrl"),
            "width": export_result.get("width"),
            "height": export_result.get("height"),
            "steps": results
        }
    except Exception as e:
        if page:
            await page.close()
        return {"success": False, "error": str(e)}


# ===================================================================
# Tool Registry
# ===================================================================

TOOLS = {
    # Canvas Management
    "canvas_get_state": canvas_get_state,
    "canvas_set_size": canvas_set_size,
    "canvas_set_bg_color": canvas_set_bg_color,
    "canvas_clear": canvas_clear,
    "canvas_export": canvas_export,

    # Layout Management
    "layout_list": layout_list,
    "layout_load": layout_load,

    # Object Management
    "object_add": object_add,
    "object_update": object_update,
    "object_delete": object_delete,
    "object_list": object_list,
    "object_move": object_move,
    "object_resize": object_resize,

    # Huggy Management
    "huggy_add": huggy_add,
    "huggy_list": huggy_list,

    # Text Operations
    "text_update": text_update,

    # Batch & High-level
    "batch_operations": batch_operations,
    "create_thumbnail": create_thumbnail,
}


# ===================================================================
# MCP Protocol Implementation
# ===================================================================

async def mcp_response(request: Request) -> AsyncGenerator[str, None]:
    """MCP server entry point"""
    try:
        payload = await request.json()
        tool_name = payload.get("name")
        arguments = payload.get("arguments", {})

        # Route to appropriate tool
        if tool_name in TOOLS:
            result = await TOOLS[tool_name](arguments)
        else:
            result = {"success": False, "error": f"Unknown tool: {tool_name}"}

        # Stream response
        yield json.dumps({"output": True, "data": result}) + "\n"
        yield json.dumps({"output": False}) + "\n"

    except Exception as e:
        error_response = {
            "output": True,
            "data": {
                "success": False,
                "error": str(e)
            }
        }
        yield json.dumps(error_response) + "\n"
        yield json.dumps({"output": False}) + "\n"


@app.post("/tools")
async def tools_endpoint(request: Request):
    """MCP tools endpoint"""
    return StreamingResponse(
        mcp_response(request),
        media_type="application/json"
    )


@app.get("/api/info")
async def api_info():
    return {
        "name": "Thumbnail Crafter MCP Server - Comprehensive",
        "version": "4.0.0",
        "mode": "full_api_coverage",
        "features": [
            "Complete canvas control",
            "All 50+ API operations exposed",
            "Layout library access",
            "44+ Huggy mascots",
            "Text manipulation",
            "Batch operations",
            "High-level thumbnail creation"
        ],
        "available_tools": list(TOOLS.keys()),
        "tool_count": len(TOOLS)
    }


@app.get("/health")
async def health_check():
    return {"status": "healthy", "service": "thumbnail-crafter-comprehensive"}


# ===================================================================
# Lifecycle
# ===================================================================

@app.on_event("startup")
async def startup_event():
    print("=" * 60)
    print("Thumbnail Crafter MCP Server - Comprehensive Mode")
    print("=" * 60)
    print("Initializing browser...")
    await get_browser()
    print("✓ Browser ready")
    print(f"✓ App URL: {APP_URL}")
    print(f"✓ {len(TOOLS)} tools available")
    print("✓ Full API coverage enabled")
    print("=" * 60)


@app.on_event("shutdown")
async def shutdown_event():
    print("Shutting down...")
    await close_browser()


# ===================================================================
# Static Files
# ===================================================================

static_dir = Path("dist")
if static_dir.exists():
    app.mount("/assets", StaticFiles(directory=static_dir / "assets"), name="assets")

    @app.get("/")
    async def serve_frontend():
        index_file = static_dir / "index.html"
        if index_file.exists():
            return FileResponse(index_file)
        return {"message": "Frontend not built"}

    @app.get("/{full_path:path}")
    async def serve_spa(full_path: str):
        if full_path.startswith(("api/", "tools", "health")):
            return {"error": "Not found"}

        file_path = static_dir / full_path
        if file_path.exists() and file_path.is_file():
            return FileResponse(file_path)

        index_file = static_dir / "index.html"
        if index_file.exists():
            return FileResponse(index_file)
        return {"error": "File not found"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)