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)}`);
        }
      }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool generates examples but doesn't describe output format, potential rate limits, authentication needs, or error handling. For a tool with no annotations, this leaves significant behavioral gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core purpose without unnecessary details. It uses minimal words to convey the essential action and scope, earning its place with zero waste.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (2 parameters, no output schema, no annotations), the description is minimally adequate. It covers the purpose but lacks behavioral details and usage guidelines. Without annotations or output schema, more context on what the generated examples look like would improve completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents both parameters ('topic' and 'language') with clear descriptions. The description adds no additional parameter semantics beyond what the schema provides, such as example topics beyond those listed or language constraints. Baseline 3 is appropriate when schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Generate detailed before/after code examples for a learning topic.' It specifies the verb ('generate'), resource ('code examples'), and scope ('before/after' for learning topics). However, it doesn't explicitly differentiate from sibling tools like 'analyze_repository' or 'generate_session', which could have overlapping educational purposes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites, exclusions, or compare it to sibling tools like 'generate_session' or 'analyze_tech_stack' that might serve similar educational contexts. Usage is implied only by the purpose statement.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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