File size: 28,651 Bytes
0805c5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
"""
Creative MCP Server

This MCP server provides tools for creative tasks using Hugging Face models:
- Concept Planning (Text LLM)
- Code Generation (Coder LLM)
- Vision Analysis (Vision-Language LLM)
- Text-to-Speech (Audio model)
"""

import asyncio
import base64
import json
import logging
import os
import sys
import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional

# Ensure project root (which contains the `utils` package) is on sys.path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from mcp.server import NotificationOptions, Server
from mcp.server.models import InitializationOptions
from mcp.server.stdio import stdio_server
from mcp.types import (
    CallToolResult,
    ListToolsResult,
    TextContent,
    Tool,
)

from utils.hf_wrapper import HFInferenceWrapper, ModelConfig, get_hf_wrapper

logger = logging.getLogger(__name__)

# Create MCP server
server = Server("neuroanim-creative")

# Global HF wrapper instance
hf_wrapper: Optional[HFInferenceWrapper] = None


class CreativeTool:
    """Base class for creative tools."""

    @staticmethod
    def get_hf_wrapper() -> HFInferenceWrapper:
        """Get or create the HF wrapper instance."""
        global hf_wrapper
        if hf_wrapper is None:
            api_key = os.getenv("HUGGINGFACE_API_KEY")
            hf_wrapper = get_hf_wrapper(api_key=api_key)
        return hf_wrapper


@server.list_tools()
async def list_tools() -> ListToolsResult:
    """List available creative tools."""
    tools = [
        Tool(
            name="plan_concept",
            description="Plan a STEM concept for animation using text LLM",
            inputSchema={
                "type": "object",
                "properties": {
                    "topic": {
                        "type": "string",
                        "description": "The STEM topic to create an animation for",
                    },
                    "target_audience": {
                        "type": "string",
                        "enum": [
                            "elementary",
                            "middle_school",
                            "high_school",
                            "college",
                            "general",
                        ],
                        "description": "Target audience level",
                    },
                    "animation_length_minutes": {
                        "type": "number",
                        "description": "Desired animation length in minutes",
                    },
                    "model": {
                        "type": "string",
                        "description": "Hugging Face model to use (optional, will use default if not provided)",
                    },
                },
                "required": ["topic", "target_audience"],
            },
        ),
        Tool(
            name="generate_manim_code",
            description="Generate Manim Python code for an animation concept",
            inputSchema={
                "type": "object",
                "properties": {
                    "concept": {
                        "type": "string",
                        "description": "The animation concept description",
                    },
                    "scene_description": {
                        "type": "string",
                        "description": "Detailed description of what should happen in the scene",
                    },
                    "visual_elements": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of visual elements to include",
                    },
                    "model": {
                        "type": "string",
                        "description": "Code model to use (optional, will use default if not provided)",
                    },
                },
                "required": ["concept", "scene_description"],
            },
        ),
        Tool(
            name="analyze_frame",
            description="Analyze an animation frame using vision model for quality assessment",
            inputSchema={
                "type": "object",
                "properties": {
                    "image_path": {
                        "type": "string",
                        "description": "Path to the image file to analyze",
                    },
                    "analysis_type": {
                        "type": "string",
                        "enum": [
                            "quality",
                            "content",
                            "educational_value",
                            "clarity",
                        ],
                        "description": "Type of analysis to perform",
                    },
                    "context": {
                        "type": "string",
                        "description": "Context about what should be in the image",
                    },
                    "model": {
                        "type": "string",
                        "description": "Vision model to use (optional, will use default if not provided)",
                    },
                },
                "required": ["image_path", "analysis_type"],
            },
        ),
        Tool(
            name="generate_narration",
            description="Generate narration script for an animation",
            inputSchema={
                "type": "object",
                "properties": {
                    "concept": {
                        "type": "string",
                        "description": "The animation concept",
                    },
                    "scene_description": {
                        "type": "string",
                        "description": "Description of the scene to narrate",
                    },
                    "target_audience": {
                        "type": "string",
                        "enum": [
                            "elementary",
                            "middle_school",
                            "high_school",
                            "college",
                            "general",
                        ],
                        "description": "Target audience",
                    },
                    "duration_seconds": {
                        "type": "number",
                        "description": "Desired narration duration in seconds",
                    },
                    "model": {
                        "type": "string",
                        "description": "Text model to use (optional, will use default if not provided)",
                    },
                },
                "required": ["concept", "scene_description", "target_audience"],
            },
        ),
        Tool(
            name="generate_speech",
            description="Convert text narration to speech audio",
            inputSchema={
                "type": "object",
                "properties": {
                    "text": {
                        "type": "string",
                        "description": "Text to convert to speech",
                    },
                    "voice": {
                        "type": "string",
                        "description": "Voice preference (optional)",
                    },
                    "output_path": {
                        "type": "string",
                        "description": "Path to save the audio file",
                    },
                    "model": {
                        "type": "string",
                        "description": "TTS model to use (optional, will use default if not provided)",
                    },
                },
                "required": ["text", "output_path"],
            },
        ),
        Tool(
            name="refine_animation",
            description="Refine and improve animation based on feedback",
            inputSchema={
                "type": "object",
                "properties": {
                    "original_code": {
                        "type": "string",
                        "description": "Original Manim code",
                    },
                    "feedback": {
                        "type": "string",
                        "description": "Feedback or issues to address",
                    },
                    "improvement_goals": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of improvement goals",
                    },
                    "model": {
                        "type": "string",
                        "description": "Code model to use (optional, will use default if not provided)",
                    },
                },
                "required": ["original_code", "feedback"],
            },
        ),
        Tool(
            name="generate_quiz",
            description="Generate quiz questions based on animation content",
            inputSchema={
                "type": "object",
                "properties": {
                    "concept": {
                        "type": "string",
                        "description": "The STEM concept covered in the animation",
                    },
                    "difficulty": {
                        "type": "string",
                        "enum": ["easy", "medium", "hard"],
                        "description": "Quiz difficulty level",
                    },
                    "num_questions": {
                        "type": "number",
                        "description": "Number of questions to generate",
                    },
                    "question_types": {
                        "type": "array",
                        "items": {
                            "type": "string",
                            "enum": ["multiple_choice", "true_false", "short_answer"],
                        },
                        "description": "Types of questions to include",
                    },
                    "model": {
                        "type": "string",
                        "description": "Text model to use (optional, will use default if not provided)",
                    },
                },
                "required": ["concept", "difficulty", "num_questions"],
            },
        ),
    ]

    return ListToolsResult(tools=tools)


