generate_contextual_content
Generate context-aware documentation for source code files using AST analysis and knowledge graph insights, supporting multiple documentation types and formats.
Instructions
Generate context-aware documentation using AST analysis and knowledge graph insights (Phase 3)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | Path to the source code file to document | |
| documentationType | No | Type of Diataxis documentation to generate | reference |
| includeExamples | No | Include code examples in generated documentation | |
| style | No | Documentation detail level | detailed |
| outputFormat | No | Output format for generated content | markdown |
Implementation Reference
- Main handler function that parses args with Zod schema, analyzes source file using ASTAnalyzer, generates contextual documentation sections (reference, tutorial, how-to, explanation), computes metadata, and returns formatted MCPToolResponse.export async function handleGenerateContextualContent( args: unknown, context?: any, ): Promise<{ content: any[] }> { const startTime = Date.now(); try { const { filePath, documentationType, includeExamples, style } = inputSchema.parse(args); await context?.info?.( `📝 Generating ${documentationType} documentation for ${path.basename( filePath, )}...`, ); // Initialize AST analyzer const analyzer = new ASTAnalyzer(); await analyzer.initialize(); // Analyze the file await context?.info?.("🔍 Analyzing code structure..."); const analysis = await analyzer.analyzeFile(filePath); if (!analysis) { throw new Error(`Failed to analyze file: ${filePath}`); } // Query knowledge graph for similar projects await context?.info?.("🧠 Retrieving contextual information..."); const similarProjects = await findSimilarProjects(analysis, context); // Generate documentation sections const sections: GeneratedSection[] = []; if (documentationType === "reference" || documentationType === "all") { sections.push( ...generateReferenceDocumentation(analysis, similarProjects, style), ); } if (documentationType === "tutorial" || documentationType === "all") { sections.push( ...generateTutorialDocumentation( analysis, similarProjects, includeExamples, style, ), ); } if (documentationType === "how-to" || documentationType === "all") { sections.push( ...generateHowToDocumentation( analysis, similarProjects, includeExamples, style, ), ); } if (documentationType === "explanation" || documentationType === "all") { sections.push( ...generateExplanationDocumentation(analysis, similarProjects, style), ); } const metadata: ContentMetadata = { generatedAt: new Date().toISOString(), codeAnalysis: { functions: analysis.functions.length, classes: analysis.classes.length, interfaces: analysis.interfaces.length, complexity: analysis.complexity, }, similarExamples: similarProjects.length, confidence: calculateOverallConfidence(sections), }; const result: GeneratedContent = { filePath, documentationType, sections, metadata, }; const response: MCPToolResponse<typeof result> = { success: true, data: result, metadata: { toolVersion: "3.0.0", executionTime: Date.now() - startTime, timestamp: new Date().toISOString(), }, recommendations: [ { type: "info", title: "Documentation Generated", description: `Generated ${sections.length} documentation section(s) with ${metadata.confidence}% confidence`, }, ], nextSteps: [ { action: "Review generated content", description: "Review and refine generated documentation for accuracy", priority: "high", }, { action: "Add to documentation site", description: "Integrate generated content into your documentation structure", priority: "medium", }, { action: "Validate content", toolRequired: "validate_diataxis_content", description: "Run validation to ensure generated content meets quality standards", priority: "medium", }, ], }; await context?.info?.( `✅ Generated ${sections.length} documentation section(s)`, ); return formatMCPResponse(response, { fullResponse: true }); } catch (error: any) { const errorResponse: MCPToolResponse = { success: false, error: { code: "GENERATION_FAILED", message: `Content generation failed: ${error.message}`, resolution: "Ensure the file path is valid and the file can be parsed", }, metadata: { toolVersion: "3.0.0", executionTime: Date.now() - startTime, timestamp: new Date().toISOString(), }, }; return formatMCPResponse(errorResponse, { fullResponse: true }); } }
- src/tools/generate-contextual-content.ts:758-795 (registration)Tool definition and registration export including name, description, and detailed inputSchema for MCP integration.export const generateContextualContent: Tool = { name: "generate_contextual_content", description: "Generate context-aware documentation using AST analysis and knowledge graph insights (Phase 3)", inputSchema: { type: "object", properties: { filePath: { type: "string", description: "Path to the source code file to document", }, documentationType: { type: "string", enum: ["tutorial", "how-to", "reference", "explanation", "all"], default: "reference", description: "Type of Diataxis documentation to generate", }, includeExamples: { type: "boolean", default: true, description: "Include code examples in generated documentation", }, style: { type: "string", enum: ["concise", "detailed", "verbose"], default: "detailed", description: "Documentation detail level", }, outputFormat: { type: "string", enum: ["markdown", "mdx", "html"], default: "markdown", description: "Output format for generated content", }, }, required: ["filePath"], }, };
- Zod schema for input validation used inside the handler to parse arguments.const inputSchema = z.object({ filePath: z.string().describe("Path to the source code file"), documentationType: z .enum(["tutorial", "how-to", "reference", "explanation", "all"]) .default("reference") .describe("Type of documentation to generate"), includeExamples: z .boolean() .default(true) .describe("Include code examples in generated documentation"), style: z .enum(["concise", "detailed", "verbose"]) .default("detailed") .describe("Documentation style"), outputFormat: z .enum(["markdown", "mdx", "html"]) .default("markdown") .describe("Output format for generated documentation"), });
- TypeScript interface defining the structure of the generated content output.export interface GeneratedContent { filePath: string; documentationType: string; sections: GeneratedSection[]; metadata: ContentMetadata; }
- Helper function to generate reference documentation sections from AST analysis.function generateReferenceDocumentation( analysis: any, _similarProjects: any[], _style: string, ): GeneratedSection[] { const sections: GeneratedSection[] = []; // Generate function reference if (analysis.functions.length > 0) { sections.push(generateFunctionReference(analysis.functions, _style)); } // Generate class reference if (analysis.classes.length > 0) { sections.push(generateClassReference(analysis.classes, _style)); } // Generate interface reference if (analysis.interfaces.length > 0) { sections.push(generateInterfaceReference(analysis.interfaces, _style)); } // Generate type reference if (analysis.types.length > 0) { sections.push(generateTypeReference(analysis.types, _style)); } return sections; }