generate_context
Create context files in various formats from codebases to help AI assistants understand project structure and dependencies.
Instructions
Generate context files in specified format for the codebase
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Root directory path | |
| format | Yes | Context file format to generate | |
| output_path | No | Output path for generated files (optional) | |
| analysis_result | No | Previous analysis result to use (optional) | |
| options | No | Format-specific options |
Implementation Reference
- src/tools/generate-context.ts:21-112 (handler)Main handler function that executes the generate_context tool logic: analyzes codebase if needed, optionally enriches with KG, generates format-specific context content, writes to file if specified, and returns success response.
export async function generateContext( args: GenerateContextArgs ): Promise<{ content: Array<{ type: string; text: string }> }> { const { path, format, output_path, analysis_result, options = {} } = args; // Get or perform analysis let analysis = analysis_result; if (!analysis) { const analyzeResult = await analyzeCodebase({ path }); analysis = JSON.parse(analyzeResult.content[0].text); } // Enrich with knowledge graph if enabled (default: true) let enriched: EnrichedContext | null = null; if (options.enable_kg !== false) { enriched = await enrichContext({ path, analysis_result: analysis, enrichment_level: options.enrichment_level || 'standard', include_yago: options.include_yago !== false, include_schema: options.include_schema !== false, max_entities: options.max_entities || 10, }); } // Generate context based on format let content: string; let filename: string; switch (format) { case 'cursorrules': content = generateCursorRules(analysis, enriched); filename = '.cursorrules'; break; case 'cursor_dir': content = generateCursorDir(analysis, enriched); filename = '.cursor/context.md'; break; case 'spec_md': content = generateSpecMd(analysis, enriched); filename = 'SPEC.md'; break; case 'agents_md': content = generateAgentsMd(analysis, enriched); filename = 'AGENTS.md'; break; case 'custom': content = generateCustom(analysis, enriched, options); filename = options.filename || 'context.md'; break; default: throw new Error(`Unknown format: ${format}`); } // Write to file if output_path specified if (output_path) { const fullPath = join(output_path, filename); const dir = dirname(fullPath); if (!existsSync(dir)) { await mkdir(dir, { recursive: true }); } await writeFile(fullPath, content, 'utf-8'); } return { content: [ { type: 'text', text: JSON.stringify( { message: 'Context generated successfully', format, path, output_file: output_path ? join(output_path, filename) : null, content_preview: content.slice(0, 500) + '...', enriched: !!enriched, kg_stats: enriched?.confidence_stats, }, null, 2 ), }, ], }; } - src/tools/generate-context.ts:13-19 (schema)TypeScript interface defining the input arguments for the generateContext handler.
interface GenerateContextArgs { path: string; format: 'cursorrules' | 'cursor_dir' | 'spec_md' | 'agents_md' | 'custom'; output_path?: string; analysis_result?: any; options?: Record<string, any>; } - src/tools/index.ts:43-44 (registration)Tool dispatch/registration in the switch statement handling CallToolRequestSchema, calling generateContext for "generate_context".
case "generate_context": return await generateContext(args as any); - src/index.ts:140-169 (registration)Tool registration in ListToolsRequestSchema response, defining name, description, and inputSchema for MCP protocol compliance.
name: "generate_context", description: "Generate context files in specified format for the codebase", inputSchema: { type: "object", properties: { path: { type: "string", description: "Root directory path", }, format: { type: "string", enum: ["cursorrules", "cursor_dir", "spec_md", "agents_md", "custom"], description: "Context file format to generate", }, output_path: { type: "string", description: "Output path for generated files (optional)", }, analysis_result: { type: "object", description: "Previous analysis result to use (optional)", }, options: { type: "object", description: "Format-specific options", }, }, required: ["path", "format"], }, }, - Helper function to generate content in '.cursorrules' format, one of several format-specific generators used by the handler.
function generateCursorRules(analysis: any, enriched: EnrichedContext | null): string { const lines: string[] = []; lines.push('# Project Rules for AI Assistants'); lines.push(''); // Project info if (analysis.package?.name) { lines.push(`## Project: ${analysis.package.name}`); if (analysis.package.description) { lines.push(analysis.package.description); } lines.push(''); } // Schema.org annotation if (enriched?.schema_annotation) { lines.push('## Semantic Type'); lines.push(`This is a **${enriched.schema_annotation['@type']}**`); if (enriched.schema_annotation.description) { lines.push(enriched.schema_annotation.description); } lines.push(''); } // Tech stack lines.push('## Tech Stack'); if (analysis.languages) { lines.push('**Languages:**', Object.keys(analysis.languages).join(', ')); } if (analysis.frameworks && analysis.frameworks.length > 0) { lines.push('**Frameworks:**', analysis.frameworks.join(', ')); } lines.push(''); // Knowledge graph enrichment if (enriched?.yago_entities && Object.keys(enriched.yago_entities).length > 0) { lines.push('## Knowledge Graph Context'); for (const [name, entities] of Object.entries(enriched.yago_entities)) { if (entities.length > 0) { const entity = entities[0]; lines.push(`- **${name}**: ${entity.description || entity.label}`); } } lines.push(''); } // Coding conventions lines.push('## Coding Conventions'); lines.push('- Follow existing patterns in the codebase'); lines.push('- Use TypeScript strict mode'); lines.push('- Write clear, self-documenting code'); lines.push('- Add JSDoc comments for public APIs'); lines.push(''); return lines.join('\n'); }