@server.call_tool()
async def call_tool(tool_name: str, arguments: Dict[str, Any]) -> CallToolResult:
    """Dispatch creative tool calls.

    The low-level MCP server passes `(tool_name, arguments)` into this
    handler, so we accept two positional arguments rather than a
    `CallToolRequest` instance.
    """

    try:
        if tool_name == "plan_concept":
            return await plan_concept(arguments)
        elif tool_name == "generate_manim_code":
            return await generate_manim_code(arguments)
        elif tool_name == "analyze_frame":
            return await analyze_frame(arguments)
        elif tool_name == "generate_narration":
            return await generate_narration(arguments)
        elif tool_name == "generate_speech":
            return await generate_speech(arguments)
        elif tool_name == "refine_animation":
            return await refine_animation(arguments)
        elif tool_name == "generate_quiz":
            return await generate_quiz(arguments)
        else:
            return CallToolResult(
                content=[TextContent(type="text", text=f"Unknown tool: {tool_name}")],
                isError=True,
            )
    except Exception as e:
        logger.error(f"Error in tool {tool_name}: {e}")
        return CallToolResult(
            content=[TextContent(type="text", text=f"Error: {str(e)}")],
            isError=True,
        )


async def plan_concept(arguments: Dict[str, Any]) -> CallToolResult:
    """Plan a STEM concept for animation."""
    topic = arguments["topic"]
    target_audience = arguments["target_audience"]
    animation_length = arguments.get("animation_length_minutes", 2.0)
    model = arguments.get("model")

    try:
        wrapper = CreativeTool.get_hf_wrapper()
        model_config = ModelConfig()
        selected_model = model or model_config.text_models[0]

        prompt = f"""
                You are a STEM Curriculum Designer. Create a structured animation plan.

                Topic: {topic}
                Audience: {target_audience}
                Length: {animation_length} min

                Return a valid JSON object with exactly these keys:
                {{
                    "learning_objectives": ["string", "string"],
                    "visual_metaphors": ["string", "string"],
                    "scene_flow": [
                        {{
                            "timestamp": "0:00-0:30",
                            "action": "description of visual action",
                            "voiceover": "key narration points"
                        }}
                    ],
                    "estimated_educational_value": "string"
                }}

                Do not include markdown formatting like ```json. Return raw JSON only.
                """

        response = await wrapper.text_generation(
            model=selected_model,
            prompt=prompt,
            max_new_tokens=1024,
            temperature=0.7,
        )

        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Animation Concept Plan:\n\n{response}",
                )
            ]
        )

    except Exception as e:
        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Concept planning failed: {str(e)}",
                )
            ],
            isError=True,
        )


