Skip to main content
Glama

generate_code_example

Create before-and-after code examples for learning topics to illustrate concepts like 'Feature Envy' or 'DRY Principle' in a specified programming language, enhancing technical coaching sessions.

Instructions

Generate detailed before/after code examples for a learning topic

Input Schema

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

Implementation Reference

  • The main handler function for the 'generate_code_example' tool. Validates input arguments using Zod schema, delegates to LearningHourGenerator to generate the code example, and formats the MCP response with the generated content.
    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)}`); } }
  • Zod input schema for validating tool arguments: requires 'topic' string, optional 'language' defaulting to 'javascript'.
    const GenerateCodeExampleInputSchema = z.object({ topic: z.string().min(1, "Topic is required"), language: z.string().optional().default("javascript"), });
  • src/index.ts:117-134 (registration)
    Tool registration in the ListTools response, defining name, description, and input schema matching the Zod 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"], }, },
  • Core helper method in LearningHourGenerator that builds a detailed prompt, calls Anthropic Claude AI model to generate structured code examples, extracts and validates the JSON response conforming to CodeExample interface.
    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)}`); } }
  • TypeScript interface defining the structure of the generated CodeExample output, used for validation and typing.
    export interface CodeExample { topic: string; language: string; context: string; refactoringSteps: RefactoringStep[]; problemStatement: string; learningHourConnection: string; additionalExercises: string[]; facilitationNotes: { timeAllocation: string; commonMistakes: string[]; discussionPoints: string[]; pairProgrammingTips: string[]; }; }

Other Tools

Related 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