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
| Name | Required | Description | Default |
|---|---|---|---|
| language | No | Programming language for examples (default: javascript) | javascript |
| topic | Yes | The learning topic (e.g., 'Feature Envy', 'DRY Principle') |
Implementation Reference
- src/index.ts:292-313 (handler)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)}`); } }
- src/index.ts:25-28 (schema)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"], }, },
- src/LearningHourGenerator.ts:410-443 (helper)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)}`); } }
- src/LearningHourGenerator.ts:48-62 (helper)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[]; }; }