async def generate_manim_code(arguments: Dict[str, Any]) -> CallToolResult:
    """Generate Manim Python code."""
    concept = arguments["concept"]
    scene_description = arguments["scene_description"]
    visual_elements = arguments.get("visual_elements", [])
    model = arguments.get("model")
    previous_code = arguments.get("previous_code")
    error_message = arguments.get("error_message")

    try:
        wrapper = CreativeTool.get_hf_wrapper()
        model_config = ModelConfig()
        selected_model = model or model_config.code_models[0]

        # Build base prompt
        if previous_code and error_message:
            # This is a retry - include error feedback
            prompt = f"""
You are an expert animation engineer using Manim Community Edition (v0.18.0+).

The previous code attempt had an error. Your task is to FIX the code.

PREVIOUS CODE:
```python
{previous_code}
```

ERROR ENCOUNTERED:
{error_message}

TASK: Fix the error in the code above. Pay special attention to:
- Closing all parentheses, brackets, and braces
- Completing all function calls
- Proper indentation
- Valid Python syntax

Concept: {concept}
Scene Description: {scene_description}
Visual Elements: {", ".join(visual_elements)}

STRICT CODE REQUIREMENTS:
1. Header: MUST start with `from manim import *`
2. Class Structure: Define a class inheriting from `MovingCameraScene` (use this instead of `Scene` to enable camera zoom/pan with `self.camera.frame`)
3. Method: All logic must be inside the `def construct(self):` method
4. SYNTAX: Ensure ALL parentheses, brackets, and function calls are properly closed
5. Colors: Use ONLY valid Manim colors (WHITE, BLACK, RED, GREEN, BLUE, YELLOW, ORANGE, PINK, PURPLE, TEAL, GOLD, etc.)
6. Text: Use `Text()` objects for strings
7. Positioning: Use `.next_to()`, `.move_to()`, or `.shift()`
8. Animations: Use Write(), Create(), FadeIn(), FadeOut(), Transform(), Flash(), Indicate() - capitalize properly!
9. Pacing: Include `self.wait(1)` between animations

OUTPUT FORMAT:
Provide ONLY the complete, corrected Python code. No markdown blocks. No explanations.
"""
        else:
            # First attempt - generate fresh code
            prompt = f"""
You are an expert animation engineer using Manim Community Edition (v0.18.0+).
Generate a complete, runnable Python script for the following request.

Concept: {concept}
Scene Description: {scene_description}
Visual Elements: {", ".join(visual_elements)}

STRICT CODE REQUIREMENTS:
1. Header: MUST start with `from manim import *`
2. Class Structure: Define a class inheriting from `MovingCameraScene` (e.g., `class GenScene(MovingCameraScene):`) - this enables camera operations like zoom/pan via `self.camera.frame`
3. Method: All logic must be inside the `def construct(self):` method
4. SYNTAX: Ensure ALL parentheses, brackets, and function calls are properly closed
5. Colors: Use ONLY these valid Manim color constants:
   - Basic: WHITE, BLACK, GRAY, GREY, LIGHT_GRAY, DARK_GRAY
   - Primary: RED, GREEN, BLUE, YELLOW, ORANGE, PINK, PURPLE, TEAL, GOLD, MAROON
   - Variants: RED_A, RED_B, RED_C, RED_D, RED_E, GREEN_A, GREEN_B, GREEN_C, GREEN_D, GREEN_E,
     BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E, YELLOW_A, YELLOW_B, YELLOW_C, YELLOW_D, YELLOW_E
   - NEVER use: DARK_GREEN, LIGHT_GREEN, DARK_BLUE, LIGHT_BLUE, DARK_RED, LIGHT_RED (these don't exist!)
6. Text: Use `Text()` objects for strings. Avoid `Tex()` or `MathTex()` unless necessary
7. Positioning: Use `.next_to()`, `.move_to()`, or `.shift()` to arrange elements
8. Animations: Use ONLY these valid animations:
   - Write(), Create(), FadeIn(), FadeOut(), GrowFromCenter(), ShrinkToCenter()
   - Transform(), ReplacementTransform(), MoveToTarget(), ApplyMethod()
   - Rotate(), Indicate(), Flash(), ShowCreation() - DO NOT use lowercase like 'flash'
   - For custom effects use .animate.method() (e.g., obj.animate.scale(2), obj.animate.shift(UP))
9. Pacing: Include `self.wait(1)` between major animation groups

OUTPUT FORMAT:
Provide ONLY the raw Python code. Do not wrap in markdown blocks (no ```python). Do not include conversational text.
"""

        response = await wrapper.text_generation(
            model=selected_model,
            prompt=prompt,
            max_new_tokens=2048,
            temperature=0.3,
        )

        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Generated Manim Code:\n\n```python\n{response}\n```",
                )
            ]
        )

    except Exception as e:
        return CallToolResult(
            content=[
                TextContent(type="text", text=f"Code generation failed: {str(e)}")
            ],
            isError=True,
        )


