|
| 1 | +import json |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import Dict, List |
| 4 | +from mcp.server.fastmcp import FastMCP, Context |
| 5 | +from mcp.types import SamplingMessage, TextContent |
| 6 | + |
| 7 | +# Initialize FastMCP server |
| 8 | +mcp = FastMCP("Tools Demo Server") |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class Exercise: |
| 12 | + title: str |
| 13 | + description: str |
| 14 | + hint: str |
| 15 | + solution: str |
| 16 | + difficulty: int |
| 17 | + |
| 18 | +# Store exercises |
| 19 | +exercises_db: Dict[str, List[Exercise]] = {} |
| 20 | + |
| 21 | +@mcp.prompt() |
| 22 | +async def generate_exercises(topic: str, level: str = "beginner") -> str: |
| 23 | + """Generate Python exercises for a given topic and level.""" |
| 24 | + |
| 25 | + return f"""Generate 5 Python exercises on '{topic}' for {level} level. |
| 26 | +
|
| 27 | + Return ONLY valid JSON (no markdown, no extra text): |
| 28 | + {{ |
| 29 | + "{level}": [ |
| 30 | + {{ |
| 31 | + "title": "Exercise Name", |
| 32 | + "description": "What to do", |
| 33 | + "hint": "Helpful hint", |
| 34 | + "solution": "Complete code solution", |
| 35 | + "difficulty": 1 |
| 36 | + }} |
| 37 | + ] |
| 38 | + }} |
| 39 | +
|
| 40 | + Make exercises progressively harder (difficulty 1-5).""" |
| 41 | + |
| 42 | +@mcp.tool() |
| 43 | +async def generate_and_create_exercises( |
| 44 | + topic: str, |
| 45 | + level: str = "beginner", |
| 46 | + ctx: Context = None |
| 47 | +) -> str: |
| 48 | + """Generate exercises using sampling and create them automatically.""" |
| 49 | + |
| 50 | + try: |
| 51 | + # Get the prompt text |
| 52 | + prompt_text = await generate_exercises(topic, level) |
| 53 | + |
| 54 | + response = await ctx.session.create_message( |
| 55 | + messages=[ |
| 56 | + SamplingMessage( |
| 57 | + role="user", |
| 58 | + content=TextContent(type="text", text=prompt_text), |
| 59 | + ) |
| 60 | + ], |
| 61 | + max_tokens=2000, |
| 62 | + ) |
| 63 | + |
| 64 | + # Extract the text from the response |
| 65 | + response_text = response.content.text if response.content else "" |
| 66 | + |
| 67 | + # Parse the generated JSON |
| 68 | + exercises_data = json.loads(response_text) |
| 69 | + |
| 70 | + # Store exercises |
| 71 | + exercises_db[level] = [] |
| 72 | + for ex in exercises_data[level]: |
| 73 | + exercises_db[level].append(Exercise( |
| 74 | + title=ex['title'], |
| 75 | + description=ex['description'], |
| 76 | + hint=ex['hint'], |
| 77 | + solution=ex['solution'], |
| 78 | + difficulty=ex['difficulty'] |
| 79 | + )) |
| 80 | + |
| 81 | + return f"✅ Created {len(exercises_db[level])} exercises on '{topic}' for {level} level" |
| 82 | + |
| 83 | + except json.JSONDecodeError as e: |
| 84 | + return f"❌ JSON Error: {str(e)}\nResponse was: {response_text[:200]}..." |
| 85 | + except Exception as e: |
| 86 | + return f"❌ Error: {str(e)}" |
| 87 | + |
| 88 | +@mcp.tool() |
| 89 | +async def list_exercises() -> str: |
| 90 | + """List all created exercises.""" |
| 91 | + |
| 92 | + if not exercises_db: |
| 93 | + return "No exercises yet. Use generate_and_create_exercises first!" |
| 94 | + |
| 95 | + result = [] |
| 96 | + for level, exercises in exercises_db.items(): |
| 97 | + result.append(f"\n{level.upper()} LEVEL:") |
| 98 | + for i, ex in enumerate(exercises): |
| 99 | + result.append(f"\n{i+1}. {ex.title}") |
| 100 | + result.append(f" 📝 {ex.description}") |
| 101 | + result.append(f" 💡 Hint: {ex.hint}") |
| 102 | + result.append(f" ⭐ Difficulty: {ex.difficulty}/5") |
| 103 | + |
| 104 | + return "\n".join(result) |
| 105 | + |
| 106 | +if __name__ == "__main__": |
| 107 | + import asyncio |
| 108 | + asyncio.run(mcp.run()) |
0 commit comments