Skip to main content
Glama

generate_code_example

Create before/after code examples for programming concepts like Feature Envy or DRY Principle to demonstrate improvements in technical practices.

Instructions

Generate detailed before/after code examples for a learning topic

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
topicYesThe learning topic (e.g., 'Feature Envy', 'DRY Principle')
languageNoProgramming language for examples (default: javascript)javascript

Implementation Reference

  • Core handler function that generates code examples using Anthropic Claude API. Builds a detailed prompt, calls the API, extracts JSON response, validates, and returns structured CodeExample.
    async generateCodeExample(topic: string, language: string = 'java'): Promise<CodeExample> { const prompt = this.buildCodeExamplePrompt(topic, language); try { const message = await this.client.messages.create({ model: this.model, max_tokens: 4000, messages: [{ role: 'user', content: prompt }] }); const textContent = message.content.find(block => block.type === 'text'); if (!textContent || textContent.type !== 'text') { throw new Error('No text content in response'); } const content = textContent.text; logger.error('Raw response:', content.substring(0, 200) + '...'); // Try to extract JSON from the response const jsonMatch = content.match(/\{[\s\S]*\}$/); if (!jsonMatch) { throw new Error('No valid JSON found in response'); } const exampleData = JSON.parse(jsonMatch[0]); this.validateCodeExample(exampleData); return exampleData; } catch (error) { throw new Error(`Failed to generate code example: ${error instanceof Error ? error.message : String(error)}`); } }
  • MCP server wrapper handler: validates input schema, delegates to LearningHourGenerator, formats MCP response.
    private async generateCodeExample(args: any) { const input = GenerateCodeExampleInputSchema.parse(args); try { const exampleData = await this.generator.generateCodeExample(input.topic, input.language); return { content: [ { type: "text", text: `✅ Code examples generated for: ${input.topic} (${input.language})`, }, { type: "text", text: JSON.stringify(exampleData, null, 2), }, ], }; } catch (error) { throw new Error(`Failed to generate code example: ${error instanceof Error ? error.message : String(error)}`); } }
  • src/index.ts:116-134 (registration)
    Tool registration in MCP server's listTools handler, including name, description, and input schema.
    { name: "generate_code_example", description: "Generate detailed before/after code examples for a learning topic", inputSchema: { type: "object", properties: { topic: { type: "string", description: "The learning topic (e.g., 'Feature Envy', 'DRY Principle')", }, language: { type: "string", description: "Programming language for examples (default: javascript)", default: "javascript" }, }, required: ["topic"], }, },
  • Zod schema for input validation in the wrapper handler.
    const GenerateCodeExampleInputSchema = z.object({ topic: z.string().min(1, "Topic is required"), language: z.string().optional().default("javascript"), });
  • Helper function that constructs the detailed prompt template sent to Anthropic for code generation.
    private buildCodeExamplePrompt(topic: string, language: string): string { return `Create a comprehensive, production-like code example for a Learning Hour on "${topic}" in ${language}. CONTEXT: This example will be used in the Concrete phase of a Learning Hour where participants practice refactoring through hands-on coding. The example must feel realistic and connect to actual problems developers face. LEARNING HOUR PHILOSOPHY: We practice in a safe environment to build muscle memory for technical excellence. Small, incremental improvements with tests give us confidence to refactor production code. REQUIREMENTS: 1. Create a REALISTIC scenario that developers would encounter in production codebases 2. Show MULTIPLE refactoring steps (3-5 steps), not just before/after 3. Include SPECIFIC code smells being addressed at each step 4. Provide TEST CODE alongside production code 5. Add FACILITATION notes for Technical Coaches 6. Demonstrate INCREMENTAL improvements - each step should be small and safe 7. Connect to broader TECHNICAL EXCELLENCE principles IMPORTANT: Return ONLY valid JSON with no additional text or markdown formatting. { "topic": "${topic}", "language": "${language}", "context": "Brief description of the realistic scenario (e.g., 'E-commerce checkout system calculating discounts and taxes')", "problemStatement": "What specific problem does this code exhibit that makes it a good Learning Hour example?", "learningHourConnection": "How does practicing with this example build skills that transfer to participants' daily work?", "refactoringSteps": [ { "stepNumber": 1, "description": "Extract Method - Isolate discount calculation logic", "code": "// Production code for this step\\nclass OrderProcessor {\\n // Show the code after this specific refactoring\\n}", "testCode": "// Test code that validates this step\\n@Test\\nvoid shouldCalculateDiscountCorrectly() {\\n // Test implementation\\n}", "codeSmells": ["Long Method", "Feature Envy", "Comments explaining complex logic"], "improvements": ["Single Responsibility", "Improved testability", "Self-documenting code"], "facilitationTip": "Ask pairs: 'What makes this method easier to test now? How would you test the edge cases?'" }, { "stepNumber": 2, "description": "Replace Conditional with Polymorphism - Different discount strategies", "code": "// Code after introducing strategy pattern\\ninterface DiscountStrategy {\\n // etc.\\n}", "testCode": "// Tests for the new abstraction\\n@Test\\nvoid shouldApplyPercentageDiscount() {\\n // Test implementation\\n}", "codeSmells": ["Switch statements", "Type checking", "Duplicate logic"], "improvements": ["Open/Closed Principle", "Strategy Pattern", "Easier to extend"], "facilitationTip": "Pause here and ask: 'What new discount types could we add without changing existing code?'" }, { "stepNumber": 3, "description": "Introduce Parameter Object - Group related parameters", "code": "// Code with new parameter object\\nclass DiscountContext {\\n // Grouped parameters\\n}", "testCode": "// Tests showing improved clarity\\n@Test\\nvoid shouldCreateDiscountContextWithValidData() {\\n // Test implementation\\n}", "codeSmells": ["Long Parameter List", "Data Clumps", "Primitive Obsession"], "improvements": ["Cohesion", "Domain modeling", "Validation in one place"], "facilitationTip": "Discuss: 'How does grouping these parameters reveal domain concepts we were missing?'" } ], "additionalExercises": [ "Add a new discount type (e.g., loyalty program) using the refactored structure", "Extract validation logic into a separate validator class", "Implement a composite pattern for combining multiple discounts" ], "facilitationNotes": { "timeAllocation": "5 min initial code review, 15 min pair refactoring, 5 min group discussion", "commonMistakes": [ "Trying to refactor everything at once instead of small steps", "Forgetting to run tests between each refactoring", "Getting stuck on naming - encourage 'good enough' names that can be improved later" ], "discussionPoints": [ "Which refactoring step had the biggest impact on code clarity?", "How do these patterns apply to your current codebase?", "What prevented us from writing it this way initially?" ], "pairProgrammingTips": [ "Enforce role switching every 5 minutes using a timer", "Navigator should focus on the current refactoring step, not jump ahead", "Encourage thinking out loud to share mental models", "Celebrate each green test as progress" ] } } CRITICAL DETAILS: - Each refactoring step must compile and pass tests independently - Code should be substantial enough to feel real (not toy examples) - Include ${language}-specific idioms and best practices - Test code should demonstrate TDD thinking - Code smells should be specific and recognizable - Facilitation tips should encourage participant engagement - The progression should tell a story of incremental improvement`; } async generateSessionContent(topic: string, style: string = 'slide'): Promise<SessionContent> { const prompt = this.buildSessionPrompt(topic, style); try { const message = await this.client.messages.create({ model: this.model, max_tokens: 3000, messages: [{ role: 'user', content: prompt }] }); const textContent = message.content.find(block => block.type === 'text'); if (!textContent || textContent.type !== 'text') { throw new Error('No text content in response'); } const content = textContent.text; const sessionData = JSON.parse(content); this.validateSessionContent(sessionData); return sessionData; } catch (error) { throw new Error(`Failed to generate session: ${error instanceof Error ? error.message : String(error)}`); } } async generateCodeExample(topic: string, language: string = 'java'): Promise<CodeExample> { const prompt = this.buildCodeExamplePrompt(topic, language); try { const message = await this.client.messages.create({ model: this.model, max_tokens: 4000, messages: [{ role: 'user', content: prompt }] }); const textContent = message.content.find(block => block.type === 'text'); if (!textContent || textContent.type !== 'text') { throw new Error('No text content in response'); } const content = textContent.text; logger.error('Raw response:', content.substring(0, 200) + '...'); // Try to extract JSON from the response const jsonMatch = content.match(/\{[\s\S]*\}$/); if (!jsonMatch) { throw new Error('No valid JSON found in response'); } const exampleData = JSON.parse(jsonMatch[0]); this.validateCodeExample(exampleData); return exampleData; } catch (error) { throw new Error(`Failed to generate code example: ${error instanceof Error ? error.message : String(error)}`); } }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/SDiamante13/learning-hour-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server