async def analyze_frame(arguments: Dict[str, Any]) -> CallToolResult:
    """Analyze an animation frame."""
    image_path = arguments["image_path"]
    analysis_type = arguments["analysis_type"]
    context = arguments.get("context", "")
    model = arguments.get("model")

    try:
        wrapper = CreativeTool.get_hf_wrapper()
        model_config = ModelConfig()
        selected_model = model or model_config.vision_models[0]

        with open(image_path, "rb") as f:
            image_bytes = f.read()

        prompt = f"""
        Analyze this {analysis_type} for an educational animation frame.
        Context: {context}

        Provide specific feedback on:
        {analysis_type.replace("_", " ").title()} assessment
        Educational effectiveness
        Visual clarity
        Suggestions for improvement
        """

        response = await wrapper.vision_analysis(
            model=selected_model,
            image=image_bytes,
            text=prompt,
        )

        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Frame Analysis ({analysis_type}):\n\n{response}",
                )
            ]
        )

    except Exception as e:
        return CallToolResult(
            content=[TextContent(type="text", text=f"Frame analysis failed: {str(e)}")],
            isError=True,
        )


async def generate_narration(arguments: Dict[str, Any]) -> CallToolResult:
    """Generate narration script."""
    concept = arguments["concept"]
    scene_description = arguments["scene_description"]
    target_audience = arguments["target_audience"]
    duration = arguments.get("duration_seconds", 30)
    model = arguments.get("model")

    try:
        wrapper = CreativeTool.get_hf_wrapper()
        model_config = ModelConfig()
        selected_model = model or model_config.text_models[0]

        prompt = f"""
        Generate a narration script for an educational animation:

        Concept: {concept}
        Scene: {scene_description}
        Target Audience: {target_audience}
        Duration: {duration} seconds

        Requirements:
        1. Clear, engaging, and age-appropriate language
        2. Educational value aligned with learning objectives
        3. Natural speaking pace (approximately {duration / 150} words for {duration} seconds)
        4. Include pauses and emphasis markers where appropriate
        5. Make it interesting and memorable

        Format as a clean script ready for text-to-speech.
        """

        response = await wrapper.text_generation(
            model=selected_model,
            prompt=prompt,
            max_new_tokens=512,
            temperature=0.6,
        )

        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Narration Script:\n\n{response}",
                )
            ]
        )

    except Exception as e:
        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Narration generation failed: {str(e)}",
                )
            ],
            isError=True,
        )


async def generate_speech(arguments: Dict[str, Any]) -> CallToolResult:
    """Convert text to speech."""
    text = arguments["text"]
    voice = arguments.get("voice")
    output_path = arguments["output_path"]
    model = arguments.get("model")

    try:
        wrapper = CreativeTool.get_hf_wrapper()
        model_config = ModelConfig()
        selected_model = model or model_config.tts_models[0]

        # Generate audio
        audio_bytes = await wrapper.text_to_speech(
            model=selected_model,
            text=text,
            voice=voice,
        )

        # Save to file
        success = await wrapper.save_audio_to_file(audio_bytes, output_path)

        if not success:
            raise Exception("Failed to save audio file")

        # Return audio info
        audio_info = {
            "output_path": output_path,
            "text_length": len(text),
            "estimated_duration": len(text) / 150,  # Rough estimate
            "model_used": selected_model,
        }

        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Speech generated successfully!\n\n{json.dumps(audio_info, indent=2)}",
                )
            ]
        )

    except Exception as e:
        return CallToolResult(
            content=[
                TextContent(type="text", text=f"Speech generation failed: {str(e)}")
            ],
            isError=True,
        )


