suggest_adrs
Generate architectural decision records (ADRs) by analyzing project code, changes, and context. Utilize advanced prompting, domain insights, and learning capabilities to suggest tailored decisions for your project phase and goals.
Instructions
Suggest architectural decisions with advanced prompting techniques (Knowledge Generation + Reflexion)
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| afterCode | No | Code after changes (for code_changes analysis) | |
| analysisType | No | Type of analysis to perform | comprehensive |
| beforeCode | No | Code before changes (for code_changes analysis) | |
| changeDescription | No | Description of the changes (for code_changes analysis) | |
| commitMessages | No | Related commit messages (for code_changes analysis) | |
| conversationContext | No | Rich context from the calling LLM about user goals and discussion history | |
| enhancedMode | No | Enable advanced prompting features (Knowledge Generation + Reflexion) | |
| existingAdrs | No | List of existing ADR titles to avoid duplication | |
| knowledgeEnhancement | No | Enable Knowledge Generation for domain-specific insights | |
| learningEnabled | No | Enable Reflexion learning from past experiences | |
| projectPath | No | Path to the project directory | . |
Input Schema (JSON Schema)
{
"properties": {
"afterCode": {
"description": "Code after changes (for code_changes analysis)",
"type": "string"
},
"analysisType": {
"default": "comprehensive",
"description": "Type of analysis to perform",
"enum": [
"implicit_decisions",
"code_changes",
"comprehensive"
],
"type": "string"
},
"beforeCode": {
"description": "Code before changes (for code_changes analysis)",
"type": "string"
},
"changeDescription": {
"description": "Description of the changes (for code_changes analysis)",
"type": "string"
},
"commitMessages": {
"description": "Related commit messages (for code_changes analysis)",
"items": {
"type": "string"
},
"type": "array"
},
"conversationContext": {
"additionalProperties": false,
"description": "Rich context from the calling LLM about user goals and discussion history",
"properties": {
"budget": {
"description": "Budget or resource constraints (e.g., \"limited budget\", \"enterprise scale\")",
"type": "string"
},
"constraints": {
"description": "Limitations, compliance requirements, or restrictions (e.g., [\"GDPR compliance\", \"budget under $50k\", \"minimal downtime\"])",
"items": {
"type": "string"
},
"type": "array"
},
"focusAreas": {
"description": "Specific areas of concern or interest (e.g., [\"security\", \"performance\", \"maintainability\"])",
"items": {
"type": "string"
},
"type": "array"
},
"humanRequest": {
"description": "Original human request text for context restoration and knowledge graph storage",
"type": "string"
},
"previousContext": {
"description": "Relevant context from previous conversation (e.g., \"User mentioned concerns about database splitting\")",
"type": "string"
},
"projectPhase": {
"description": "Current project phase (e.g., \"planning\", \"development\", \"migration\", \"production\")",
"type": "string"
},
"requirements": {
"description": "Specific requirements or preferences mentioned",
"items": {
"type": "string"
},
"type": "array"
},
"timeline": {
"description": "Timeline or urgency information (e.g., \"launch in 3 months\", \"urgent migration\")",
"type": "string"
},
"userGoals": {
"description": "Primary objectives the user wants to achieve (e.g., [\"microservices migration\", \"improve security\"])",
"items": {
"type": "string"
},
"type": "array"
},
"userRole": {
"description": "User's role or expertise level (e.g., \"senior architect\", \"developer\", \"project manager\")",
"type": "string"
}
},
"type": "object"
},
"enhancedMode": {
"default": true,
"description": "Enable advanced prompting features (Knowledge Generation + Reflexion)",
"type": "boolean"
},
"existingAdrs": {
"description": "List of existing ADR titles to avoid duplication",
"items": {
"type": "string"
},
"type": "array"
},
"knowledgeEnhancement": {
"default": true,
"description": "Enable Knowledge Generation for domain-specific insights",
"type": "boolean"
},
"learningEnabled": {
"default": true,
"description": "Enable Reflexion learning from past experiences",
"type": "boolean"
},
"projectPath": {
"default": ".",
"description": "Path to the project directory",
"type": "string"
}
},
"type": "object"
}
Implementation Reference
- src/tools/adr-suggestion-tool.ts:25-931 (handler)Primary handler function for the 'suggest_adrs' tool. Implements ADR suggestion logic for implicit decisions, code changes, and comprehensive project analysis. Integrates advanced AI features including knowledge generation, reflexion self-improvement, tree-sitter parsing, research orchestration, and enhanced prompting.export async function suggestAdrs(args: { projectPath?: string; analysisType?: 'implicit_decisions' | 'code_changes' | 'comprehensive'; beforeCode?: string; afterCode?: string; changeDescription?: string; commitMessages?: string[]; existingAdrs?: string[]; enhancedMode?: boolean; // Enable advanced prompting features learningEnabled?: boolean; // Enable Reflexion learning knowledgeEnhancement?: boolean; // Enable Knowledge Generation enableTreeSitterAnalysis?: boolean; // Enable tree-sitter for enhanced code analysis conversationContext?: ConversationContext; // Context from calling LLM }): Promise<any> { const { projectPath = process.cwd(), analysisType = 'comprehensive', beforeCode, afterCode, changeDescription, commitMessages, existingAdrs, enhancedMode = true, // Default to enhanced mode learningEnabled = true, // Default to learning enabled knowledgeEnhancement = true, // Default to knowledge enhancement enableTreeSitterAnalysis = true, // Default to tree-sitter enabled conversationContext, // Context from calling LLM } = args; try { const { analyzeImplicitDecisions, analyzeCodeChanges } = await import( '../utils/adr-suggestions.js' ); switch (analysisType) { case 'implicit_decisions': { let enhancedPrompt = ''; let enhancementInfo = ''; let codeContext = ''; // Smart Code Linking for implicit decisions if (existingAdrs && existingAdrs.length > 0) { try { const mockAdrContent = existingAdrs.join('\n\n'); const relatedCodeResult = await findRelatedCode( 'implicit-decisions-analysis', mockAdrContent, projectPath, { useAI: true, useRipgrep: true, maxFiles: 10, includeContent: false, } ); if (relatedCodeResult.relatedFiles.length > 0) { codeContext = `\n## Smart Code Linking - Implicit Decision Context\n\nAnalyzing related code for implicit architectural decisions:\n\n${relatedCodeResult.relatedFiles .slice(0, 5) .map((file, index) => `${index + 1}. **${file.path}** - ${file.extension} file`) .join( '\n' )}\n\n**Code Analysis**: Found ${relatedCodeResult.relatedFiles.length} related files that may contain implicit decisions\n**Keywords Used**: ${relatedCodeResult.keywords.join(', ')}\n**Confidence**: ${(relatedCodeResult.confidence * 100).toFixed(1)}%\n`; } } catch (error) { console.warn('[WARNING] Smart Code Linking for implicit decisions failed:', error); } } // Apply enhancements if enabled if (enhancedMode && (knowledgeEnhancement || learningEnabled)) { let knowledgeContext = ''; // Generate domain knowledge for implicit decision detection if (knowledgeEnhancement) { try { const knowledgeResult = await generateArchitecturalKnowledge( { projectPath, technologies: [], patterns: [], projectType: 'implicit-decision-detection', }, { domains: ['api-design', 'database-design'], depth: 'basic', cacheEnabled: true, } ); knowledgeContext = `\n## Knowledge Enhancement\n${knowledgeResult.prompt}\n`; } catch (error) { console.error('[WARNING] Knowledge generation failed:', error); } } // Apply learning if enabled if (learningEnabled) { try { const reflexionConfig = createToolReflexionConfig('suggest_adrs'); const baseResult = await analyzeImplicitDecisions( projectPath, existingAdrs, conversationContext ); const reflexionResult = await executeWithReflexion( { prompt: baseResult.analysisPrompt + knowledgeContext, instructions: baseResult.instructions, context: { projectPath, analysisType: 'implicit_decisions', existingAdrs }, }, reflexionConfig ); enhancedPrompt = reflexionResult.prompt; enhancementInfo = ` ## Enhancement Status - **Knowledge Generation**: ${knowledgeEnhancement ? 'โ Applied' : 'โ Disabled'} - **Reflexion Learning**: โ Applied - **Smart Code Linking**: ${codeContext ? 'โ Applied' : 'โ No existing ADRs'} - **Learning from**: Past implicit decision detection tasks `; } catch (error) { console.error('[WARNING] Reflexion enhancement failed:', error); const result = await analyzeImplicitDecisions( projectPath, existingAdrs, conversationContext ); enhancedPrompt = result.analysisPrompt + knowledgeContext; } } else { const result = await analyzeImplicitDecisions( projectPath, existingAdrs, conversationContext ); enhancedPrompt = result.analysisPrompt + knowledgeContext; enhancementInfo = ` ## Enhancement Status - **Knowledge Generation**: ${knowledgeEnhancement ? 'โ Applied' : 'โ Disabled'} - **Reflexion Learning**: โ Disabled - **Smart Code Linking**: ${codeContext ? 'โ Applied' : 'โ No existing ADRs'} `; } } else { const result = await analyzeImplicitDecisions( projectPath, existingAdrs, conversationContext ); enhancedPrompt = result.analysisPrompt; enhancementInfo = ` ## Enhancement Status - **Enhanced Mode**: โ Disabled - **Smart Code Linking**: ${codeContext ? 'โ Applied' : 'โ No existing ADRs'} - All advanced features are disabled for this analysis `; } const baseResult = await analyzeImplicitDecisions( projectPath, existingAdrs, conversationContext ); return { content: [ { type: 'text', text: `# ADR Suggestions: Enhanced Implicit Decisions Analysis ${enhancementInfo} ${codeContext} ${baseResult.instructions} ## Enhanced AI Analysis Prompt ${enhancedPrompt} ## Next Steps 1. **Submit the enhanced prompt** to an AI agent for comprehensive analysis 2. **Review the detected decisions** and prioritize based on impact and risk 3. **Use the \`generate_adr_from_decision\` tool** to create ADRs for high-priority decisions 4. **Integrate with existing ADR workflow** for review and approval ## Expected Output The enhanced AI analysis will identify implicit architectural decisions and provide: - Detailed decision analysis with evidence and domain knowledge - Priority and risk assessments informed by past experiences - Suggested ADR titles and content with improved quality - Recommendations for documentation strategy based on learning `, }, ], }; } case 'code_changes': { if (!beforeCode || !afterCode || !changeDescription) { throw new McpAdrError( 'Code change analysis requires beforeCode, afterCode, and changeDescription', 'INVALID_INPUT' ); } let enhancedPrompt = ''; let enhancementInfo = ''; let codeContext = ''; // Smart Code Linking for code changes if (existingAdrs && existingAdrs.length > 0) { try { const mockAdrContent = `${existingAdrs.join('\n\n')}\n\nCODE CHANGE:\n${changeDescription}`; const relatedCodeResult = await findRelatedCode( 'code-changes-analysis', mockAdrContent, projectPath || process.cwd(), { useAI: true, useRipgrep: true, maxFiles: 8, includeContent: false, } ); if (relatedCodeResult.relatedFiles.length > 0) { codeContext = `\n## Smart Code Linking - Code Change Context\n\nFound related code files that may be affected by this change:\n\n${relatedCodeResult.relatedFiles .slice(0, 3) .map( (file, index) => `${index + 1}. **${file.path}** - ${file.extension} file (${file.size} bytes)` ) .join( '\n' )}\n\n**Impact Analysis**: ${relatedCodeResult.relatedFiles.length} files may be affected by this architectural change\n**Keywords Used**: ${relatedCodeResult.keywords.join(', ')}\n**Confidence**: ${(relatedCodeResult.confidence * 100).toFixed(1)}%\n`; } } catch (error) { console.warn('[WARNING] Smart Code Linking for code changes failed:', error); } } // Apply enhancements if enabled let treeSitterAnalysis = ''; if (enhancedMode && (knowledgeEnhancement || learningEnabled)) { let knowledgeContext = ''; // Generate domain knowledge for code change analysis if (knowledgeEnhancement) { try { const knowledgeResult = await generateArchitecturalKnowledge( { projectPath: projectPath || process.cwd(), technologies: [], patterns: [], projectType: 'code-change-analysis', }, { domains: ['api-design', 'performance-optimization'], depth: 'basic', cacheEnabled: true, } ); knowledgeContext = `\n## Knowledge Enhancement\n${knowledgeResult.prompt}\n`; } catch (error) { console.error('[WARNING] Knowledge generation failed:', error); } } // Perform tree-sitter analysis for enhanced code change understanding if (enableTreeSitterAnalysis) { try { const codeChangeAnalysis = await performTreeSitterCodeChangeAnalysis( beforeCode, afterCode, changeDescription ); if ( codeChangeAnalysis.architecturalChanges.length > 0 || codeChangeAnalysis.securityImpacts.length > 0 ) { treeSitterAnalysis = ` ## ๐ Tree-sitter Code Change Analysis **Analysis Results:** - **Architectural Changes**: ${codeChangeAnalysis.architecturalChanges.length} - **Security Impacts**: ${codeChangeAnalysis.securityImpacts.length} - **Complexity Change**: ${codeChangeAnalysis.complexityDelta > 0 ? '+' : ''}${codeChangeAnalysis.complexityDelta} - **New Dependencies**: ${codeChangeAnalysis.newDependencies.length} ${ codeChangeAnalysis.architecturalChanges.length > 0 ? ` ### ๐๏ธ Architectural Changes Detected ${codeChangeAnalysis.architecturalChanges.map(change => `- **${change.type}**: ${change.description} (impact: ${change.impact})`).join('\n')} ` : '' } ${ codeChangeAnalysis.securityImpacts.length > 0 ? ` ### ๐ Security Impact Analysis ${codeChangeAnalysis.securityImpacts.map(impact => `- **${impact.type}**: ${impact.description} (severity: ${impact.severity})`).join('\n')} ` : '' } ${ codeChangeAnalysis.newDependencies.length > 0 ? ` ### ๐ฆ New Dependencies ${codeChangeAnalysis.newDependencies.map(dep => `- **${dep.name}**: ${dep.reason} (risk: ${dep.riskLevel})`).join('\n')} ` : '' } --- `; } } catch (error) { console.warn('Tree-sitter code change analysis failed:', error); treeSitterAnalysis = ` ## ๐ Tree-sitter Code Change Analysis **Status**: โ ๏ธ Analysis failed - continuing with standard analysis **Error**: ${error instanceof Error ? error.message : 'Unknown error'} --- `; } } // Apply learning if enabled if (learningEnabled) { try { const reflexionConfig = createToolReflexionConfig('suggest_adrs', { evaluationCriteria: ['task-success', 'accuracy', 'relevance'], }); const baseResult = await analyzeCodeChanges( beforeCode, afterCode, changeDescription, commitMessages ); const reflexionResult = await executeWithReflexion( { prompt: baseResult.analysisPrompt + knowledgeContext, instructions: baseResult.instructions, context: { analysisType: 'code_changes', changeDescription, hasCommitMessages: !!commitMessages?.length, }, }, reflexionConfig ); enhancedPrompt = reflexionResult.prompt; enhancementInfo = ` ## Enhancement Status - **Knowledge Generation**: ${knowledgeEnhancement ? 'โ Applied' : 'โ Disabled'} - **Reflexion Learning**: โ Applied - **Smart Code Linking**: ${codeContext ? 'โ Applied' : 'โ No existing ADRs'} - **Learning from**: Past code change analysis tasks `; } catch (error) { console.error('[WARNING] Reflexion enhancement failed:', error); const result = await analyzeCodeChanges( beforeCode, afterCode, changeDescription, commitMessages ); enhancedPrompt = result.analysisPrompt + knowledgeContext; } } else { const result = await analyzeCodeChanges( beforeCode, afterCode, changeDescription, commitMessages ); enhancedPrompt = result.analysisPrompt + knowledgeContext; enhancementInfo = ` ## Enhancement Status - **Knowledge Generation**: ${knowledgeEnhancement ? 'โ Applied' : 'โ Disabled'} - **Reflexion Learning**: โ Disabled - **Smart Code Linking**: ${codeContext ? 'โ Applied' : 'โ No existing ADRs'} `; } } else { const result = await analyzeCodeChanges( beforeCode, afterCode, changeDescription, commitMessages ); enhancedPrompt = result.analysisPrompt; enhancementInfo = ` ## Enhancement Status - **Enhanced Mode**: โ Disabled - **Smart Code Linking**: ${codeContext ? 'โ Applied' : 'โ No existing ADRs'} - All advanced features are disabled for this analysis `; } const baseResult = await analyzeCodeChanges( beforeCode, afterCode, changeDescription, commitMessages ); return { content: [ { type: 'text', text: `# ADR Suggestions: Enhanced Code Change Analysis ${enhancementInfo} ${codeContext} ${treeSitterAnalysis} ${baseResult.instructions} ## Enhanced AI Analysis Prompt ${enhancedPrompt} ## Next Steps 1. **Submit the enhanced prompt** to an AI agent for change analysis 2. **Review the identified decisions** reflected in the code changes 3. **Document significant decisions** as ADRs using the generation tool 4. **Follow up with development team** for any clarification questions ## Expected Output The enhanced AI analysis will provide: - Architectural decisions reflected in the changes with domain context - Change motivation and context analysis informed by past experiences - Impact and risk assessment with improved accuracy - Recommendations for documentation based on learning patterns `, }, ], }; } case 'comprehensive': { let enhancedPrompt = ''; let knowledgeContext = ''; let reflexionContext = ''; let codeContext = ''; let researchContext = ''; // Step 0: Research current infrastructure state (NEW - Research-Driven Architecture) try { const orchestrator = new ResearchOrchestrator(projectPath, 'docs/adrs'); // Research questions about current architecture const infrastructureResearch = await orchestrator.answerResearchQuestion( 'What is our current infrastructure and deployment architecture? Include container technology, orchestration, databases, and key architectural patterns.' ); if (infrastructureResearch.confidence >= 0.5) { researchContext = ` ## ๐ฌ Research-Driven Architecture Analysis **Live Infrastructure Research Results:** ### Current State ${infrastructureResearch.answer} ### Data Sources Consulted ${infrastructureResearch.sources.map(s => `- **${s.type}** (confidence: ${(s.confidence * 100).toFixed(1)}%)`).join('\n')} ### Research Metadata - **Overall Confidence**: ${(infrastructureResearch.confidence * 100).toFixed(1)}% - **Files Analyzed**: ${infrastructureResearch.metadata.filesAnalyzed} - **Sources Queried**: ${infrastructureResearch.metadata.sourcesQueried.join(', ')} - **Research Duration**: ${infrastructureResearch.metadata.duration}ms ${infrastructureResearch.needsWebSearch ? '- **Recommendation**: Consider web search for additional context\n' : ''} ### Infrastructure Evidence ${infrastructureResearch.sources .filter(s => s.found && s.data) .map(s => { if (s.type === 'project_files') { return `**Project Files**: ${s.data.files?.length || 0} relevant files found`; } else if (s.type === 'environment') { return `**Environment Data**: ${JSON.stringify(s.data).substring(0, 200)}...`; } else if (s.type === 'knowledge_graph') { return `**Knowledge Graph**: ${s.data.relatedAdrs?.length || 0} related ADRs`; } return ''; }) .filter(Boolean) .join('\n')} --- `; } } catch (error) { console.warn('[WARNING] Research-driven infrastructure analysis failed:', error); researchContext = ` ## ๐ฌ Research-Driven Architecture Analysis **Status**: โ ๏ธ Research analysis unavailable **Error**: ${error instanceof Error ? error.message : 'Unknown error'} Proceeding with traditional analysis methods... --- `; } // Step 1: Generate domain-specific knowledge if enabled if (knowledgeEnhancement) { try { const knowledgeResult = await generateArchitecturalKnowledge( { projectPath, technologies: [], // Will be auto-detected from project patterns: [], projectType: 'software-architecture', existingAdrs: existingAdrs || [], }, { domains: ['api-design', 'database-design', 'microservices'], depth: 'intermediate', cacheEnabled: true, } ); knowledgeContext = ` ## Domain-Specific Knowledge Enhancement The following architectural knowledge has been generated to enhance ADR suggestions: ${knowledgeResult.prompt} --- `; } catch (error) { console.error('[WARNING] Knowledge generation failed:', error); knowledgeContext = '<!-- Knowledge generation unavailable -->\n'; } } // Step 1a: Smart Code Linking - Analyze existing ADRs for related code if (existingAdrs && existingAdrs.length > 0) { try { // For comprehensive analysis, we'll simulate ADR content analysis // In a real scenario, this would read actual ADR files const mockAdrContent = existingAdrs.join('\n\n'); const relatedCodeResult = await findRelatedCode( 'comprehensive-analysis', mockAdrContent, projectPath, { useAI: true, useRipgrep: true, maxFiles: 15, includeContent: false, } ); if (relatedCodeResult.relatedFiles.length > 0) { codeContext = ` ## Smart Code Linking Analysis Found ${relatedCodeResult.relatedFiles.length} code files related to existing ADRs: ### Related Code Files ${relatedCodeResult.relatedFiles .map( (file, index) => ` ${index + 1}. **${file.path}** (${file.extension} file) - Size: ${file.size} bytes - Directory: ${file.directory} ` ) .join('')} ### Search Information - **Keywords Used**: ${relatedCodeResult.keywords.join(', ')} - **Search Patterns**: ${relatedCodeResult.searchPatterns.join(', ')} - **Confidence**: ${(relatedCodeResult.confidence * 100).toFixed(1)}% **Analysis Summary**: ${relatedCodeResult.relatedFiles.length} related files found --- `; } else { codeContext = ` ## Smart Code Linking Analysis **Status**: No related code files found for existing ADRs **Keywords Searched**: ${relatedCodeResult.keywords.join(', ')} **Patterns Used**: ${relatedCodeResult.searchPatterns.join(', ')} This suggests either: - ADRs are high-level architectural decisions not yet implemented - Code patterns don't match ADR terminology - Additional implementation work may be needed --- `; } } catch (error) { console.warn('[WARNING] Smart Code Linking failed:', error); codeContext = ` ## Smart Code Linking Analysis **Status**: โ ๏ธ Analysis failed - continuing without code context **Error**: ${error instanceof Error ? error.message : 'Unknown error'} --- `; } } // Step 2: Apply Reflexion learning if enabled if (learningEnabled) { try { // Retrieve relevant memories from past ADR suggestion tasks const memoryResult = await retrieveRelevantMemories( 'adr-suggestion', { projectPath, analysisType: 'comprehensive', existingAdrs }, { maxResults: 5, relevanceThreshold: 0.6 } ); reflexionContext = ` ## Learning from Past Experiences The following insights from past ADR suggestion tasks will inform this analysis: ${memoryResult.prompt} --- `; } catch (error) { console.error('[WARNING] Reflexion memory retrieval failed:', error); reflexionContext = '<!-- Learning context unavailable -->\n'; } } // Step 3: Get the base analysis const implicitResult = await analyzeImplicitDecisions( projectPath, existingAdrs, conversationContext ); // Step 4: Apply Reflexion execution if learning is enabled if (learningEnabled) { try { const reflexionConfig = createToolReflexionConfig('suggest_adrs', { reflectionDepth: 'detailed', evaluationCriteria: ['task-success', 'relevance', 'clarity'], learningRate: 0.7, }); const reflexionResult = await executeWithReflexion( { prompt: implicitResult.analysisPrompt, instructions: implicitResult.instructions, context: { projectPath, analysisType: 'comprehensive', existingAdrs, knowledgeEnhanced: knowledgeEnhancement, learningEnabled: true, }, }, reflexionConfig ); enhancedPrompt = ` ## Enhanced Analysis with Learning ${reflexionResult.prompt} --- `; } catch (error) { console.error('[WARNING] Reflexion execution failed:', error); enhancedPrompt = implicitResult.analysisPrompt; } } else { enhancedPrompt = implicitResult.analysisPrompt; } // Execute the analysis with AI if enabled, otherwise return prompt const aiExecutor = getAIExecutor(); let executionResult: any; // Try AI-powered analysis with research context if (aiExecutor.isAvailable()) { try { const aiResult = await aiExecutor.executeStructuredPrompt( `You are an expert software architect analyzing a project for ADR recommendations. ${researchContext} ${knowledgeContext} ${reflexionContext} ${codeContext} Based on the research data above, generate comprehensive ADR suggestions. ${implicitResult.instructions} ${enhancedPrompt}`, null, { temperature: 0.3, maxTokens: 4000, systemPrompt: 'You are an architecture expert. Generate ADR recommendations based on ACTUAL infrastructure data from research, not assumptions. Reference specific files, environment data, and existing ADRs found in the research.', } ); executionResult = { isAIGenerated: true, content: typeof aiResult.data === 'string' ? aiResult.data : JSON.stringify(aiResult.data, null, 2), metadata: aiResult.raw.metadata, }; } catch (error) { console.warn('[WARNING] AI execution failed, falling back to prompt-only mode:', error); executionResult = await executeADRSuggestionPrompt( enhancedPrompt, implicitResult.instructions, { temperature: 0.1, maxTokens: 4000, } ); } } else { executionResult = await executeADRSuggestionPrompt( enhancedPrompt, implicitResult.instructions, { temperature: 0.1, maxTokens: 4000, } ); } if (executionResult.isAIGenerated) { // AI execution successful - return actual analysis results return formatMCPResponse({ ...executionResult, content: `# ADR Suggestions: AI Analysis Results (Research-Driven) ## Enhancement Features - **Research-Driven Analysis**: โ Enabled (Live infrastructure data) - **Knowledge Generation**: ${knowledgeEnhancement ? 'โ Enabled' : 'โ Disabled'} - **Reflexion Learning**: ${learningEnabled ? 'โ Enabled' : 'โ Disabled'} - **Enhanced Mode**: ${enhancedMode ? 'โ Enabled' : 'โ Disabled'} - **Smart Code Linking**: ${existingAdrs && existingAdrs.length > 0 ? 'โ Enabled' : 'โ No existing ADRs'} - **AI Execution**: โ OpenRouter.ai ${executionResult.metadata?.model || 'enabled'} ## Project Analysis - **Project Path**: ${projectPath} - **Existing ADRs**: ${existingAdrs?.length || 0} ADRs provided - **Analysis Type**: Comprehensive (Research + AI-driven) - **AI Response Time**: ${executionResult.metadata?.executionTime || 'N/A'}ms - **Tokens Used**: ${executionResult.metadata?.usage?.totalTokens || 'N/A'} ${researchContext} ${codeContext} ${knowledgeContext} ${reflexionContext} ## AI Analysis Results ${executionResult.content} ## Next Steps Based on the analysis above: 1. **Review Suggested ADRs**: Examine each suggested architectural decision 2. **Prioritize by Impact**: Focus on high-impact decisions first 3. **Generate ADRs**: Use the \`generate_adr_from_decision\` tool for priority decisions 4. **Implement Changes**: Plan and execute the architectural changes 5. **Update Documentation**: Keep ADRs current as decisions evolve ## Integration Workflow For each suggested decision, use: \`\`\`json { "tool": "generate_adr_from_decision", "args": { "decisionData": { "title": "Decision title from analysis", "context": "Context from analysis", "decision": "Decision description", "consequences": "Consequences from analysis" } } } \`\`\` `, }); } else { // Fallback to prompt-only mode return { content: [ { type: 'text', text: `# ADR Suggestions: Enhanced Comprehensive Analysis (Research-Driven) This enhanced analysis uses research-driven architecture with live infrastructure data and advanced prompting techniques. ## Enhancement Features - **Research-Driven Analysis**: โ Enabled (Live infrastructure data) - **Knowledge Generation**: ${knowledgeEnhancement ? 'โ Enabled' : 'โ Disabled'} - **Reflexion Learning**: ${learningEnabled ? 'โ Enabled' : 'โ Disabled'} - **Enhanced Mode**: ${enhancedMode ? 'โ Enabled' : 'โ Disabled'} - **Smart Code Linking**: ${existingAdrs && existingAdrs.length > 0 ? 'โ Enabled' : 'โ No existing ADRs'} - **AI Execution**: โ Disabled (configure OPENROUTER_API_KEY for AI execution) ## Project Analysis - **Project Path**: ${projectPath} - **Existing ADRs**: ${existingAdrs?.length || 0} ADRs provided - **Analysis Type**: Comprehensive (Research-driven + Enhanced prompting) ${researchContext} ${codeContext} ${knowledgeContext} ${reflexionContext} ## AI Analysis Instructions ${implicitResult.instructions} ## Enhanced AI Analysis Prompt ${enhancedPrompt} ## Recommended Workflow ### 1. **Initial Analysis** Submit the prompt above to get comprehensive decision detection ### 2. **Priority Review** - Focus on **high** and **critical** priority decisions first - Consider **risk level** and **complexity** for planning - Group related decisions using suggested clusters ### 3. **ADR Generation** Use \`generate_adr_from_decision\` tool for each prioritized decision ### 4. **Integration** - Save generated ADRs to your ADR directory - Update ADR index/catalog - Schedule team review sessions - Plan implementation tasks `, }, ], }; } } default: throw new McpAdrError(`Unknown analysis type: ${analysisType}`, 'INVALID_INPUT'); } } catch (error) { throw new McpAdrError( `Failed to suggest ADRs: ${error instanceof Error ? error.message : String(error)}`, 'SUGGESTION_ERROR' ); } }
- src/tools/tool-chain-orchestrator.ts:72-99 (registration)Tool registration in the central orchestrator's TOOL_CAPABILITIES mapping and AVAILABLE_TOOLS array. Defines the tool's purpose and makes it discoverable for AI-driven tool chain planning.const TOOL_CAPABILITIES = { analyze_project_ecosystem: 'Analyze technology stack, dependencies, and architectural patterns', generate_adrs_from_prd: 'Convert Product Requirements Documents to Architectural Decision Records', suggest_adrs: 'Auto-suggest ADRs based on code analysis and project patterns', analyze_content_security: 'Detect and mask sensitive information in project content', generate_rules: 'Extract architectural rules and constraints from project analysis', generate_adr_todo: 'Generate TODO.md from ADRs with comprehensive task breakdown', compare_adr_progress: 'Validate TODO vs ADRs vs actual environment state', manage_todo: 'Comprehensive TODO.md lifecycle management and progress tracking', generate_deployment_guidance: 'AI-driven deployment procedures from architectural decisions', smart_score: 'Project health scoring with cross-tool synchronization', troubleshoot_guided_workflow: 'Systematic troubleshooting with ADR/TODO alignment', smart_git_push: 'Intelligent release readiness analysis and git operations', generate_research_questions: 'Generate targeted research questions for project analysis', validate_rules: 'Validate architectural rule compliance across the project', analyze_code_patterns: 'Identify code patterns and architectural consistency', suggest_improvements: 'Provide targeted improvement recommendations', generate_test_scenarios: 'Create comprehensive test scenarios and strategies', create_documentation: 'Generate project documentation from code and ADRs', security_audit: 'Comprehensive security analysis and vulnerability detection', performance_analysis: 'Analyze performance bottlenecks and optimization opportunities', dependency_analysis: 'Analyze project dependencies and potential issues', refactoring_suggestions: 'Suggest code refactoring based on architectural principles', api_documentation: 'Generate API documentation from code analysis', deployment_checklist: 'Create deployment checklists based on ADRs and project state', release_notes: 'Generate release notes from commits, ADRs, and TODO completion', };
- src/utils/server-context-generator.ts:138-140 (registration)Tool listed in server context generator's hardcoded tool registry for LLM context awareness and @-referencing.{ name: 'suggest_adrs', description: 'Suggest new ADRs based on project context and analysis',
- Automatic Prompt Engineering (APE) configuration optimized specifically for the suggest_adrs tool, defining candidate generation, evaluation criteria, and selection strategy for prompt optimization.suggest_adrs: { candidateCount: 6, evaluationCriteria: ['task-completion', 'context-awareness', 'clarity'], optimizationRounds: 2, selectionStrategy: 'context-aware', qualityThreshold: 0.7, },