async def refine_animation(arguments: Dict[str, Any]) -> CallToolResult:
    """Refine animation code based on feedback."""
    original_code = arguments["original_code"]
    feedback = arguments["feedback"]
    improvement_goals = arguments.get("improvement_goals", [])
    model = arguments.get("model")

    try:
        wrapper = CreativeTool.get_hf_wrapper()
        model_config = ModelConfig()
        selected_model = model or model_config.code_models[0]

        prompt = f"""
                You are a Manim Code Repair Agent. Your task is to rewrite the FULL Python script to fix issues or apply improvements.

                Previous Code:
                {original_code}

                User Feedback/Error:
                {feedback}

                Improvement Goals:
                {", ".join(improvement_goals)}

                INSTRUCTIONS:
                1. Output the COMPLETE corrected script, including `from manim import *`.
                2. Do not output diffs or partial snippets.
                3. Ensure the class inherits from `MovingCameraScene` and uses `def construct(self):`.
                4. Fix logic errors based on the feedback.
                5. Animations: Use ONLY valid animations like Write(), FadeIn(), FadeOut(), Create(), Flash(), Transform() - NEVER lowercase!
                6. Colors: Use ONLY these valid Manim color constants:
                   - Basic: WHITE, BLACK, GRAY, GREY, LIGHT_GRAY, DARK_GRAY
                   - Primary: RED, GREEN, BLUE, YELLOW, ORANGE, PINK, PURPLE, TEAL, GOLD, MAROON
                   - Variants: RED_A, RED_B, RED_C, RED_D, RED_E, GREEN_A, GREEN_B, GREEN_C, GREEN_D, GREEN_E,
                     BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E, YELLOW_A, YELLOW_B, YELLOW_C, YELLOW_D, YELLOW_E
                   - NEVER use: DARK_GREEN, LIGHT_GREEN, DARK_BLUE, LIGHT_BLUE, DARK_RED, LIGHT_RED (these don't exist!)
                   - For darker/lighter variants, use the letter suffixes (e.g., GREEN_E for dark green, GREEN_A for light green).

                OUTPUT:
                Return ONLY the raw Python code. No markdown backticks. No explanation.
                """

        response = await wrapper.text_generation(
            model=selected_model,
            prompt=prompt,
            max_new_tokens=2048,
            temperature=0.3,
        )

        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Refined Manim Code:\n\n```python\n{response}\n```",
                )
            ]
        )

    except Exception as e:
        return CallToolResult(
            content=[
                TextContent(type="text", text=f"Code refinement failed: {str(e)}")
            ],
            isError=True,
        )


async def generate_quiz(arguments: Dict[str, Any]) -> CallToolResult:
    """Generate quiz questions."""
    concept = arguments["concept"]
    difficulty = arguments["difficulty"]
    num_questions = arguments["num_questions"]
    question_types = arguments.get("question_types", ["multiple_choice"])
    model = arguments.get("model")

    try:
        wrapper = CreativeTool.get_hf_wrapper()
        model_config = ModelConfig()
        selected_model = model or model_config.text_models[0]

        prompt = f"""
        Generate {num_questions} quiz questions for the following STEM concept:

        Concept: {concept}
        Difficulty: {difficulty}
        Question Types: {", ".join(question_types)}

        For each question provide:
        1. The question
        2. Possible answers (for multiple choice)
        3. Correct answer
        4. Brief explanation

        Format as JSON array of question objects.
        """

        response = await wrapper.text_generation(
            model=selected_model,
            prompt=prompt,
            max_new_tokens=1024,
            temperature=0.5,
        )

        return CallToolResult(
            content=[
                TextContent(
                    type="text",
                    text=f"Generated Quiz Questions:\n\n{response}",
                )
            ]
        )

    except Exception as e:
        return CallToolResult(
            content=[
                TextContent(type="text", text=f"Quiz generation failed: {str(e)}")
            ],
            isError=True,
        )


async def main():
    """Main entry point for the creative MCP server."""
    # Set up logging
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )

    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="neuroanim-creative",
                server_version="0.1.0",
                capabilities=server.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                ),
            ),
        )


if __name__ == "__main__":
    asyncio.run(main())