mcp-adr-analysis-server 1.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +313 -69
  2. package/dist/src/config/ai-config.d.ts +81 -0
  3. package/dist/src/config/ai-config.d.ts.map +1 -0
  4. package/dist/src/config/ai-config.js +134 -0
  5. package/dist/src/config/ai-config.js.map +1 -0
  6. package/dist/src/index.d.ts +96 -1
  7. package/dist/src/index.d.ts.map +1 -1
  8. package/dist/src/index.js +1818 -199
  9. package/dist/src/index.js.map +1 -1
  10. package/dist/src/prompts/adr-suggestion-prompts.d.ts +2 -2
  11. package/dist/src/prompts/adr-suggestion-prompts.d.ts.map +1 -1
  12. package/dist/src/prompts/adr-suggestion-prompts.js +25 -17
  13. package/dist/src/prompts/adr-suggestion-prompts.js.map +1 -1
  14. package/dist/src/prompts/analysis-prompts.js +1 -1
  15. package/dist/src/prompts/analysis-prompts.js.map +1 -1
  16. package/dist/src/resources/index.d.ts +1 -1
  17. package/dist/src/resources/index.d.ts.map +1 -1
  18. package/dist/src/resources/index.js +52 -44
  19. package/dist/src/resources/index.js.map +1 -1
  20. package/dist/src/templates/domain-knowledge-templates.d.ts +36 -0
  21. package/dist/src/templates/domain-knowledge-templates.d.ts.map +1 -0
  22. package/dist/src/templates/domain-knowledge-templates.js +376 -0
  23. package/dist/src/templates/domain-knowledge-templates.js.map +1 -0
  24. package/dist/src/tools/adr-suggestion-tool.d.ts +8 -3
  25. package/dist/src/tools/adr-suggestion-tool.d.ts.map +1 -1
  26. package/dist/src/tools/adr-suggestion-tool.js +561 -172
  27. package/dist/src/tools/adr-suggestion-tool.js.map +1 -1
  28. package/dist/src/tools/content-masking-tool.d.ts.map +1 -1
  29. package/dist/src/tools/content-masking-tool.js +168 -22
  30. package/dist/src/tools/content-masking-tool.js.map +1 -1
  31. package/dist/src/tools/deployment-analysis-tool.d.ts.map +1 -1
  32. package/dist/src/tools/deployment-analysis-tool.js +64 -27
  33. package/dist/src/tools/deployment-analysis-tool.js.map +1 -1
  34. package/dist/src/tools/environment-analysis-tool.d.ts.map +1 -1
  35. package/dist/src/tools/environment-analysis-tool.js +65 -29
  36. package/dist/src/tools/environment-analysis-tool.js.map +1 -1
  37. package/dist/src/tools/research-question-tool.d.ts.map +1 -1
  38. package/dist/src/tools/research-question-tool.js +150 -49
  39. package/dist/src/tools/research-question-tool.js.map +1 -1
  40. package/dist/src/tools/rule-generation-tool.d.ts.map +1 -1
  41. package/dist/src/tools/rule-generation-tool.js +328 -143
  42. package/dist/src/tools/rule-generation-tool.js.map +1 -1
  43. package/dist/src/types/ape-framework.d.ts +566 -0
  44. package/dist/src/types/ape-framework.d.ts.map +1 -0
  45. package/dist/src/types/ape-framework.js +98 -0
  46. package/dist/src/types/ape-framework.js.map +1 -0
  47. package/dist/src/types/index.d.ts +96 -93
  48. package/dist/src/types/index.d.ts.map +1 -1
  49. package/dist/src/types/knowledge-generation.d.ts +671 -0
  50. package/dist/src/types/knowledge-generation.d.ts.map +1 -0
  51. package/dist/src/types/knowledge-generation.js +107 -0
  52. package/dist/src/types/knowledge-generation.js.map +1 -0
  53. package/dist/src/types/reflexion-framework.d.ts +652 -0
  54. package/dist/src/types/reflexion-framework.d.ts.map +1 -0
  55. package/dist/src/types/reflexion-framework.js +85 -0
  56. package/dist/src/types/reflexion-framework.js.map +1 -0
  57. package/dist/src/utils/adr-suggestions.d.ts +1 -1
  58. package/dist/src/utils/adr-suggestions.d.ts.map +1 -1
  59. package/dist/src/utils/adr-suggestions.js +8 -50
  60. package/dist/src/utils/adr-suggestions.js.map +1 -1
  61. package/dist/src/utils/ai-executor.d.ts +125 -0
  62. package/dist/src/utils/ai-executor.d.ts.map +1 -0
  63. package/dist/src/utils/ai-executor.js +292 -0
  64. package/dist/src/utils/ai-executor.js.map +1 -0
  65. package/dist/src/utils/automatic-prompt-engineering.d.ts +72 -0
  66. package/dist/src/utils/automatic-prompt-engineering.d.ts.map +1 -0
  67. package/dist/src/utils/automatic-prompt-engineering.js +820 -0
  68. package/dist/src/utils/automatic-prompt-engineering.js.map +1 -0
  69. package/dist/src/utils/cache.d.ts +54 -22
  70. package/dist/src/utils/cache.d.ts.map +1 -1
  71. package/dist/src/utils/cache.js +1234 -143
  72. package/dist/src/utils/cache.js.map +1 -1
  73. package/dist/src/utils/config.d.ts +2 -2
  74. package/dist/src/utils/config.js +3 -3
  75. package/dist/src/utils/config.js.map +1 -1
  76. package/dist/src/utils/deployment-analysis.d.ts.map +1 -1
  77. package/dist/src/utils/deployment-analysis.js +57 -38
  78. package/dist/src/utils/deployment-analysis.js.map +1 -1
  79. package/dist/src/utils/environment-analysis.d.ts.map +1 -1
  80. package/dist/src/utils/environment-analysis.js +113 -100
  81. package/dist/src/utils/environment-analysis.js.map +1 -1
  82. package/dist/src/utils/file-system.d.ts +42 -13
  83. package/dist/src/utils/file-system.d.ts.map +1 -1
  84. package/dist/src/utils/file-system.js +795 -89
  85. package/dist/src/utils/file-system.js.map +1 -1
  86. package/dist/src/utils/index.d.ts +9 -0
  87. package/dist/src/utils/index.d.ts.map +1 -0
  88. package/dist/src/utils/index.js +13 -0
  89. package/dist/src/utils/index.js.map +1 -0
  90. package/dist/src/utils/knowledge-generation.d.ts +79 -0
  91. package/dist/src/utils/knowledge-generation.d.ts.map +1 -0
  92. package/dist/src/utils/knowledge-generation.js +646 -0
  93. package/dist/src/utils/knowledge-generation.js.map +1 -0
  94. package/dist/src/utils/output-masking.d.ts.map +1 -1
  95. package/dist/src/utils/output-masking.js +2 -1
  96. package/dist/src/utils/output-masking.js.map +1 -1
  97. package/dist/src/utils/prompt-composition.d.ts +234 -0
  98. package/dist/src/utils/prompt-composition.d.ts.map +1 -0
  99. package/dist/src/utils/prompt-composition.js +379 -0
  100. package/dist/src/utils/prompt-composition.js.map +1 -0
  101. package/dist/src/utils/prompt-execution.d.ts +88 -0
  102. package/dist/src/utils/prompt-execution.d.ts.map +1 -0
  103. package/dist/src/utils/prompt-execution.js +227 -0
  104. package/dist/src/utils/prompt-execution.js.map +1 -0
  105. package/dist/src/utils/reflexion.d.ts +92 -0
  106. package/dist/src/utils/reflexion.d.ts.map +1 -0
  107. package/dist/src/utils/reflexion.js +1100 -0
  108. package/dist/src/utils/reflexion.js.map +1 -0
  109. package/dist/src/utils/research-integration.d.ts.map +1 -1
  110. package/dist/src/utils/research-integration.js +156 -100
  111. package/dist/src/utils/research-integration.js.map +1 -1
  112. package/dist/src/utils/research-questions.d.ts.map +1 -1
  113. package/dist/src/utils/research-questions.js +85 -24
  114. package/dist/src/utils/research-questions.js.map +1 -1
  115. package/dist/src/utils/rule-generation.d.ts.map +1 -1
  116. package/dist/src/utils/rule-generation.js +92 -108
  117. package/dist/src/utils/rule-generation.js.map +1 -1
  118. package/package.json +7 -1
package/dist/src/index.js CHANGED
@@ -23,7 +23,7 @@ const SERVER_INFO = {
23
23
  /**
24
24
  * Main server class
25
25
  */
26
- class McpAdrAnalysisServer {
26
+ export class McpAdrAnalysisServer {
27
27
  server;
28
28
  maskingConfig;
29
29
  config;
@@ -75,7 +75,7 @@ class McpAdrAnalysisServer {
75
75
  tools: [
76
76
  {
77
77
  name: 'analyze_project_ecosystem',
78
- description: 'Analyze the project ecosystem including technology stack, patterns, and architecture',
78
+ description: 'Comprehensive recursive project ecosystem analysis with advanced prompting techniques (Knowledge Generation + Reflexion)',
79
79
  inputSchema: {
80
80
  type: 'object',
81
81
  properties: {
@@ -87,6 +87,48 @@ class McpAdrAnalysisServer {
87
87
  type: 'array',
88
88
  items: { type: 'string' },
89
89
  description: 'File patterns to include in analysis'
90
+ },
91
+ enhancedMode: {
92
+ type: 'boolean',
93
+ description: 'Enable advanced prompting features (Knowledge Generation + Reflexion)',
94
+ default: true
95
+ },
96
+ knowledgeEnhancement: {
97
+ type: 'boolean',
98
+ description: 'Enable Knowledge Generation for technology-specific insights',
99
+ default: true
100
+ },
101
+ learningEnabled: {
102
+ type: 'boolean',
103
+ description: 'Enable Reflexion learning from past analysis outcomes',
104
+ default: true
105
+ },
106
+ technologyFocus: {
107
+ type: 'array',
108
+ items: { type: 'string' },
109
+ description: 'Specific technologies to focus analysis on (auto-detected if not provided)'
110
+ },
111
+ analysisDepth: {
112
+ type: 'string',
113
+ enum: ['basic', 'detailed', 'comprehensive'],
114
+ description: 'Depth of ecosystem analysis',
115
+ default: 'comprehensive'
116
+ },
117
+ includeEnvironment: {
118
+ type: 'boolean',
119
+ description: 'Automatically include comprehensive environment analysis (default: true)',
120
+ default: true
121
+ },
122
+ recursiveDepth: {
123
+ type: 'string',
124
+ description: 'Depth of recursive project analysis',
125
+ enum: ['shallow', 'moderate', 'deep', 'comprehensive'],
126
+ default: 'comprehensive'
127
+ },
128
+ analysisScope: {
129
+ type: 'array',
130
+ items: { type: 'string' },
131
+ description: 'Specific analysis areas to focus on (e.g., ["security", "performance", "architecture", "dependencies"])'
90
132
  }
91
133
  },
92
134
  required: []
@@ -94,7 +136,7 @@ class McpAdrAnalysisServer {
94
136
  },
95
137
  {
96
138
  name: 'get_architectural_context',
97
- description: 'Get detailed architectural context for specific files or the entire project',
139
+ description: 'Get detailed architectural context for specific files or the entire project, automatically sets up ADR infrastructure if missing, and provides outcome-focused workflow for project success',
98
140
  inputSchema: {
99
141
  type: 'object',
100
142
  properties: {
@@ -112,7 +154,7 @@ class McpAdrAnalysisServer {
112
154
  },
113
155
  {
114
156
  name: 'generate_adrs_from_prd',
115
- description: 'Generate Architectural Decision Records from a Product Requirements Document',
157
+ description: 'Generate Architectural Decision Records from a Product Requirements Document with advanced prompting techniques (APE + Knowledge Generation)',
116
158
  inputSchema: {
117
159
  type: 'object',
118
160
  properties: {
@@ -123,6 +165,27 @@ class McpAdrAnalysisServer {
123
165
  outputDirectory: {
124
166
  type: 'string',
125
167
  description: 'Directory to output generated ADRs (optional, uses configured ADR_DIRECTORY if not provided)'
168
+ },
169
+ enhancedMode: {
170
+ type: 'boolean',
171
+ description: 'Enable advanced prompting features (APE + Knowledge Generation)',
172
+ default: true
173
+ },
174
+ promptOptimization: {
175
+ type: 'boolean',
176
+ description: 'Enable Automatic Prompt Engineering for optimized ADR generation',
177
+ default: true
178
+ },
179
+ knowledgeEnhancement: {
180
+ type: 'boolean',
181
+ description: 'Enable Knowledge Generation for domain-specific insights',
182
+ default: true
183
+ },
184
+ prdType: {
185
+ type: 'string',
186
+ enum: ['web-application', 'mobile-app', 'microservices', 'data-platform', 'api-service', 'general'],
187
+ description: 'Type of PRD for optimized knowledge generation',
188
+ default: 'general'
126
189
  }
127
190
  },
128
191
  required: ['prdPath']
@@ -313,7 +376,7 @@ class McpAdrAnalysisServer {
313
376
  },
314
377
  {
315
378
  name: 'suggest_adrs',
316
- description: 'Suggest ADRs based on project analysis and implicit decisions',
379
+ description: 'Suggest architectural decisions with advanced prompting techniques (Knowledge Generation + Reflexion)',
317
380
  inputSchema: {
318
381
  type: 'object',
319
382
  properties: {
@@ -349,6 +412,21 @@ class McpAdrAnalysisServer {
349
412
  type: 'array',
350
413
  items: { type: 'string' },
351
414
  description: 'List of existing ADR titles to avoid duplication'
415
+ },
416
+ enhancedMode: {
417
+ type: 'boolean',
418
+ description: 'Enable advanced prompting features (Knowledge Generation + Reflexion)',
419
+ default: true
420
+ },
421
+ learningEnabled: {
422
+ type: 'boolean',
423
+ description: 'Enable Reflexion learning from past experiences',
424
+ default: true
425
+ },
426
+ knowledgeEnhancement: {
427
+ type: 'boolean',
428
+ description: 'Enable Knowledge Generation for domain-specific insights',
429
+ default: true
352
430
  }
353
431
  }
354
432
  }
@@ -889,6 +967,100 @@ class McpAdrAnalysisServer {
889
967
  }
890
968
  }
891
969
  }
970
+ },
971
+ {
972
+ name: 'check_ai_execution_status',
973
+ description: 'Check AI execution configuration and status for debugging prompt-only mode issues',
974
+ inputSchema: {
975
+ type: 'object',
976
+ properties: {},
977
+ required: []
978
+ }
979
+ },
980
+ {
981
+ name: 'get_workflow_guidance',
982
+ description: 'Get intelligent workflow guidance and tool recommendations based on your goals and project context to achieve expected outcomes efficiently',
983
+ inputSchema: {
984
+ type: 'object',
985
+ properties: {
986
+ goal: {
987
+ type: 'string',
988
+ description: 'What you want to accomplish (e.g., "analyze new project", "document existing decisions", "security audit", "modernize legacy system")'
989
+ },
990
+ projectContext: {
991
+ type: 'string',
992
+ description: 'Current state of your project (e.g., "new project", "existing project with ADRs", "legacy codebase", "greenfield development")',
993
+ enum: ['new_project', 'existing_with_adrs', 'existing_without_adrs', 'legacy_codebase', 'greenfield', 'maintenance_mode', 'unknown']
994
+ },
995
+ availableAssets: {
996
+ type: 'array',
997
+ items: { type: 'string' },
998
+ description: 'What assets you already have (e.g., ["PRD.md", "existing ADRs", "codebase", "documentation", "test suite"])'
999
+ },
1000
+ timeframe: {
1001
+ type: 'string',
1002
+ description: 'Available time/effort level',
1003
+ enum: ['quick_analysis', 'thorough_review', 'comprehensive_audit', 'ongoing_process']
1004
+ },
1005
+ primaryConcerns: {
1006
+ type: 'array',
1007
+ items: { type: 'string' },
1008
+ description: 'Main areas of concern (e.g., ["security", "performance", "maintainability", "scalability", "compliance"])'
1009
+ }
1010
+ },
1011
+ required: ['goal', 'projectContext']
1012
+ }
1013
+ },
1014
+ {
1015
+ name: 'get_development_guidance',
1016
+ description: 'Get comprehensive development guidance that translates architectural decisions and workflow recommendations into specific coding tasks, implementation patterns, and development roadmap',
1017
+ inputSchema: {
1018
+ type: 'object',
1019
+ properties: {
1020
+ developmentPhase: {
1021
+ type: 'string',
1022
+ description: 'Current development phase',
1023
+ enum: ['planning', 'setup', 'implementation', 'testing', 'deployment', 'maintenance', 'refactoring']
1024
+ },
1025
+ adrsToImplement: {
1026
+ type: 'array',
1027
+ items: { type: 'string' },
1028
+ description: 'List of ADR titles or file paths that need to be implemented in code'
1029
+ },
1030
+ technologyStack: {
1031
+ type: 'array',
1032
+ items: { type: 'string' },
1033
+ description: 'Current technology stack (e.g., ["TypeScript", "React", "Node.js", "PostgreSQL", "Docker"])'
1034
+ },
1035
+ currentProgress: {
1036
+ type: 'string',
1037
+ description: 'What has already been implemented or current state of development'
1038
+ },
1039
+ teamContext: {
1040
+ type: 'object',
1041
+ properties: {
1042
+ size: {
1043
+ type: 'string',
1044
+ enum: ['solo', 'small_team', 'medium_team', 'large_team']
1045
+ },
1046
+ experienceLevel: {
1047
+ type: 'string',
1048
+ enum: ['junior', 'mixed', 'senior', 'expert']
1049
+ }
1050
+ }
1051
+ },
1052
+ timeline: {
1053
+ type: 'string',
1054
+ description: 'Development timeline or deadline constraints'
1055
+ },
1056
+ focusAreas: {
1057
+ type: 'array',
1058
+ items: { type: 'string' },
1059
+ description: 'Specific areas to focus on (e.g., ["API design", "database schema", "testing strategy", "deployment pipeline"])'
1060
+ }
1061
+ },
1062
+ required: ['developmentPhase']
1063
+ }
892
1064
  }
893
1065
  ]
894
1066
  };
@@ -968,6 +1140,15 @@ class McpAdrAnalysisServer {
968
1140
  case 'analyze_deployment_progress':
969
1141
  response = await this.analyzeDeploymentProgress(args);
970
1142
  break;
1143
+ case 'check_ai_execution_status':
1144
+ response = await this.checkAIExecutionStatus(args);
1145
+ break;
1146
+ case 'get_workflow_guidance':
1147
+ response = await this.getWorkflowGuidance(args);
1148
+ break;
1149
+ case 'get_development_guidance':
1150
+ response = await this.getDevelopmentGuidance(args);
1151
+ break;
971
1152
  default:
972
1153
  throw new McpAdrError(`Unknown tool: ${name}`, 'UNKNOWN_TOOL');
973
1154
  }
@@ -1073,230 +1254,1445 @@ class McpAdrAnalysisServer {
1073
1254
  /**
1074
1255
  * Tool implementations
1075
1256
  */
1076
- async analyzeProjectEcosystem(args) {
1077
- // Use configured project path if not provided in args
1078
- const projectPath = args.projectPath || this.config.projectPath;
1079
- this.logger.info(`Analyzing project ecosystem at: ${projectPath}`);
1257
+ async checkAIExecutionStatus(_args) {
1080
1258
  try {
1081
- // Import utilities dynamically to avoid circular dependencies
1082
- const { analyzeProjectStructure, readFileContent } = await import('./utils/file-system.js');
1083
- const { generateAnalysisContext, generateComprehensiveAnalysisPrompt } = await import('./prompts/analysis-prompts.js');
1084
- // Analyze project structure
1085
- const projectStructure = await analyzeProjectStructure(projectPath);
1086
- // Read key files for context
1087
- let packageJsonContent;
1088
- try {
1089
- packageJsonContent = await readFileContent(`${projectPath}/package.json`);
1090
- }
1091
- catch {
1092
- // package.json might not exist
1093
- }
1094
- // Generate analysis context
1095
- const analysisContext = generateAnalysisContext(projectStructure);
1096
- // Generate comprehensive analysis prompt
1097
- const analysisPrompt = generateComprehensiveAnalysisPrompt(analysisContext, packageJsonContent);
1259
+ const { getAIExecutionStatus } = await import('./utils/prompt-execution.js');
1260
+ const status = getAIExecutionStatus();
1098
1261
  return {
1099
1262
  content: [
1100
1263
  {
1101
1264
  type: 'text',
1102
- text: `Project ecosystem analysis for: ${projectPath}\n\nPlease analyze this project using the following prompt:\n\n${analysisPrompt}`
1265
+ text: `# AI Execution Status Diagnostic
1266
+
1267
+ ## Current Configuration
1268
+ - **AI Execution Enabled**: ${status.isEnabled ? '✅ YES' : '❌ NO'}
1269
+ - **Has API Key**: ${status.hasApiKey ? '✅ YES' : '❌ NO'}
1270
+ - **Execution Mode**: ${status.executionMode}
1271
+ - **AI Model**: ${status.model}
1272
+
1273
+ ${status.reason ? `## ⚠️ Issue Detected
1274
+ **Problem**: ${status.reason}
1275
+
1276
+ ## Solution
1277
+ ${!status.hasApiKey ? `
1278
+ 1. Get an OpenRouter API key from https://openrouter.ai/keys
1279
+ 2. Add it to your MCP configuration:
1280
+ \`\`\`json
1281
+ {
1282
+ "mcpServers": {
1283
+ "adr-analysis": {
1284
+ "command": "mcp-adr-analysis-server",
1285
+ "env": {
1286
+ "OPENROUTER_API_KEY": "your_api_key_here",
1287
+ "EXECUTION_MODE": "full",
1288
+ "AI_MODEL": "anthropic/claude-3-sonnet"
1289
+ }
1290
+ }
1291
+ }
1292
+ }
1293
+ \`\`\`
1294
+ 3. Restart your MCP client (Claude Desktop, etc.)
1295
+ ` : status.executionMode !== 'full' ? `
1296
+ 1. Update your MCP configuration to set EXECUTION_MODE to "full":
1297
+ \`\`\`json
1298
+ {
1299
+ "mcpServers": {
1300
+ "adr-analysis": {
1301
+ "env": {
1302
+ "EXECUTION_MODE": "full"
1303
+ }
1304
+ }
1305
+ }
1306
+ }
1307
+ \`\`\`
1308
+ 2. Restart your MCP client
1309
+ ` : ''}` : `## ✅ Configuration Looks Good!
1310
+
1311
+ AI execution is properly configured. Tools should return actual results instead of prompts.
1312
+
1313
+ If you're still seeing prompts instead of results, try:
1314
+ 1. Restart your MCP client
1315
+ 2. Check your OpenRouter API key has sufficient credits
1316
+ 3. Verify network connectivity to OpenRouter.ai`}
1317
+
1318
+ ## Environment Variables Expected
1319
+ - **OPENROUTER_API_KEY**: Your OpenRouter API key
1320
+ - **EXECUTION_MODE**: Set to "full" for AI execution
1321
+ - **AI_MODEL**: AI model to use (optional, defaults to claude-3-sonnet)
1322
+
1323
+ ## Testing
1324
+ After fixing the configuration, try calling \`suggest_adrs\` - it should return actual ADR suggestions instead of prompts.
1325
+ `
1103
1326
  }
1104
1327
  ]
1105
1328
  };
1106
1329
  }
1107
1330
  catch (error) {
1108
- throw new McpAdrError(`Failed to analyze project ecosystem: ${error instanceof Error ? error.message : String(error)}`, 'ANALYSIS_ERROR');
1109
- }
1110
- }
1111
- async getArchitecturalContext(args) {
1112
- const { filePath } = args;
1113
- try {
1114
- const { analyzeProjectStructure } = await import('./utils/file-system.js');
1115
- const { generateAnalysisContext, generatePatternDetectionPrompt } = await import('./prompts/analysis-prompts.js');
1116
- // Determine project path
1117
- const projectPath = filePath ? filePath.split('/').slice(0, -1).join('/') : process.cwd();
1118
- // Analyze project structure
1119
- const projectStructure = await analyzeProjectStructure(projectPath);
1120
- const analysisContext = generateAnalysisContext(projectStructure);
1121
- // Generate pattern detection prompt
1122
- const patternPrompt = generatePatternDetectionPrompt(analysisContext);
1123
1331
  return {
1124
1332
  content: [
1125
1333
  {
1126
1334
  type: 'text',
1127
- text: `Architectural context analysis${filePath ? ` for: ${filePath}` : ''}\n\nPlease analyze architectural patterns using the following prompt:\n\n${patternPrompt}`
1335
+ text: `# AI Execution Status Check Failed
1336
+
1337
+ **Error**: ${error instanceof Error ? error.message : String(error)}
1338
+
1339
+ This diagnostic tool helps identify why tools return prompts instead of actual results.
1340
+
1341
+ ## Manual Check
1342
+ Verify these environment variables are set in your MCP configuration:
1343
+ - OPENROUTER_API_KEY
1344
+ - EXECUTION_MODE=full
1345
+ - AI_MODEL (optional)
1346
+ `
1128
1347
  }
1129
1348
  ]
1130
1349
  };
1131
1350
  }
1132
- catch (error) {
1133
- throw new McpAdrError(`Failed to get architectural context: ${error instanceof Error ? error.message : String(error)}`, 'ANALYSIS_ERROR');
1134
- }
1135
1351
  }
1136
- async generateAdrsFromPrd(args) {
1137
- const { prdPath } = args;
1138
- const outputDirectory = args.outputDirectory || this.config.adrDirectory;
1139
- this.logger.info(`Generating ADRs from PRD: ${prdPath} to ${outputDirectory}`);
1352
+ async getWorkflowGuidance(args) {
1353
+ const { goal, projectContext, availableAssets = [], timeframe = 'thorough_review', primaryConcerns = [] } = args;
1140
1354
  try {
1141
- const { readFileContent, fileExists } = await import('./utils/file-system.js');
1142
- // Check if PRD file exists
1143
- if (!(await fileExists(prdPath))) {
1144
- throw new McpAdrError(`PRD file not found: ${prdPath}`, 'FILE_NOT_FOUND');
1145
- }
1146
- // Read PRD content
1147
- const prdContent = await readFileContent(prdPath);
1148
- // Generate ADR creation prompt
1149
- const adrPrompt = `
1150
- # ADR Generation from PRD Request
1355
+ const workflowPrompt = `
1356
+ # Workflow Guidance & Tool Recommendation System
1151
1357
 
1152
- Please analyze the following Product Requirements Document and generate Architectural Decision Records (ADRs).
1358
+ ## User Context Analysis
1359
+ - **Goal**: ${goal}
1360
+ - **Project Context**: ${projectContext}
1361
+ - **Available Assets**: ${availableAssets.length > 0 ? availableAssets.join(', ') : 'None specified'}
1362
+ - **Timeframe**: ${timeframe}
1363
+ - **Primary Concerns**: ${primaryConcerns.length > 0 ? primaryConcerns.join(', ') : 'General analysis'}
1153
1364
 
1154
- ## PRD Content
1155
- \`\`\`markdown
1156
- ${prdContent}
1157
- \`\`\`
1365
+ ## Available MCP Tools (24 Total)
1158
1366
 
1159
- ## Requirements
1367
+ ### 🎯 **Core Analysis Tools** (AI-Powered ✅)
1368
+ 1. **analyze_project_ecosystem** - Comprehensive technology and pattern detection
1369
+ 2. **get_architectural_context** - Generate intelligent architectural insights + ADR setup
1370
+ 3. **generate_adrs_from_prd** - Convert requirements to structured ADRs
1371
+ 4. **analyze_content_security** - Detect sensitive information patterns
1160
1372
 
1161
- 1. **Extract Key Decisions**: Identify all architectural decisions implied or stated in the PRD
1162
- 2. **Generate ADRs**: Create individual ADR files for each significant decision
1163
- 3. **Follow ADR Format**: Use standard ADR template (title, status, context, decision, consequences)
1164
- 4. **Number Sequentially**: Use format 001-decision-title.md, 002-next-decision.md, etc.
1165
- 5. **Output Directory**: Place ADRs in ${outputDirectory}/
1373
+ ### 📋 **ADR Management Tools** (AI-Powered ✅)
1374
+ 5. **suggest_adrs** - Auto-suggest ADRs from implicit decisions
1375
+ 6. **generate_adr_from_decision** - Create ADRs from specific decisions
1376
+ 7. **discover_existing_adrs** - Intelligent ADR discovery and analysis
1377
+ 8. **generate_adr_todo** - Create actionable task lists from ADRs
1166
1378
 
1167
- ## ADR Template Format
1379
+ ### 🔍 **Research & Documentation Tools** (AI-Powered ✅)
1380
+ 9. **generate_research_questions** - Create context-aware research questions
1381
+ 10. **incorporate_research** - Integrate research findings into decisions
1382
+ 11. **create_research_template** - Generate research documentation templates
1168
1383
 
1169
- \`\`\`markdown
1170
- # [Number]. [Title]
1384
+ ### 🛡️ **Security & Compliance Tools** (AI-Powered ✅)
1385
+ 12. **generate_content_masking** - Intelligent content masking and protection
1386
+ 13. **configure_custom_patterns** - Customize security and masking settings
1387
+ 14. **apply_basic_content_masking** - Basic content masking (fallback)
1388
+ 15. **validate_content_masking** - Validate masking effectiveness
1171
1389
 
1172
- **Status**: [Proposed/Accepted/Deprecated/Superseded]
1173
- **Date**: [YYYY-MM-DD]
1390
+ ### 🏗️ **Rule & Governance Tools** (AI-Powered ✅)
1391
+ 16. **generate_rules** - Extract architectural rules from ADRs
1392
+ 17. **validate_rules** - Validate code against architectural rules
1393
+ 18. **create_rule_set** - Create comprehensive rule management systems
1174
1394
 
1175
- ## Context
1176
- [Describe the context and problem statement]
1395
+ ### 🚀 **Deployment & Environment Tools** (AI-Powered ✅)
1396
+ 19. **analyze_environment** - Environment analysis and optimization
1397
+ 20. **analyze_deployment_progress** - Deployment tracking and verification
1177
1398
 
1178
- ## Decision
1179
- [Describe the architectural decision]
1399
+ ### ⚙️ **Utility & Management Tools**
1400
+ 21. **manage_cache** - Cache management and optimization
1401
+ 22. **configure_output_masking** - Configure global output masking
1402
+ 23. **request_action_confirmation** - Interactive user confirmation workflows
1403
+ 24. **get_workflow_guidance** - This tool - intelligent workflow advisor
1180
1404
 
1181
- ## Consequences
1182
- [Describe the positive and negative consequences]
1405
+ ## Workflow Recommendation Instructions
1183
1406
 
1184
- ## Implementation Plan
1185
- [Optional: Steps to implement this decision]
1186
- \`\`\`
1407
+ Based on the user's goal, project context, available assets, timeframe, and concerns, provide:
1187
1408
 
1188
- Please provide:
1189
- 1. List of identified architectural decisions
1190
- 2. Generated ADR content for each decision
1191
- 3. Recommended file names and structure
1192
- 4. Implementation priority order
1409
+ ### 1. **Recommended Tool Sequence**
1410
+ Provide a step-by-step workflow with:
1411
+ - **Tool Name**: Exact tool to call
1412
+ - **Purpose**: Why this tool is needed
1413
+ - **Expected Outcome**: What it will deliver
1414
+ - **Parameters**: Suggested parameters for the tool call
1415
+ - **Success Criteria**: How to know it worked
1416
+
1417
+ ### 2. **Alternative Workflows**
1418
+ Provide 2-3 alternative approaches based on:
1419
+ - Different time constraints
1420
+ - Different priorities
1421
+ - Different starting points
1422
+
1423
+ ### 3. **Expected Timeline & Effort**
1424
+ For each recommended workflow:
1425
+ - **Estimated Time**: How long each step takes
1426
+ - **Effort Level**: Low/Medium/High effort required
1427
+ - **Dependencies**: Which steps must be completed first
1428
+
1429
+ ### 4. **Success Metrics**
1430
+ Define how to measure success:
1431
+ - **Immediate Indicators**: Quick wins and early signals
1432
+ - **Progress Milestones**: Key checkpoints
1433
+ - **Final Outcomes**: Ultimate success criteria
1434
+
1435
+ ### 5. **Common Pitfalls & Tips**
1436
+ - **What to Avoid**: Common mistakes in this workflow
1437
+ - **Pro Tips**: Best practices for maximum effectiveness
1438
+ - **Troubleshooting**: What to do if steps fail
1439
+
1440
+ ## Common Workflow Patterns
1441
+
1442
+ ### **New Project Setup**
1443
+ 1. analyze_project_ecosystem → 2. get_architectural_context → 3. suggest_adrs → 4. generate_adr_from_decision
1444
+
1445
+ ### **Existing Project Analysis**
1446
+ 1. discover_existing_adrs → 2. get_architectural_context → 3. generate_adr_todo → 4. validate_rules
1447
+
1448
+ ### **Security Audit**
1449
+ 1. analyze_content_security → 2. generate_content_masking → 3. configure_custom_patterns → 4. validate_content_masking
1450
+
1451
+ ### **PRD to Implementation**
1452
+ 1. generate_adrs_from_prd → 2. generate_adr_todo → 3. analyze_deployment_progress
1453
+
1454
+ ### **Legacy Modernization**
1455
+ 1. analyze_project_ecosystem → 2. get_architectural_context → 3. suggest_adrs → 4. generate_rules → 5. validate_rules
1456
+
1457
+ ## Output Format
1458
+
1459
+ Provide a comprehensive workflow guide that includes:
1460
+
1461
+ 1. **🎯 Recommended Primary Workflow** (step-by-step with tool calls)
1462
+ 2. **🔄 Alternative Approaches** (2-3 different paths)
1463
+ 3. **⏱️ Timeline & Effort Estimates** (realistic expectations)
1464
+ 4. **📊 Success Metrics** (how to measure progress)
1465
+ 5. **💡 Pro Tips & Best Practices** (maximize effectiveness)
1466
+ 6. **⚠️ Common Pitfalls** (what to avoid)
1467
+
1468
+ Make the guidance **actionable, specific, and outcome-focused** so the user can immediately start executing the recommended workflow.
1193
1469
  `;
1194
- return {
1195
- content: [
1196
- {
1197
- type: 'text',
1198
- text: `ADR generation from PRD: ${prdPath}\n\nPlease generate ADRs using the following prompt:\n\n${adrPrompt}`
1199
- }
1200
- ]
1201
- };
1470
+ // Execute the workflow guidance with AI if enabled
1471
+ const { executePromptWithFallback, formatMCPResponse } = await import('./utils/prompt-execution.js');
1472
+ const executionResult = await executePromptWithFallback(workflowPrompt, 'Analyze the user context and provide intelligent workflow guidance with specific tool recommendations.', {
1473
+ temperature: 0.1,
1474
+ maxTokens: 6000,
1475
+ systemPrompt: `You are an expert workflow advisor for the MCP ADR Analysis Server.
1476
+ Your role is to analyze user goals and project context, then recommend the optimal sequence of tools to achieve their objectives efficiently.
1477
+ Provide specific, actionable guidance with clear tool sequences, expected outcomes, and success criteria.
1478
+ Focus on practical workflows that deliver measurable results.`
1479
+ });
1480
+ if (executionResult.isAIGenerated) {
1481
+ // AI execution successful - return actual workflow guidance
1482
+ return formatMCPResponse({
1483
+ ...executionResult,
1484
+ content: `# Workflow Guidance & Tool Recommendations
1485
+
1486
+ ## Your Context
1487
+ - **Goal**: ${goal}
1488
+ - **Project Context**: ${projectContext}
1489
+ - **Available Assets**: ${availableAssets.length > 0 ? availableAssets.join(', ') : 'None specified'}
1490
+ - **Timeframe**: ${timeframe}
1491
+ - **Primary Concerns**: ${primaryConcerns.length > 0 ? primaryConcerns.join(', ') : 'General analysis'}
1492
+
1493
+ ## AI-Generated Workflow Guidance
1494
+
1495
+ ${executionResult.content}
1496
+
1497
+ ## Quick Reference: Available Tools
1498
+
1499
+ **Core Analysis**: analyze_project_ecosystem, get_architectural_context, generate_adrs_from_prd, analyze_content_security
1500
+ **ADR Management**: suggest_adrs, generate_adr_from_decision, discover_existing_adrs, generate_adr_todo
1501
+ **Security**: generate_content_masking, configure_custom_patterns, validate_content_masking
1502
+ **Governance**: generate_rules, validate_rules, create_rule_set
1503
+ **Environment**: analyze_environment, analyze_deployment_progress
1504
+ **Utilities**: manage_cache, configure_output_masking, check_ai_execution_status
1505
+
1506
+ ## Next Steps
1507
+
1508
+ 1. **Start with the recommended primary workflow** above
1509
+ 2. **Call the first tool** with the suggested parameters
1510
+ 3. **Review the results** and proceed to the next step
1511
+ 4. **Track progress** using the success metrics provided
1512
+ 5. **Adjust as needed** based on your specific findings
1513
+
1514
+ This guidance is tailored to your specific context and goals for maximum effectiveness!
1515
+ `,
1516
+ });
1517
+ }
1518
+ else {
1519
+ // Fallback to prompt-only mode
1520
+ return {
1521
+ content: [
1522
+ {
1523
+ type: 'text',
1524
+ text: workflowPrompt
1525
+ }
1526
+ ]
1527
+ };
1528
+ }
1202
1529
  }
1203
1530
  catch (error) {
1204
- throw new McpAdrError(`Failed to generate ADRs from PRD: ${error instanceof Error ? error.message : String(error)}`, 'GENERATION_ERROR');
1531
+ throw new McpAdrError(`Failed to generate workflow guidance: ${error instanceof Error ? error.message : String(error)}`, 'WORKFLOW_ERROR');
1205
1532
  }
1206
1533
  }
1207
- async generateAdrTodo(args) {
1208
- const { scope = 'all' } = args;
1209
- const adrDirectory = args.adrDirectory || this.config.adrDirectory;
1210
- this.logger.info(`Generating todo from ADRs in: ${adrDirectory}`);
1534
+ async getDevelopmentGuidance(args) {
1535
+ const { developmentPhase, adrsToImplement = [], technologyStack = [], currentProgress = '', teamContext = { size: 'small_team', experienceLevel: 'mixed' }, timeline = '', focusAreas = [] } = args;
1211
1536
  try {
1537
+ // Generate prompts for ADR discovery if ADRs are specified
1212
1538
  const { findFiles } = await import('./utils/file-system.js');
1213
- // Find all ADR files
1214
- const adrFiles = await findFiles(process.cwd(), [`${adrDirectory}/**/*.md`], { includeContent: true });
1215
- if (adrFiles.length === 0) {
1216
- throw new McpAdrError(`No ADR files found in ${adrDirectory}`, 'NO_ADRS_FOUND');
1539
+ let adrAnalysisPrompt = '';
1540
+ if (adrsToImplement.length > 0) {
1541
+ const { getAdrDirectoryPath } = await import('./utils/config.js');
1542
+ const absoluteAdrPath = getAdrDirectoryPath(this.config);
1543
+ const adrFileDiscovery = await findFiles(this.config.projectPath, [`${absoluteAdrPath}/**/*.md`], {
1544
+ includeContent: true,
1545
+ });
1546
+ adrAnalysisPrompt = `
1547
+ ## ADR Analysis for Implementation
1548
+
1549
+ ${adrFileDiscovery.prompt}
1550
+
1551
+ **ADRs to Implement**: ${adrsToImplement.join(', ')}
1552
+ **ADR Directory**: ${absoluteAdrPath}
1553
+ `;
1217
1554
  }
1218
- // Prepare ADR content for analysis
1219
- const adrContent = adrFiles.map(file => ({
1220
- filename: file.name,
1221
- path: file.path,
1222
- content: file.content || ''
1223
- }));
1224
- // Generate todo creation prompt
1225
- const todoPrompt = `
1226
- # ADR Todo Generation Request
1555
+ const developmentPrompt = `
1556
+ # Development Guidance & Implementation Roadmap
1227
1557
 
1228
- Please analyze the following Architectural Decision Records and generate a comprehensive todo.md file.
1558
+ ## Development Context
1559
+ - **Development Phase**: ${developmentPhase}
1560
+ - **Technology Stack**: ${technologyStack.length > 0 ? technologyStack.join(', ') : 'Not specified'}
1561
+ - **Current Progress**: ${currentProgress || 'Starting fresh'}
1562
+ - **Team Size**: ${teamContext.size}
1563
+ - **Team Experience**: ${teamContext.experienceLevel}
1564
+ - **Timeline**: ${timeline || 'Not specified'}
1565
+ - **Focus Areas**: ${focusAreas.length > 0 ? focusAreas.join(', ') : 'General development'}
1229
1566
 
1230
- ## ADR Files
1231
- ${adrContent.map(adr => `
1232
- ### ${adr.filename}
1233
- \`\`\`markdown
1234
- ${adr.content.slice(0, 1500)}${adr.content.length > 1500 ? '\n... (truncated)' : ''}
1235
- \`\`\`
1236
- `).join('')}
1567
+ ${adrAnalysisPrompt}
1237
1568
 
1238
- ## Requirements
1569
+ ## Development Guidance Instructions
1239
1570
 
1240
- 1. **Extract Tasks**: Identify all implementation tasks from ADRs
1241
- 2. **Categorize**: Group tasks by ADR and priority
1242
- 3. **Status Detection**: Determine task completion status based on:
1243
- - File existence checks
1244
- - Code analysis hints
1245
- - Implementation evidence
1246
- 4. **Progress Tracking**: Calculate overall progress
1247
- 5. **Scope Filter**: ${scope === 'all' ? 'Include all tasks' : `Focus on ${scope} tasks only`}
1571
+ Based on the development context, ADRs to implement, and technology stack, provide comprehensive development guidance including:
1248
1572
 
1249
- ## Todo.md Format
1573
+ ### 1. **Implementation Roadmap**
1574
+ Create a detailed development plan with:
1575
+ - **Phase-by-Phase Breakdown**: Logical development phases
1576
+ - **Task Prioritization**: Order tasks by dependencies and impact
1577
+ - **Milestone Definition**: Clear checkpoints and deliverables
1578
+ - **Risk Assessment**: Potential blockers and mitigation strategies
1250
1579
 
1251
- \`\`\`markdown
1252
- # ADR Implementation Progress
1580
+ ### 2. **Code Structure & Architecture**
1581
+ Provide specific guidance on:
1582
+ - **Project Structure**: How to organize code files and directories
1583
+ - **Module Architecture**: How to structure components/modules
1584
+ - **Design Patterns**: Which patterns to use and where
1585
+ - **Code Organization**: Separation of concerns and layering
1253
1586
 
1254
- **Last Updated**: [Date]
1255
- **Overall Progress**: [X]% Complete
1587
+ ### 3. **Implementation Patterns & Best Practices**
1588
+ For each technology in the stack, provide:
1589
+ - **Framework-Specific Patterns**: Best practices for the chosen frameworks
1590
+ - **API Design**: How to structure APIs and endpoints
1591
+ - **Data Layer**: Database schema and data access patterns
1592
+ - **State Management**: How to handle application state
1593
+ - **Error Handling**: Consistent error handling strategies
1256
1594
 
1257
- ## Summary
1258
- - Total ADRs: [count]
1259
- - Total Tasks: [count]
1260
- - Completed: [count]
1261
- - In Progress: [count]
1262
- - Pending: [count]
1595
+ ### 4. **ADR-to-Code Translation**
1596
+ For each ADR to implement:
1597
+ - **Implementation Tasks**: Specific coding tasks derived from the ADR
1598
+ - **Code Examples**: Pseudo-code or pattern examples
1599
+ - **Integration Points**: How this ADR affects other parts of the system
1600
+ - **Validation Criteria**: How to verify the ADR is properly implemented
1263
1601
 
1264
- ## Tasks by ADR
1602
+ ### 5. **Testing Strategy**
1603
+ Comprehensive testing approach:
1604
+ - **Unit Testing**: What to test and how
1605
+ - **Integration Testing**: API and component integration tests
1606
+ - **End-to-End Testing**: User workflow testing
1607
+ - **Performance Testing**: Load and performance validation
1608
+ - **Security Testing**: Security validation approaches
1265
1609
 
1266
- ### ADR-001: [Title]
1267
- - [ ] Task 1 description
1268
- - [x] Task 2 description (completed)
1269
- - [/] Task 3 description (in progress)
1610
+ ### 6. **Development Workflow**
1611
+ Team-specific guidance:
1612
+ - **Git Workflow**: Branching strategy and code review process
1613
+ - **CI/CD Pipeline**: Automated testing and deployment
1614
+ - **Code Quality**: Linting, formatting, and quality gates
1615
+ - **Documentation**: What to document and how
1270
1616
 
1271
- ### ADR-002: [Title]
1272
- - [ ] Task 1 description
1273
- ...
1274
- \`\`\`
1617
+ ### 7. **Quality Gates & Checkpoints**
1618
+ Define success criteria:
1619
+ - **Code Quality Metrics**: Coverage, complexity, maintainability
1620
+ - **Performance Benchmarks**: Response times, throughput targets
1621
+ - **Security Checkpoints**: Security validation at each phase
1622
+ - **Architectural Compliance**: Adherence to ADR decisions
1275
1623
 
1276
- Please provide:
1277
- 1. Comprehensive task extraction from all ADRs
1278
- 2. Status assessment for each task
1279
- 3. Progress calculation
1280
- 4. Prioritized task list
1281
- 5. Implementation recommendations
1624
+ ### 8. **Technology-Specific Implementation**
1625
+ For each technology in the stack, provide:
1626
+ - **Setup Instructions**: Environment and tooling setup
1627
+ - **Configuration**: Framework and tool configuration
1628
+ - **Optimization**: Performance and build optimization
1629
+ - **Deployment**: Technology-specific deployment considerations
1630
+
1631
+ ## Expected Output Format
1632
+
1633
+ Provide a comprehensive development guide that includes:
1634
+
1635
+ ### 📋 **1. Development Roadmap**
1636
+ - **Phase 1-N**: Logical development phases with tasks
1637
+ - **Dependencies**: Task dependencies and critical path
1638
+ - **Timeline**: Estimated effort and duration
1639
+ - **Milestones**: Key deliverables and checkpoints
1640
+
1641
+ ### 🏗️ **2. Implementation Guide**
1642
+ - **Code Structure**: Detailed project organization
1643
+ - **Design Patterns**: Specific patterns to implement
1644
+ - **API Design**: Endpoint structure and conventions
1645
+ - **Data Architecture**: Database and data flow design
1646
+
1647
+ ### 🧪 **3. Testing & Quality Strategy**
1648
+ - **Test Types**: Unit, integration, e2e testing approach
1649
+ - **Quality Gates**: Code quality and performance criteria
1650
+ - **Automation**: CI/CD and automated testing setup
1651
+
1652
+ ### 🚀 **4. Deployment & Operations**
1653
+ - **Environment Setup**: Development, staging, production
1654
+ - **Deployment Pipeline**: Automated deployment process
1655
+ - **Monitoring**: Logging, metrics, and alerting
1656
+ - **Maintenance**: Ongoing maintenance and updates
1657
+
1658
+ ### 📊 **5. Progress Tracking**
1659
+ - **Success Metrics**: How to measure development progress
1660
+ - **Quality Indicators**: Code quality and performance metrics
1661
+ - **Milestone Validation**: How to verify milestone completion
1662
+ - **Risk Monitoring**: Early warning signs and mitigation
1663
+
1664
+ ### 💡 **6. Team-Specific Recommendations**
1665
+ Based on team size (${teamContext.size}) and experience (${teamContext.experienceLevel}):
1666
+ - **Workflow Adaptations**: Process adjustments for team context
1667
+ - **Skill Development**: Areas for team skill building
1668
+ - **Tool Recommendations**: Development tools and practices
1669
+ - **Communication**: Coordination and documentation practices
1670
+
1671
+ ## Integration with Architectural Decisions
1672
+
1673
+ Ensure all development guidance:
1674
+ - **Aligns with ADRs**: Every recommendation supports architectural decisions
1675
+ - **Maintains Consistency**: Consistent patterns across the codebase
1676
+ - **Enables Evolution**: Flexible design for future changes
1677
+ - **Supports Quality**: Built-in quality and maintainability
1678
+
1679
+ Make the guidance **actionable, specific, and immediately implementable** so developers can start coding with confidence and architectural alignment.
1282
1680
  `;
1283
- return {
1284
- content: [
1285
- {
1286
- type: 'text',
1287
- text: `ADR todo generation for: ${adrDirectory}\n\nPlease generate todo.md using the following prompt:\n\n${todoPrompt}`
1288
- }
1289
- ]
1290
- };
1291
- }
1292
- catch (error) {
1293
- throw new McpAdrError(`Failed to generate ADR todo: ${error instanceof Error ? error.message : String(error)}`, 'GENERATION_ERROR');
1294
- }
1295
- }
1296
- /**
1297
- * Content masking tool implementations
1298
- */
1299
- async analyzeContentSecurity(args) {
1681
+ // Execute the development guidance with AI if enabled
1682
+ const { executePromptWithFallback, formatMCPResponse } = await import('./utils/prompt-execution.js');
1683
+ const executionResult = await executePromptWithFallback(developmentPrompt, 'Analyze the development context and provide comprehensive implementation guidance that translates architectural decisions into specific coding tasks and development roadmap.', {
1684
+ temperature: 0.1,
1685
+ maxTokens: 8000,
1686
+ systemPrompt: `You are an expert software development advisor specializing in translating architectural decisions into practical implementation guidance.
1687
+ Your role is to bridge the gap between architectural planning and actual code development.
1688
+ Provide specific, actionable development guidance with clear implementation steps, code patterns, and quality criteria.
1689
+ Focus on practical guidance that ensures architectural decisions are properly implemented in code.
1690
+ Consider team context, technology stack, and development phase to provide tailored recommendations.`
1691
+ });
1692
+ if (executionResult.isAIGenerated) {
1693
+ // AI execution successful - return actual development guidance
1694
+ return formatMCPResponse({
1695
+ ...executionResult,
1696
+ content: `# Development Guidance & Implementation Roadmap
1697
+
1698
+ ## Your Development Context
1699
+ - **Development Phase**: ${developmentPhase}
1700
+ - **Technology Stack**: ${technologyStack.length > 0 ? technologyStack.join(', ') : 'Not specified'}
1701
+ - **Current Progress**: ${currentProgress || 'Starting fresh'}
1702
+ - **Team Context**: ${teamContext.size} team with ${teamContext.experienceLevel} experience
1703
+ - **Timeline**: ${timeline || 'Not specified'}
1704
+ - **Focus Areas**: ${focusAreas.length > 0 ? focusAreas.join(', ') : 'General development'}
1705
+ - **ADRs to Implement**: ${adrsToImplement.length > 0 ? adrsToImplement.join(', ') : 'None specified'}
1706
+
1707
+ ## AI-Generated Development Guidance
1708
+
1709
+ ${executionResult.content}
1710
+
1711
+ ## Integration with Workflow Tools
1712
+
1713
+ This development guidance works seamlessly with other MCP tools:
1714
+
1715
+ ### **Workflow Integration**
1716
+ 1. **get_workflow_guidance** → Recommends architectural process
1717
+ 2. **get_development_guidance** → Guides implementation (this tool)
1718
+ 3. **validate_rules** → Ensures code follows architectural decisions
1719
+ 4. **analyze_deployment_progress** → Tracks implementation progress
1720
+
1721
+ ### **Quality Assurance Tools**
1722
+ - **generate_rules** → Extract coding standards from ADRs
1723
+ - **validate_rules** → Validate code against architectural rules
1724
+ - **analyze_content_security** → Security validation during development
1725
+
1726
+ ### **Documentation Tools**
1727
+ - **generate_adr_todo** → Create implementation task lists
1728
+ - **discover_existing_adrs** → Reference existing architectural decisions
1729
+
1730
+ ## Next Steps: From Architecture to Code
1731
+
1732
+ 1. **📋 Review the Development Roadmap** above
1733
+ 2. **🏗️ Set Up Project Structure** as recommended
1734
+ 3. **🧪 Implement Testing Strategy** early in development
1735
+ 4. **📊 Track Progress** using the success metrics provided
1736
+ 5. **🔄 Iterate and Refine** based on implementation learnings
1737
+
1738
+ This guidance ensures your development work is **architecturally aligned**, **quality-focused**, and **efficiently executed**!
1739
+ `,
1740
+ });
1741
+ }
1742
+ else {
1743
+ // Fallback to prompt-only mode
1744
+ return {
1745
+ content: [
1746
+ {
1747
+ type: 'text',
1748
+ text: developmentPrompt
1749
+ }
1750
+ ]
1751
+ };
1752
+ }
1753
+ }
1754
+ catch (error) {
1755
+ throw new McpAdrError(`Failed to generate development guidance: ${error instanceof Error ? error.message : String(error)}`, 'DEVELOPMENT_ERROR');
1756
+ }
1757
+ }
1758
+ async analyzeProjectEcosystem(args) {
1759
+ // Use configured project path if not provided in args
1760
+ const projectPath = args.projectPath || this.config.projectPath;
1761
+ const { includePatterns, enhancedMode = true, knowledgeEnhancement = true, learningEnabled = true, technologyFocus = [], analysisDepth = 'comprehensive', includeEnvironment = true, recursiveDepth = 'comprehensive', analysisScope = [] } = args;
1762
+ this.logger.info(`Generating comprehensive ecosystem analysis for project at: ${projectPath}`);
1763
+ this.logger.info(`Analysis configuration - Depth: ${analysisDepth}, Recursive: ${recursiveDepth}, Environment: ${includeEnvironment}`);
1764
+ this.logger.info(`Enhancement features - Knowledge: ${knowledgeEnhancement}, Learning: ${learningEnabled}`);
1765
+ this.logger.info(`Analysis scope: ${analysisScope.length > 0 ? analysisScope.join(', ') : 'Full ecosystem analysis'}`);
1766
+ try {
1767
+ // Import utilities dynamically to avoid circular dependencies
1768
+ const { analyzeProjectStructure } = await import('./utils/file-system.js');
1769
+ // Import advanced prompting utilities if enhanced mode is enabled
1770
+ let generateArchitecturalKnowledge = null;
1771
+ let executeWithReflexion = null;
1772
+ let retrieveRelevantMemories = null;
1773
+ let createToolReflexionConfig = null;
1774
+ if (enhancedMode) {
1775
+ if (knowledgeEnhancement) {
1776
+ const knowledgeModule = await import('./utils/knowledge-generation.js');
1777
+ generateArchitecturalKnowledge = knowledgeModule.generateArchitecturalKnowledge;
1778
+ }
1779
+ if (learningEnabled) {
1780
+ const reflexionModule = await import('./utils/reflexion.js');
1781
+ executeWithReflexion = reflexionModule.executeWithReflexion;
1782
+ retrieveRelevantMemories = reflexionModule.retrieveRelevantMemories;
1783
+ createToolReflexionConfig = reflexionModule.createToolReflexionConfig;
1784
+ }
1785
+ }
1786
+ // Step 1: Generate technology-specific knowledge if enabled
1787
+ let knowledgeContext = '';
1788
+ if (enhancedMode && knowledgeEnhancement && generateArchitecturalKnowledge) {
1789
+ try {
1790
+ const knowledgeResult = await generateArchitecturalKnowledge({
1791
+ projectPath,
1792
+ technologies: technologyFocus,
1793
+ patterns: [],
1794
+ projectType: 'ecosystem-analysis',
1795
+ existingAdrs: []
1796
+ }, {
1797
+ domains: this.getEcosystemAnalysisDomains(technologyFocus),
1798
+ depth: analysisDepth === 'basic' ? 'basic' : 'intermediate',
1799
+ cacheEnabled: true
1800
+ });
1801
+ knowledgeContext = `
1802
+ ## Technology-Specific Knowledge Enhancement
1803
+
1804
+ The following architectural knowledge has been generated to enhance ecosystem analysis:
1805
+
1806
+ ${knowledgeResult.prompt}
1807
+
1808
+ ---
1809
+ `;
1810
+ }
1811
+ catch (error) {
1812
+ this.logger.warn('Knowledge generation failed:', error);
1813
+ knowledgeContext = '<!-- Knowledge generation unavailable -->\n';
1814
+ }
1815
+ }
1816
+ // Step 2: Retrieve relevant memories if learning is enabled
1817
+ let reflexionContext = '';
1818
+ if (enhancedMode && learningEnabled && retrieveRelevantMemories) {
1819
+ try {
1820
+ const memoryResult = await retrieveRelevantMemories('ecosystem-analysis', { projectPath, analysisDepth, technologyFocus }, { maxResults: 5, relevanceThreshold: 0.6 });
1821
+ reflexionContext = `
1822
+ ## Learning from Past Analyses
1823
+
1824
+ The following insights from past ecosystem analysis tasks will inform this analysis:
1825
+
1826
+ ${memoryResult.prompt}
1827
+
1828
+ ---
1829
+ `;
1830
+ }
1831
+ catch (error) {
1832
+ this.logger.warn('Reflexion memory retrieval failed:', error);
1833
+ reflexionContext = '<!-- Learning context unavailable -->\n';
1834
+ }
1835
+ }
1836
+ // Step 3: Generate base project analysis prompt with recursive depth
1837
+ const baseProjectAnalysisPrompt = await analyzeProjectStructure(projectPath);
1838
+ // Step 4: Generate environment analysis if enabled
1839
+ let environmentAnalysisContext = '';
1840
+ if (includeEnvironment) {
1841
+ try {
1842
+ this.logger.info('Including comprehensive environment analysis in ecosystem analysis');
1843
+ const { analyzeEnvironment } = await import('./tools/environment-analysis-tool.js');
1844
+ // Call environment analysis with comprehensive scope
1845
+ const environmentResult = await analyzeEnvironment({
1846
+ projectPath,
1847
+ adrDirectory: this.config.adrDirectory,
1848
+ analysisType: 'comprehensive'
1849
+ });
1850
+ // Extract environment analysis content
1851
+ if (environmentResult.content && environmentResult.content[0]) {
1852
+ environmentAnalysisContext = `
1853
+ ## Integrated Environment Analysis
1854
+
1855
+ ${environmentResult.content[0].text}
1856
+
1857
+ ---
1858
+ `;
1859
+ }
1860
+ }
1861
+ catch (error) {
1862
+ this.logger.warn('Environment analysis integration failed:', error);
1863
+ environmentAnalysisContext = `
1864
+ ## Environment Analysis
1865
+ <!-- Environment analysis unavailable: ${error instanceof Error ? error.message : 'Unknown error'} -->
1866
+
1867
+ ---
1868
+ `;
1869
+ }
1870
+ }
1871
+ // Step 5: Apply Reflexion execution if learning is enabled
1872
+ let enhancedAnalysisPrompt = baseProjectAnalysisPrompt.prompt + environmentAnalysisContext;
1873
+ if (enhancedMode && learningEnabled && executeWithReflexion && createToolReflexionConfig) {
1874
+ try {
1875
+ const reflexionConfig = createToolReflexionConfig('analyze_project_ecosystem', {
1876
+ reflectionDepth: analysisDepth === 'basic' ? 'basic' : 'detailed',
1877
+ evaluationCriteria: ['task-success', 'accuracy', 'completeness'],
1878
+ learningRate: 0.7
1879
+ });
1880
+ const reflexionResult = await executeWithReflexion({
1881
+ prompt: baseProjectAnalysisPrompt.prompt + knowledgeContext + environmentAnalysisContext,
1882
+ instructions: baseProjectAnalysisPrompt.instructions,
1883
+ context: {
1884
+ projectPath,
1885
+ analysisDepth,
1886
+ recursiveDepth,
1887
+ technologyFocus,
1888
+ includePatterns,
1889
+ includeEnvironment,
1890
+ analysisScope,
1891
+ knowledgeEnhanced: knowledgeEnhancement,
1892
+ learningEnabled: true
1893
+ }
1894
+ }, reflexionConfig);
1895
+ enhancedAnalysisPrompt = reflexionResult.prompt;
1896
+ }
1897
+ catch (error) {
1898
+ this.logger.warn('Reflexion execution failed:', error);
1899
+ enhancedAnalysisPrompt = baseProjectAnalysisPrompt.prompt + knowledgeContext + environmentAnalysisContext;
1900
+ }
1901
+ }
1902
+ else {
1903
+ enhancedAnalysisPrompt = baseProjectAnalysisPrompt.prompt + knowledgeContext + environmentAnalysisContext;
1904
+ }
1905
+ // Execute the analysis with AI if enabled, otherwise return prompt
1906
+ const { executeEcosystemAnalysisPrompt, formatMCPResponse } = await import('./utils/prompt-execution.js');
1907
+ const executionResult = await executeEcosystemAnalysisPrompt(enhancedAnalysisPrompt, baseProjectAnalysisPrompt.instructions, {
1908
+ temperature: 0.1,
1909
+ maxTokens: 6000,
1910
+ });
1911
+ if (executionResult.isAIGenerated) {
1912
+ // AI execution successful - return actual analysis results
1913
+ return formatMCPResponse({
1914
+ ...executionResult,
1915
+ content: `# Comprehensive Project Ecosystem Analysis Results
1916
+
1917
+ ## Analysis Configuration
1918
+ - **Project Path**: ${projectPath}
1919
+ - **Analysis Depth**: ${analysisDepth}
1920
+ - **Recursive Depth**: ${recursiveDepth}
1921
+ - **Environment Analysis**: ${includeEnvironment ? '✅ Included' : '❌ Excluded'}
1922
+ - **Analysis Scope**: ${analysisScope.length > 0 ? analysisScope.join(', ') : 'Full ecosystem analysis'}
1923
+
1924
+ ## Enhancement Features
1925
+ - **Knowledge Generation**: ${enhancedMode && knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
1926
+ - **Reflexion Learning**: ${enhancedMode && learningEnabled ? '✅ Enabled' : '❌ Disabled'}
1927
+ - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
1928
+ - **Technology Focus**: ${technologyFocus.length > 0 ? technologyFocus.join(', ') : 'Auto-detect'}
1929
+
1930
+ ${knowledgeContext}
1931
+
1932
+ ${reflexionContext}
1933
+
1934
+ ## Comprehensive Ecosystem Analysis Results
1935
+
1936
+ ${executionResult.content}
1937
+
1938
+ ${includeEnvironment ? `
1939
+
1940
+ ## Environment Integration Summary
1941
+
1942
+ The analysis above includes comprehensive environment analysis covering:
1943
+ - **Infrastructure Specifications**: Deployment and runtime environment details
1944
+ - **Containerization**: Docker, Kubernetes, and container orchestration analysis
1945
+ - **Environment Requirements**: Configuration and dependency requirements
1946
+ - **Compliance Assessment**: Security and regulatory compliance evaluation
1947
+
1948
+ This integrated approach provides complete understanding of both codebase patterns AND operational environment.
1949
+ ` : ''}
1950
+
1951
+ ## Next Steps: Complete Ecosystem Understanding
1952
+
1953
+ Based on the comprehensive analysis above:
1954
+
1955
+ ### **Immediate Actions**
1956
+ 1. **Review Ecosystem Overview**: Examine the complete technology stack and environment context
1957
+ 2. **Assess Integration Points**: Understand how code patterns relate to operational environment
1958
+ 3. **Identify Critical Dependencies**: Focus on key dependencies between code and infrastructure
1959
+
1960
+ ### **Strategic Planning**
1961
+ 4. **Address Architectural Issues**: Prioritize improvements based on both code and environment analysis
1962
+ 5. **Plan Environment Optimization**: Optimize deployment and operational configurations
1963
+ 6. **Update Documentation**: Document both architectural decisions and environment specifications
1964
+
1965
+ ### **Implementation Roadmap**
1966
+ 7. **Implement Code Improvements**: Execute code-level architectural enhancements
1967
+ 8. **Optimize Environment**: Improve infrastructure and deployment configurations
1968
+ 9. **Monitor Integration**: Ensure code and environment changes work together effectively
1969
+
1970
+ This comprehensive ecosystem analysis provides the foundation for informed architectural and operational decisions.
1971
+ `,
1972
+ });
1973
+ }
1974
+ else {
1975
+ // Fallback to prompt-only mode
1976
+ return {
1977
+ content: [
1978
+ {
1979
+ type: 'text',
1980
+ text: `# Comprehensive Project Ecosystem Analysis
1981
+
1982
+ This comprehensive analysis provides deep recursive project understanding with integrated environment analysis.
1983
+
1984
+ ## Analysis Configuration
1985
+ - **Project Path**: ${projectPath}
1986
+ - **Analysis Depth**: ${analysisDepth}
1987
+ - **Recursive Depth**: ${recursiveDepth}
1988
+ - **Environment Analysis**: ${includeEnvironment ? '✅ Included' : '❌ Excluded'}
1989
+ - **Analysis Scope**: ${analysisScope.length > 0 ? analysisScope.join(', ') : 'Full ecosystem analysis'}
1990
+
1991
+ ## Enhancement Features
1992
+ - **Knowledge Generation**: ${enhancedMode && knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
1993
+ - **Reflexion Learning**: ${enhancedMode && learningEnabled ? '✅ Enabled' : '❌ Disabled'}
1994
+ - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
1995
+ - **Technology Focus**: ${technologyFocus.length > 0 ? technologyFocus.join(', ') : 'Auto-detect'}
1996
+ - **Include Patterns**: ${includePatterns?.length ? includePatterns.join(', ') : 'Default patterns'}
1997
+
1998
+ ${knowledgeContext}
1999
+
2000
+ ${reflexionContext}
2001
+
2002
+ ## Enhanced Analysis Prompt
2003
+
2004
+ ${enhancedAnalysisPrompt}
2005
+
2006
+ ## Enhanced Implementation Instructions
2007
+
2008
+ ${baseProjectAnalysisPrompt.instructions}
2009
+
2010
+ ### Enhancement-Specific Instructions
2011
+
2012
+ ${enhancedMode && knowledgeEnhancement ? `
2013
+ #### Knowledge Enhancement
2014
+ - Apply technology-specific knowledge to ecosystem analysis
2015
+ - Use domain expertise to identify patterns and anti-patterns
2016
+ - Leverage architectural best practices for technology stack evaluation
2017
+ ` : ''}
2018
+
2019
+ ${enhancedMode && learningEnabled ? `
2020
+ #### Learning Integration
2021
+ - Apply lessons learned from past ecosystem analyses
2022
+ - Use memory insights to improve pattern recognition accuracy
2023
+ - Incorporate feedback from previous analysis outcomes
2024
+ ` : ''}
2025
+
2026
+ ## Expected Enhanced Output
2027
+
2028
+ The enhanced analysis should provide:
2029
+ 1. **Technology Stack Analysis** with domain knowledge context
2030
+ 2. **Architectural Pattern Detection** informed by past experiences
2031
+ 3. **Ecosystem Health Assessment** using learned evaluation criteria
2032
+ 4. **Improvement Recommendations** based on domain best practices
2033
+ 5. **Learning Insights** for future analysis improvement
2034
+
2035
+ ## Quality Assurance
2036
+
2037
+ - Ensure analysis leverages all available enhancement features
2038
+ - Verify technology-specific knowledge is properly applied
2039
+ - Confirm learning insights improve analysis accuracy
2040
+ - Validate recommendations align with domain best practices`
2041
+ }
2042
+ ]
2043
+ };
2044
+ }
2045
+ }
2046
+ catch (error) {
2047
+ throw new McpAdrError(`Failed to analyze project ecosystem: ${error instanceof Error ? error.message : String(error)}`, 'ANALYSIS_ERROR');
2048
+ }
2049
+ }
2050
+ async getArchitecturalContext(args) {
2051
+ const { filePath, includeCompliance = true } = args;
2052
+ try {
2053
+ const { analyzeProjectStructure, fileExists, ensureDirectory } = await import('./utils/file-system.js');
2054
+ const path = await import('path');
2055
+ // Determine project path
2056
+ const projectPath = filePath ? filePath.split('/').slice(0, -1).join('/') : this.config.projectPath;
2057
+ const adrDirectory = path.join(projectPath, this.config.adrDirectory);
2058
+ // Generate prompts for ADR directory setup
2059
+ const adrDirectoryCheckPrompt = await fileExists(adrDirectory);
2060
+ const adrDirectorySetupPrompt = await ensureDirectory(adrDirectory);
2061
+ // Generate architectural analysis prompt
2062
+ const projectAnalysisPrompt = await analyzeProjectStructure(projectPath);
2063
+ const architecturalPrompt = `
2064
+ # Architectural Context Analysis & Project Setup
2065
+
2066
+ ## Project Overview
2067
+ **Project Path**: ${projectPath}
2068
+ **Analysis Scope**: ${filePath ? `Specific file: ${filePath}` : 'Entire project'}
2069
+ **ADR Directory**: ${this.config.adrDirectory}
2070
+ **Include Compliance**: ${includeCompliance ? 'Yes' : 'No'}
2071
+
2072
+ ## 🚀 ADR Infrastructure Setup
2073
+
2074
+ This analysis will include setting up ADR infrastructure if needed:
2075
+
2076
+ ### ADR Directory Check
2077
+ ${adrDirectoryCheckPrompt.prompt}
2078
+
2079
+ ### ADR Directory Setup (if needed)
2080
+ ${adrDirectorySetupPrompt.prompt}
2081
+
2082
+ ## Comprehensive Project Analysis
2083
+
2084
+ ${projectAnalysisPrompt.prompt}
2085
+
2086
+ ## Enhanced Architectural Focus
2087
+
2088
+ Please provide a **comprehensive, outcome-focused analysis** including:
2089
+
2090
+ ### 1. Technology Stack & Infrastructure Analysis
2091
+ - **Core Technologies**: Programming languages, frameworks, runtime environments
2092
+ - **Dependencies**: Package managers, third-party libraries, version constraints
2093
+ - **Build & Deployment**: CI/CD pipelines, build tools, deployment strategies
2094
+ - **Data Layer**: Databases, caching, data storage and retrieval patterns
2095
+
2096
+ ### 2. Architectural Pattern & Design Analysis
2097
+ - **System Architecture**: Monolith, microservices, serverless, hybrid patterns
2098
+ - **Code Organization**: Module structure, separation of concerns, layering
2099
+ - **API Design**: REST, GraphQL, RPC patterns and conventions
2100
+ - **Data Flow**: Request/response cycles, event handling, state management
2101
+ ${filePath ? `- **File-specific Context**: How ${filePath} fits into the overall architecture` : ''}
2102
+
2103
+ ### 3. Quality, Security & Performance Assessment
2104
+ - **Code Quality**: Structure, naming, documentation, testing strategies
2105
+ - **Security Implementation**: Authentication, authorization, data protection
2106
+ - **Performance Patterns**: Caching, optimization, scalability considerations
2107
+ - **Monitoring & Observability**: Logging, metrics, error tracking
2108
+
2109
+ ### 4. Architectural Decision Discovery & Documentation
2110
+ - **Explicit Decisions**: Find existing documentation and decision records
2111
+ - **Implicit Decisions**: Identify significant undocumented architectural choices
2112
+ - **Technology Rationale**: Understand selection criteria and trade-offs
2113
+ - **Evolution Path**: How the architecture has changed over time
2114
+
2115
+ ${includeCompliance ? `### 5. Compliance & Standards Assessment
2116
+ - **Industry Standards**: Adherence to relevant industry standards and best practices
2117
+ - **Security Compliance**: Security standards compliance (OWASP, SOC2, etc.)
2118
+ - **Code Standards**: Coding standards and style guide compliance
2119
+ - **Architectural Compliance**: Adherence to established architectural principles
2120
+ - **Regulatory Requirements**: Any regulatory compliance requirements (GDPR, HIPAA, etc.)` : ''}
2121
+
2122
+ ## Expected Output: Outcome-Focused Architectural Context
2123
+
2124
+ Provide a **comprehensive architectural context** with **clear project outcomes**:
2125
+
2126
+ ### 📋 **1. Executive Summary & Project Outcomes**
2127
+ - **Current State**: What the project is and what it does
2128
+ - **Architectural Maturity**: Assessment of current architectural practices
2129
+ - **Key Strengths**: What's working well architecturally
2130
+ - **Critical Gaps**: What needs immediate attention
2131
+ - **Success Metrics**: How to measure architectural improvements
2132
+
2133
+ ### 🔧 **2. Technology & Infrastructure Inventory**
2134
+ - **Technology Stack**: Complete inventory with versions and purposes
2135
+ - **Infrastructure Components**: Deployment, monitoring, data storage
2136
+ - **Dependencies**: Critical dependencies and potential risks
2137
+ - **Tool Chain**: Development, testing, and deployment tools
2138
+
2139
+ ### 🏗️ **3. Architectural Patterns & Design Decisions**
2140
+ - **System Design**: Overall architectural approach and patterns
2141
+ - **Component Architecture**: How major components interact
2142
+ - **Data Architecture**: How data flows and is managed
2143
+ - **Integration Patterns**: How external systems are integrated
2144
+
2145
+ ### 📊 **4. Quality & Compliance Assessment**
2146
+ - **Code Quality Score**: Assessment of current code quality
2147
+ - **Security Posture**: Security implementation and gaps
2148
+ - **Performance Profile**: Current performance characteristics
2149
+ - **Maintainability Index**: How easy the system is to maintain and evolve
2150
+
2151
+ ### 🎯 **5. Outcome-Focused Action Plan**
2152
+ Based on the analysis, provide a **clear workflow** with **projected outcomes**:
2153
+
2154
+ #### **Immediate Actions (Next 1-2 weeks)**
2155
+ - **Priority 1**: Most critical architectural issues to address
2156
+ - **Quick Wins**: Low-effort, high-impact improvements
2157
+ - **Documentation**: Essential decisions that need immediate documentation
2158
+
2159
+ #### **Short-term Goals (Next 1-3 months)**
2160
+ - **Architectural Improvements**: Planned enhancements with expected outcomes
2161
+ - **Technical Debt**: Priority technical debt to address
2162
+ - **Process Improvements**: Development workflow enhancements
2163
+
2164
+ #### **Long-term Vision (3-12 months)**
2165
+ - **Strategic Architecture**: Long-term architectural evolution
2166
+ - **Scalability Roadmap**: How to scale the system effectively
2167
+ - **Innovation Opportunities**: Areas for architectural innovation
2168
+
2169
+ ### 📈 **6. Success Metrics & Outcomes**
2170
+ Define **measurable outcomes** for architectural improvements:
2171
+
2172
+ - **Performance Metrics**: Response times, throughput, resource utilization
2173
+ - **Quality Metrics**: Code coverage, bug rates, maintainability scores
2174
+ - **Developer Experience**: Build times, deployment frequency, developer satisfaction
2175
+ - **Business Impact**: Feature delivery speed, system reliability, cost efficiency
2176
+
2177
+ ### 🏗️ **7. ADR Infrastructure & Documentation Plan**
2178
+
2179
+ If ADR directory doesn't exist, also provide:
2180
+
2181
+ 1. **Create Directory Structure**:
2182
+ \`\`\`
2183
+ ${this.config.adrDirectory}/
2184
+ ├── 0001-record-architecture-decisions.md (template)
2185
+ ├── README.md (ADR process guide)
2186
+ └── template.md (ADR template)
2187
+ \`\`\`
2188
+
2189
+ 2. **Generate Initial ADRs** for discovered architectural decisions
2190
+ 3. **Create ADR Process Guide** for the team
2191
+ 4. **Establish ADR Workflow** for future decisions
2192
+
2193
+ ### 🔄 **8. Continuous Improvement Workflow**
2194
+ Establish ongoing architectural governance:
2195
+
2196
+ - **Regular Reviews**: Monthly architectural health checks
2197
+ - **Decision Documentation**: Process for documenting new architectural decisions
2198
+ - **Compliance Monitoring**: Ongoing adherence to architectural standards
2199
+ - **Evolution Planning**: Quarterly architectural roadmap updates
2200
+
2201
+ ## Next Steps: Grounded Project Workflow
2202
+
2203
+ After this analysis, follow this **outcome-focused workflow**:
2204
+
2205
+ 1. **📋 Review Analysis**: Examine the architectural context and recommendations
2206
+ 2. **🎯 Set Priorities**: Choose 3-5 most impactful improvements based on outcomes
2207
+ 3. **📝 Document Decisions**: Create ADRs for significant architectural choices
2208
+ 4. **🔧 Implement Changes**: Execute improvements in priority order
2209
+ 5. **📊 Measure Progress**: Track success metrics and outcomes
2210
+ 6. **🔄 Iterate**: Regular reviews and continuous improvement
2211
+
2212
+ This approach ensures that architectural work is **grounded in measurable outcomes** and **aligned with project success**.
2213
+ `;
2214
+ // Execute the analysis with AI if enabled, otherwise return prompt
2215
+ const { executeEcosystemAnalysisPrompt, formatMCPResponse } = await import('./utils/prompt-execution.js');
2216
+ const executionResult = await executeEcosystemAnalysisPrompt(architecturalPrompt, projectAnalysisPrompt.instructions, {
2217
+ temperature: 0.1,
2218
+ maxTokens: 5000,
2219
+ systemPrompt: `You are a senior software architect specializing in architectural context analysis.
2220
+ Analyze the provided project to understand its architectural patterns, design decisions, and structural organization.
2221
+ Focus on providing actionable insights about the architecture that can guide development decisions.`
2222
+ });
2223
+ if (executionResult.isAIGenerated) {
2224
+ // AI execution successful - return actual analysis results
2225
+ return formatMCPResponse({
2226
+ ...executionResult,
2227
+ content: `# Architectural Context Analysis Results
2228
+
2229
+ ${filePath ? `## Target File: ${filePath}` : '## Project-wide Analysis'}
2230
+
2231
+ ## Project Information
2232
+ - **Project Path**: ${projectPath}
2233
+ - **Analysis Scope**: ${filePath ? 'File-specific' : 'Project-wide'}
2234
+ - **ADR Directory**: ${this.config.adrDirectory}
2235
+
2236
+ ## ADR Infrastructure Setup
2237
+
2238
+ The analysis includes automatic ADR infrastructure setup:
2239
+
2240
+ ${adrDirectoryCheckPrompt.instructions}
2241
+
2242
+ ${adrDirectorySetupPrompt.instructions}
2243
+
2244
+ ## AI Analysis Results
2245
+
2246
+ ${executionResult.content}
2247
+
2248
+ ## Outcome-Focused Next Steps
2249
+
2250
+ Based on the architectural analysis, follow this **grounded workflow**:
2251
+
2252
+ ### **Immediate Actions (This Week)**
2253
+ 1. **Review Analysis**: Examine the architectural context and recommendations above
2254
+ 2. **Set Up ADRs**: Ensure ADR directory structure is created and ready
2255
+ 3. **Identify Quick Wins**: Focus on low-effort, high-impact improvements
2256
+
2257
+ ### **Short-term Goals (Next Month)**
2258
+ 4. **Document Key Decisions**: Create ADRs for the most significant architectural choices
2259
+ 5. **Address Critical Issues**: Tackle the highest-priority architectural concerns
2260
+ 6. **Establish Metrics**: Set up measurement for the success metrics identified
2261
+
2262
+ ### **Long-term Vision (Next Quarter)**
2263
+ 7. **Implement Roadmap**: Execute the architectural improvement plan
2264
+ 8. **Monitor Progress**: Track success metrics and adjust approach as needed
2265
+ 9. **Continuous Improvement**: Establish regular architectural reviews
2266
+
2267
+ This **outcome-focused approach** ensures architectural work delivers **measurable value** and keeps the project **grounded in clear objectives**.
2268
+ `,
2269
+ });
2270
+ }
2271
+ else {
2272
+ // Fallback to prompt-only mode
2273
+ return {
2274
+ content: [
2275
+ {
2276
+ type: 'text',
2277
+ text: architecturalPrompt
2278
+ }
2279
+ ]
2280
+ };
2281
+ }
2282
+ }
2283
+ catch (error) {
2284
+ throw new McpAdrError(`Failed to get architectural context: ${error instanceof Error ? error.message : String(error)}`, 'ANALYSIS_ERROR');
2285
+ }
2286
+ }
2287
+ async generateAdrsFromPrd(args) {
2288
+ const { prdPath, enhancedMode = true, promptOptimization = true, knowledgeEnhancement = true, prdType = 'general' } = args;
2289
+ const outputDirectory = args.outputDirectory || this.config.adrDirectory;
2290
+ this.logger.info(`Generating enhanced ADRs from PRD: ${prdPath} to ${outputDirectory}`);
2291
+ this.logger.info(`Enhancement features - APE: ${promptOptimization}, Knowledge: ${knowledgeEnhancement}, Type: ${prdType}`);
2292
+ try {
2293
+ const { readFileContent, fileExists } = await import('./utils/file-system.js');
2294
+ // Import advanced prompting utilities if enhanced mode is enabled
2295
+ let generateArchitecturalKnowledge = null;
2296
+ let optimizePromptWithAPE = null;
2297
+ let createToolAPEConfig = null;
2298
+ if (enhancedMode) {
2299
+ if (knowledgeEnhancement) {
2300
+ const knowledgeModule = await import('./utils/knowledge-generation.js');
2301
+ generateArchitecturalKnowledge = knowledgeModule.generateArchitecturalKnowledge;
2302
+ }
2303
+ if (promptOptimization) {
2304
+ const apeModule = await import('./utils/automatic-prompt-engineering.js');
2305
+ optimizePromptWithAPE = apeModule.optimizePromptWithAPE;
2306
+ createToolAPEConfig = apeModule.createToolAPEConfig;
2307
+ }
2308
+ }
2309
+ // Generate file existence check prompt
2310
+ const fileExistsPrompt = await fileExists(prdPath);
2311
+ // Generate file content reading prompt
2312
+ const fileContentPrompt = await readFileContent(prdPath);
2313
+ // Step 1: Generate domain-specific knowledge if enabled
2314
+ let knowledgeContext = '';
2315
+ if (enhancedMode && knowledgeEnhancement && generateArchitecturalKnowledge) {
2316
+ try {
2317
+ const knowledgeResult = await generateArchitecturalKnowledge({
2318
+ projectPath: outputDirectory,
2319
+ technologies: [],
2320
+ patterns: [],
2321
+ projectType: prdType,
2322
+ existingAdrs: []
2323
+ }, {
2324
+ domains: this.getPrdTypeDomains(prdType),
2325
+ depth: 'intermediate',
2326
+ cacheEnabled: true
2327
+ });
2328
+ knowledgeContext = `
2329
+ ## Domain-Specific Knowledge Enhancement
2330
+
2331
+ The following architectural knowledge has been generated to enhance PRD analysis and ADR creation:
2332
+
2333
+ ${knowledgeResult.prompt}
2334
+
2335
+ ---
2336
+ `;
2337
+ }
2338
+ catch (error) {
2339
+ this.logger.warn('Knowledge generation failed:', error);
2340
+ knowledgeContext = '<!-- Knowledge generation unavailable -->\n';
2341
+ }
2342
+ }
2343
+ // Step 2: Create base ADR generation prompt
2344
+ const baseAdrPrompt = this.createBaseAdrPrompt(prdPath, outputDirectory, knowledgeContext);
2345
+ // Step 3: Apply APE optimization if enabled
2346
+ let finalAdrPrompt = baseAdrPrompt;
2347
+ if (enhancedMode && promptOptimization && optimizePromptWithAPE && createToolAPEConfig) {
2348
+ try {
2349
+ const apeConfig = createToolAPEConfig('generate_adrs_from_prd', {
2350
+ candidateCount: 5,
2351
+ evaluationCriteria: ['task-completion', 'clarity', 'specificity'],
2352
+ optimizationRounds: 2,
2353
+ qualityThreshold: 0.75
2354
+ });
2355
+ const apeResult = await optimizePromptWithAPE({
2356
+ prompt: baseAdrPrompt,
2357
+ instructions: 'Generate comprehensive ADRs from PRD analysis',
2358
+ context: { prdPath, outputDirectory, prdType, knowledgeEnhanced: knowledgeEnhancement }
2359
+ }, apeConfig);
2360
+ finalAdrPrompt = apeResult.prompt;
2361
+ }
2362
+ catch (error) {
2363
+ this.logger.warn('APE optimization failed:', error);
2364
+ finalAdrPrompt = baseAdrPrompt;
2365
+ }
2366
+ }
2367
+ // Generate comprehensive ADR creation prompt that includes file operations
2368
+ const adrPrompt = `
2369
+ # Enhanced ADR Generation from PRD Request
2370
+
2371
+ This is a comprehensive prompt-driven ADR generation process enhanced with advanced prompting techniques.
2372
+
2373
+ ## Enhancement Status
2374
+ - **APE Optimization**: ${enhancedMode && promptOptimization ? '✅ Enabled' : '❌ Disabled'}
2375
+ - **Knowledge Generation**: ${enhancedMode && knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
2376
+ - **PRD Type**: ${prdType}
2377
+ - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
2378
+
2379
+ ## Step 1: File Validation
2380
+ ${fileExistsPrompt.prompt}
2381
+
2382
+ **Instructions**: First, execute the file existence check above. If the file does not exist, stop the process and report the error. Only proceed to Step 2 if the file exists.
2383
+
2384
+ ## Step 2: PRD Content Reading
2385
+ ${fileContentPrompt.prompt}
2386
+
2387
+ **Instructions**: Execute the file reading operation above to obtain the PRD content. Use the content from this step for the enhanced ADR generation in Step 3.
2388
+
2389
+ ## Step 3: Enhanced ADR Generation
2390
+
2391
+ ${enhancedMode && promptOptimization ? `
2392
+ ### APE-Optimized Analysis
2393
+ This prompt has been optimized using Automatic Prompt Engineering for superior ADR generation quality.
2394
+ The optimization focused on task completion, clarity, and specificity for PRD analysis.
2395
+
2396
+ ` : ''}
2397
+
2398
+ ${finalAdrPrompt}
2399
+
2400
+ ### File Creation Instructions
2401
+
2402
+ For each generated ADR, create a file creation prompt using the following pattern:
2403
+ - **File Path**: ${outputDirectory}/[number]-[decision-title].md
2404
+ - **Content**: The complete enhanced ADR markdown content
2405
+ - **Action Confirmation**: Require user confirmation before creating files
2406
+ - **Security Validation**: Ensure output directory is safe and authorized
2407
+
2408
+ ### Enhanced Quality Assurance
2409
+
2410
+ - Ensure each ADR leverages domain knowledge when available
2411
+ - Verify decisions align with PRD type best practices
2412
+ - Check that enhancement features are properly utilized
2413
+ - Validate that ADR content exceeds baseline quality expectations
2414
+ - Confirm all decisions are traceable back to PRD requirements with domain context
2415
+ `;
2416
+ // Execute the ADR generation with AI if enabled, otherwise return prompt
2417
+ const { executeADRGenerationPrompt, formatMCPResponse } = await import('./utils/prompt-execution.js');
2418
+ const executionResult = await executeADRGenerationPrompt(adrPrompt, 'Generate comprehensive ADRs from PRD analysis with enhanced domain knowledge and optimization', {
2419
+ temperature: 0.1,
2420
+ maxTokens: 8000,
2421
+ systemPrompt: `You are an expert software architect who creates comprehensive Architectural Decision Records (ADRs) from Product Requirements Documents (PRDs).
2422
+ Generate well-structured ADRs that follow best practices and include all necessary sections.
2423
+ Focus on extracting architectural decisions from the PRD and creating actionable ADRs with clear reasoning.`
2424
+ });
2425
+ if (executionResult.isAIGenerated) {
2426
+ // AI execution successful - return actual ADR generation results
2427
+ return formatMCPResponse({
2428
+ ...executionResult,
2429
+ content: `# ADR Generation from PRD Results
2430
+
2431
+ ## Enhancement Features
2432
+ - **APE Optimization**: ${enhancedMode && promptOptimization ? '✅ Enabled' : '❌ Disabled'}
2433
+ - **Knowledge Generation**: ${enhancedMode && knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
2434
+ - **PRD Type Optimization**: ${prdType}
2435
+ - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
2436
+
2437
+ ## Source Information
2438
+ - **PRD Path**: ${prdPath}
2439
+ - **Output Directory**: ${outputDirectory}
2440
+
2441
+ ## Generated ADRs
2442
+
2443
+ ${executionResult.content}
2444
+
2445
+ ## Next Steps
2446
+
2447
+ 1. **Review Generated ADRs**: Examine each ADR for completeness and accuracy
2448
+ 2. **Save ADR Files**: Create individual .md files for each ADR in ${outputDirectory}
2449
+ 3. **Update ADR Index**: Add new ADRs to your project's ADR catalog
2450
+ 4. **Stakeholder Review**: Share ADRs with team for feedback and approval
2451
+ 5. **Implementation Planning**: Create tasks for implementing the architectural decisions
2452
+
2453
+ ## File Creation Commands
2454
+
2455
+ To save the generated ADRs, create individual files in ${outputDirectory}:
2456
+
2457
+ \`\`\`bash
2458
+ # Create ADR directory if it doesn't exist
2459
+ mkdir -p ${outputDirectory}
2460
+
2461
+ # Save each ADR as a separate file (example)
2462
+ # Replace [NUMBER] and [TITLE] with actual values from generated ADRs
2463
+ # cat > "${outputDirectory}/001-example-decision.md" << 'EOF'
2464
+ # [ADR content here]
2465
+ # EOF
2466
+ \`\`\`
2467
+ `,
2468
+ });
2469
+ }
2470
+ else {
2471
+ // Fallback to prompt-only mode
2472
+ return {
2473
+ content: [
2474
+ {
2475
+ type: 'text',
2476
+ text: `# Enhanced ADR Generation from PRD: ${prdPath}
2477
+
2478
+ ## Advanced Prompt-Driven ADR Generation Process
2479
+
2480
+ This tool uses a 100% prompt-driven architecture enhanced with advanced prompting techniques:
2481
+
2482
+ ### Enhancement Features
2483
+ - **APE Optimization**: ${enhancedMode && promptOptimization ? '✅ Enabled - Prompts optimized for superior quality' : '❌ Disabled'}
2484
+ - **Knowledge Generation**: ${enhancedMode && knowledgeEnhancement ? '✅ Enabled - Domain knowledge enhanced analysis' : '❌ Disabled'}
2485
+ - **PRD Type Optimization**: ${prdType} - Tailored for specific domain requirements
2486
+ - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled - All advanced features active' : '❌ Disabled - Basic mode'}
2487
+
2488
+ ### Enhanced AI Agent Workflow
2489
+
2490
+ 1. **Validate PRD file existence** using secure file system operations
2491
+ 2. **Read PRD content** safely with proper security validation
2492
+ 3. **Apply domain knowledge** to enhance understanding (if enabled)
2493
+ 4. **Generate optimized ADRs** using APE-enhanced prompts (if enabled)
2494
+ 5. **Create enhanced ADR files** in the specified output directory: ${outputDirectory}
2495
+
2496
+ ## Execution Instructions
2497
+
2498
+ Please execute the following enhanced comprehensive prompt:
2499
+
2500
+ ${adrPrompt}
2501
+
2502
+ ## Advanced Features
2503
+
2504
+ ${enhancedMode && knowledgeEnhancement ? `
2505
+ ### Knowledge Enhancement
2506
+ - Domain-specific architectural knowledge has been generated
2507
+ - PRD analysis is enhanced with ${prdType} domain expertise
2508
+ - ADR decisions leverage domain best practices and patterns
2509
+ ` : ''}
2510
+
2511
+ ${enhancedMode && promptOptimization ? `
2512
+ ### APE Optimization
2513
+ - Prompts have been automatically optimized for quality
2514
+ - Enhanced evaluation criteria ensure superior ADR generation
2515
+ - Optimization focused on task completion, clarity, and specificity
2516
+ ` : ''}
2517
+
2518
+ ## Security and Validation
2519
+
2520
+ - All file operations include security validation
2521
+ - Path traversal protection is enabled
2522
+ - System directory access is prevented
2523
+ - User confirmation is required for file creation
2524
+ - Content validation ensures safe enhanced ADR generation
2525
+
2526
+ ## Expected Enhanced Workflow
2527
+
2528
+ 1. Execute file existence check for: ${prdPath}
2529
+ 2. If file exists, read PRD content securely
2530
+ 3. Apply domain knowledge to enhance PRD understanding
2531
+ 4. Analyze PRD content using optimized prompts
2532
+ 5. Generate domain-enhanced individual ADRs for each decision
2533
+ 6. Create file creation prompts for each enhanced ADR
2534
+ 7. Confirm with user before writing files to: ${outputDirectory}
2535
+
2536
+ The enhanced process maintains full traceability from PRD requirements to generated ADRs while providing superior quality through advanced prompting techniques and ensuring security and user control over file operations.`
2537
+ }
2538
+ ]
2539
+ };
2540
+ }
2541
+ }
2542
+ catch (error) {
2543
+ throw new McpAdrError(`Failed to generate ADR prompts from PRD: ${error instanceof Error ? error.message : String(error)}`, 'PROMPT_GENERATION_ERROR');
2544
+ }
2545
+ }
2546
+ async generateAdrTodo(args) {
2547
+ const { scope = 'all' } = args;
2548
+ const { getAdrDirectoryPath } = await import('./utils/config.js');
2549
+ const path = await import('path');
2550
+ // Use absolute ADR path relative to project
2551
+ const absoluteAdrPath = args.adrDirectory ?
2552
+ path.resolve(this.config.projectPath, args.adrDirectory) :
2553
+ getAdrDirectoryPath(this.config);
2554
+ // Keep relative path for display purposes
2555
+ const adrDirectory = args.adrDirectory || this.config.adrDirectory;
2556
+ this.logger.info(`Generating todo prompt for ADRs in: ${absoluteAdrPath}`);
2557
+ try {
2558
+ const { findFiles } = await import('./utils/file-system.js');
2559
+ // Generate file discovery prompt for ADR files using project path as base
2560
+ const adrFilesPrompt = await findFiles(this.config.projectPath, [`${absoluteAdrPath}/**/*.md`], { includeContent: true });
2561
+ // Generate comprehensive todo creation prompt
2562
+ const todoPrompt = `
2563
+ # ADR Todo Generation Request
2564
+
2565
+ ## Step 1: File Discovery
2566
+ ${adrFilesPrompt.prompt}
2567
+
2568
+ ## Step 2: Todo Generation Analysis
2569
+
2570
+ Once you have discovered and read the ADR files, please analyze them and generate a comprehensive todo.md file.
2571
+
2572
+ ## Requirements
2573
+
2574
+ 1. **Extract Tasks**: Identify all implementation tasks from ADRs
2575
+ 2. **Categorize**: Group tasks by ADR and priority
2576
+ 3. **Status Detection**: Determine task completion status based on:
2577
+ - File existence checks
2578
+ - Code analysis hints
2579
+ - Implementation evidence
2580
+ 4. **Progress Tracking**: Calculate overall progress
2581
+ 5. **Scope Filter**: ${scope === 'all' ? 'Include all tasks' : `Focus on ${scope} tasks only`}
2582
+
2583
+ ## Todo.md Format
2584
+
2585
+ \`\`\`markdown
2586
+ # ADR Implementation Progress
2587
+
2588
+ **Last Updated**: [Date]
2589
+ **Overall Progress**: [X]% Complete
2590
+
2591
+ ## Summary
2592
+ - Total ADRs: [count]
2593
+ - Total Tasks: [count]
2594
+ - Completed: [count]
2595
+ - In Progress: [count]
2596
+ - Pending: [count]
2597
+
2598
+ ## Tasks by ADR
2599
+
2600
+ ### ADR-001: [Title]
2601
+ - [ ] Task 1 description
2602
+ - [x] Task 2 description (completed)
2603
+ - [/] Task 3 description (in progress)
2604
+
2605
+ ### ADR-002: [Title]
2606
+ - [ ] Task 1 description
2607
+ ...
2608
+ \`\`\`
2609
+
2610
+ Please provide:
2611
+ 1. Comprehensive task extraction from all ADRs
2612
+ 2. Status assessment for each task
2613
+ 3. Progress calculation
2614
+ 4. Prioritized task list
2615
+ 5. Implementation recommendations
2616
+ `;
2617
+ // Execute the todo generation with AI if enabled, otherwise return prompt
2618
+ const { executePromptWithFallback, formatMCPResponse } = await import('./utils/prompt-execution.js');
2619
+ const executionResult = await executePromptWithFallback(todoPrompt, 'Generate comprehensive todo.md file from ADR analysis with task extraction and progress tracking', {
2620
+ temperature: 0.1,
2621
+ maxTokens: 6000,
2622
+ systemPrompt: `You are an expert project manager specializing in ADR implementation tracking.
2623
+ Analyze the provided ADRs to extract actionable tasks and create a comprehensive todo.md file.
2624
+ Focus on identifying concrete implementation steps, tracking progress, and providing clear priorities.
2625
+ Ensure the todo.md file follows the specified format and includes all necessary details.`,
2626
+ responseFormat: 'text'
2627
+ });
2628
+ if (executionResult.isAIGenerated) {
2629
+ // AI execution successful - return actual todo generation results
2630
+ return formatMCPResponse({
2631
+ ...executionResult,
2632
+ content: `# ADR Todo Generation Results
2633
+
2634
+ ## Analysis Information
2635
+ - **ADR Directory**: ${adrDirectory}
2636
+ - **Scope**: ${scope}
2637
+
2638
+ ## AI Todo Generation Results
2639
+
2640
+ ${executionResult.content}
2641
+
2642
+ ## Next Steps
2643
+
2644
+ Based on the generated todo list:
2645
+
2646
+ 1. **Review Generated Tasks**: Examine each task for accuracy and completeness
2647
+ 2. **Prioritize Implementation**: Order tasks by importance and dependencies
2648
+ 3. **Assign Responsibilities**: Determine who will work on each task
2649
+ 4. **Track Progress**: Use the todo.md file to monitor implementation progress
2650
+ 5. **Update Regularly**: Keep the todo list current as work progresses
2651
+
2652
+ ## Todo Management
2653
+
2654
+ The generated todo.md file includes:
2655
+ - **Overall Progress**: Percentage completion tracking
2656
+ - **Task Categories**: Tasks organized by ADR
2657
+ - **Status Indicators**: Clear progress markers ([ ], [x], [/])
2658
+ - **Priority Levels**: High, medium, low priority assignments
2659
+ - **Implementation Guidance**: Specific steps for each task
2660
+
2661
+ ## Integration Commands
2662
+
2663
+ To update the todo list as work progresses:
2664
+ \`\`\`json
2665
+ {
2666
+ "tool": "generate_adr_todo",
2667
+ "args": {
2668
+ "adrDirectory": "${adrDirectory}",
2669
+ "scope": "pending"
2670
+ }
2671
+ }
2672
+ \`\`\`
2673
+ `,
2674
+ });
2675
+ }
2676
+ else {
2677
+ // Fallback to prompt-only mode
2678
+ return {
2679
+ content: [
2680
+ {
2681
+ type: 'text',
2682
+ text: `ADR todo generation for: ${adrDirectory}\n\nPlease generate todo.md using the following prompt:\n\n${todoPrompt}`
2683
+ }
2684
+ ]
2685
+ };
2686
+ }
2687
+ }
2688
+ catch (error) {
2689
+ throw new McpAdrError(`Failed to generate ADR todo: ${error instanceof Error ? error.message : String(error)}`, 'GENERATION_ERROR');
2690
+ }
2691
+ }
2692
+ /**
2693
+ * Content masking tool implementations
2694
+ */
2695
+ async analyzeContentSecurity(args) {
1300
2696
  const { analyzeContentSecurity } = await import('./tools/content-masking-tool.js');
1301
2697
  return await analyzeContentSecurity(args);
1302
2698
  }
@@ -1322,29 +2718,55 @@ Please provide:
1322
2718
  const { clearCache, getCacheStats, cleanupCache, invalidateCache } = await import('./utils/cache.js');
1323
2719
  switch (action) {
1324
2720
  case 'clear': {
1325
- await clearCache();
2721
+ const clearPrompt = await clearCache();
1326
2722
  return {
1327
2723
  content: [
1328
2724
  {
1329
2725
  type: 'text',
1330
- text: '✅ Cache cleared successfully. All cached resources have been removed.'
2726
+ text: `# Cache Clear Operation
2727
+
2728
+ ## AI Delegation Required
2729
+
2730
+ Please execute the following cache clearing operation:
2731
+
2732
+ ${clearPrompt.prompt}
2733
+
2734
+ ## Implementation Instructions
2735
+
2736
+ ${clearPrompt.instructions}
2737
+
2738
+ ## Expected Result
2739
+
2740
+ After successful execution, all cache entries will be removed while preserving the cache directory structure and metadata.json file.`
1331
2741
  }
1332
2742
  ]
1333
2743
  };
1334
2744
  }
1335
2745
  case 'stats': {
1336
- const stats = await getCacheStats();
2746
+ const statsPrompt = await getCacheStats();
1337
2747
  return {
1338
2748
  content: [
1339
2749
  {
1340
2750
  type: 'text',
1341
- text: `# Cache Statistics
2751
+ text: `# Cache Statistics Collection
2752
+
2753
+ ## AI Delegation Required
2754
+
2755
+ Please execute the following cache statistics collection operation:
1342
2756
 
1343
- ## Overview
1344
- - **Total Entries**: ${stats.totalEntries}
1345
- - **Total Size**: ${(stats.totalSize / 1024).toFixed(2)} KB
1346
- - **Oldest Entry**: ${stats.oldestEntry || 'None'}
1347
- - **Newest Entry**: ${stats.newestEntry || 'None'}
2757
+ ${statsPrompt.prompt}
2758
+
2759
+ ## Implementation Instructions
2760
+
2761
+ ${statsPrompt.instructions}
2762
+
2763
+ ## Expected Information
2764
+
2765
+ The AI agent will provide:
2766
+ - **Total Entries**: Number of cache files
2767
+ - **Total Size**: Combined size of all cache files
2768
+ - **Oldest Entry**: Cache key of the oldest entry
2769
+ - **Newest Entry**: Cache key of the newest entry
1348
2770
 
1349
2771
  ## Cache Directory
1350
2772
  \`.mcp-adr-cache/\`
@@ -1358,19 +2780,32 @@ Please provide:
1358
2780
  Use \`manage_cache\` tool with different actions:
1359
2781
  - \`clear\`: Remove all cache entries
1360
2782
  - \`cleanup\`: Remove expired entries only
1361
- - \`invalidate\`: Remove specific cache entry
1362
- `
2783
+ - \`invalidate\`: Remove specific cache entry`
1363
2784
  }
1364
2785
  ]
1365
2786
  };
1366
2787
  }
1367
2788
  case 'cleanup': {
1368
- const cleanedCount = await cleanupCache();
2789
+ const cleanupPrompt = await cleanupCache();
1369
2790
  return {
1370
2791
  content: [
1371
2792
  {
1372
2793
  type: 'text',
1373
- text: `✅ Cache cleanup completed. Removed ${cleanedCount} expired entries.`
2794
+ text: `# Cache Cleanup Operation
2795
+
2796
+ ## AI Delegation Required
2797
+
2798
+ Please execute the following cache cleanup operation:
2799
+
2800
+ ${cleanupPrompt.prompt}
2801
+
2802
+ ## Implementation Instructions
2803
+
2804
+ ${cleanupPrompt.instructions}
2805
+
2806
+ ## Expected Result
2807
+
2808
+ The AI agent will remove expired cache entries and provide a count of cleaned files.`
1374
2809
  }
1375
2810
  ]
1376
2811
  };
@@ -1379,12 +2814,28 @@ Use \`manage_cache\` tool with different actions:
1379
2814
  if (!key) {
1380
2815
  throw new McpAdrError('Cache key is required for invalidate action', 'INVALID_INPUT');
1381
2816
  }
1382
- await invalidateCache(key);
2817
+ const invalidatePrompt = await invalidateCache(key);
1383
2818
  return {
1384
2819
  content: [
1385
2820
  {
1386
2821
  type: 'text',
1387
- text: `✅ Cache entry invalidated: ${key}`
2822
+ text: `# Cache Invalidation Operation
2823
+
2824
+ ## AI Delegation Required
2825
+
2826
+ Please execute the following cache invalidation operation:
2827
+
2828
+ ${invalidatePrompt.prompt}
2829
+
2830
+ ## Implementation Instructions
2831
+
2832
+ ${invalidatePrompt.instructions}
2833
+
2834
+ ## Target Cache Entry
2835
+
2836
+ **Cache Key**: ${key}
2837
+
2838
+ The AI agent will safely remove the specified cache entry.`
1388
2839
  }
1389
2840
  ]
1390
2841
  };
@@ -1497,6 +2948,165 @@ ${newConfig.enabled ?
1497
2948
  throw new McpAdrError(`Output masking configuration failed: ${error instanceof Error ? error.message : String(error)}`, 'CONFIG_ERROR');
1498
2949
  }
1499
2950
  }
2951
+ /**
2952
+ * Helper method to get domains based on PRD type
2953
+ */
2954
+ getPrdTypeDomains(prdType) {
2955
+ const domainMap = {
2956
+ 'web-application': ['api-design', 'frontend-architecture', 'database-design', 'security'],
2957
+ 'mobile-app': ['mobile-architecture', 'api-design', 'performance-optimization', 'security'],
2958
+ 'microservices': ['microservices', 'api-design', 'distributed-systems', 'database-design'],
2959
+ 'data-platform': ['database-design', 'data-architecture', 'performance-optimization', 'scalability'],
2960
+ 'api-service': ['api-design', 'microservices', 'security', 'performance-optimization'],
2961
+ 'general': ['api-design', 'database-design', 'security']
2962
+ };
2963
+ return domainMap[prdType] || domainMap['general'] || ['api-design', 'database-design', 'security'];
2964
+ }
2965
+ /**
2966
+ * Helper method to get domains for ecosystem analysis based on technology focus
2967
+ */
2968
+ getEcosystemAnalysisDomains(technologyFocus) {
2969
+ // Base domains for ecosystem analysis
2970
+ const baseDomains = ['api-design', 'database-design', 'security', 'performance-optimization'];
2971
+ // Technology-specific domain mapping
2972
+ const technologyDomainMap = {
2973
+ 'react': ['frontend-architecture', 'web-applications'],
2974
+ 'vue': ['frontend-architecture', 'web-applications'],
2975
+ 'angular': ['frontend-architecture', 'web-applications'],
2976
+ 'node': ['api-design', 'microservices'],
2977
+ 'express': ['api-design', 'web-applications'],
2978
+ 'fastify': ['api-design', 'performance-optimization'],
2979
+ 'nestjs': ['api-design', 'microservices'],
2980
+ 'spring': ['api-design', 'microservices'],
2981
+ 'django': ['api-design', 'web-applications'],
2982
+ 'flask': ['api-design', 'web-applications'],
2983
+ 'rails': ['api-design', 'web-applications'],
2984
+ 'laravel': ['api-design', 'web-applications'],
2985
+ 'docker': ['containerization', 'microservices'],
2986
+ 'kubernetes': ['containerization', 'distributed-systems'],
2987
+ 'mongodb': ['database-design', 'data-architecture'],
2988
+ 'postgresql': ['database-design', 'data-architecture'],
2989
+ 'mysql': ['database-design', 'data-architecture'],
2990
+ 'redis': ['database-design', 'performance-optimization'],
2991
+ 'elasticsearch': ['database-design', 'data-architecture'],
2992
+ 'kafka': ['distributed-systems', 'data-architecture'],
2993
+ 'rabbitmq': ['distributed-systems', 'microservices'],
2994
+ 'aws': ['cloud-architecture', 'scalability'],
2995
+ 'azure': ['cloud-architecture', 'scalability'],
2996
+ 'gcp': ['cloud-architecture', 'scalability'],
2997
+ 'terraform': ['infrastructure-as-code', 'cloud-architecture'],
2998
+ 'ansible': ['infrastructure-as-code', 'automation'],
2999
+ 'jenkins': ['ci-cd', 'automation'],
3000
+ 'github-actions': ['ci-cd', 'automation'],
3001
+ 'gitlab-ci': ['ci-cd', 'automation']
3002
+ };
3003
+ // Collect domains based on technology focus
3004
+ const technologyDomains = new Set();
3005
+ for (const tech of technologyFocus) {
3006
+ const techLower = tech.toLowerCase();
3007
+ const domains = technologyDomainMap[techLower];
3008
+ if (domains) {
3009
+ domains.forEach(domain => technologyDomains.add(domain));
3010
+ }
3011
+ }
3012
+ // Combine base domains with technology-specific domains
3013
+ const allDomains = [...baseDomains, ...Array.from(technologyDomains)];
3014
+ // Remove duplicates and limit to reasonable number
3015
+ const uniqueDomains = [...new Set(allDomains)];
3016
+ // Return up to 6 most relevant domains
3017
+ return uniqueDomains.slice(0, 6);
3018
+ }
3019
+ /**
3020
+ * Helper method to create base ADR generation prompt
3021
+ */
3022
+ createBaseAdrPrompt(prdPath, outputDirectory, knowledgeContext) {
3023
+ return `
3024
+ # Enhanced ADR Generation from PRD Request
3025
+
3026
+ This is a comprehensive prompt-driven ADR generation process enhanced with domain knowledge and optimized prompting.
3027
+
3028
+ ${knowledgeContext}
3029
+
3030
+ ## Step 1: File Validation
3031
+ Please verify that the PRD file exists at: ${prdPath}
3032
+
3033
+ ## Step 2: PRD Content Reading
3034
+ Read and analyze the PRD content from: ${prdPath}
3035
+
3036
+ ## Step 3: Enhanced ADR Generation and Creation
3037
+
3038
+ Once you have successfully read the PRD content, analyze it using the domain knowledge above and generate Architectural Decision Records (ADRs).
3039
+
3040
+ ### Enhanced Analysis Requirements
3041
+
3042
+ 1. **Extract Key Decisions**: Identify all architectural decisions implied or stated in the PRD
3043
+ 2. **Apply Domain Knowledge**: Use the generated domain knowledge to enhance decision analysis
3044
+ 3. **Decision Categorization**: Group decisions by:
3045
+ - Technology stack choices (informed by domain best practices)
3046
+ - Architectural patterns (leveraging domain-specific patterns)
3047
+ - Infrastructure decisions (considering domain requirements)
3048
+ - Security considerations (applying domain security knowledge)
3049
+ - Performance requirements (using domain performance insights)
3050
+ - Integration approaches (following domain integration patterns)
3051
+
3052
+ ### Enhanced ADR Generation Requirements
3053
+
3054
+ 1. **Follow ADR Format**: Use standard ADR template with domain-enhanced content
3055
+ 2. **Number Sequentially**: Use format 001-decision-title.md, 002-next-decision.md, etc.
3056
+ 3. **Output Directory**: Place ADRs in ${outputDirectory}/
3057
+ 4. **Domain Context**: Include relevant domain knowledge in each ADR
3058
+ 5. **File Creation**: Generate file creation prompts for each ADR
3059
+
3060
+ ### Enhanced ADR Template Format
3061
+
3062
+ \`\`\`markdown
3063
+ # [Number]. [Title]
3064
+
3065
+ **Status**: [Proposed/Accepted/Deprecated/Superseded]
3066
+ **Date**: [YYYY-MM-DD]
3067
+ **Domain**: [Relevant domain from knowledge enhancement]
3068
+
3069
+ ## Context
3070
+ [Describe the context and problem statement from PRD, enhanced with domain knowledge]
3071
+
3072
+ ## Decision
3073
+ [Describe the architectural decision, informed by domain best practices]
3074
+
3075
+ ## Consequences
3076
+ [Describe positive and negative consequences, considering domain-specific implications]
3077
+
3078
+ ## Domain Considerations
3079
+ [Specific considerations from the domain knowledge that influenced this decision]
3080
+
3081
+ ## Implementation Plan
3082
+ [Steps to implement this decision, leveraging domain expertise]
3083
+
3084
+ ## Related PRD Sections
3085
+ [Reference specific sections from the PRD that led to this decision]
3086
+
3087
+ ## Domain References
3088
+ [References to domain knowledge that informed this decision]
3089
+ \`\`\`
3090
+
3091
+ ### Expected Enhanced Output
3092
+
3093
+ Please provide:
3094
+ 1. **File Validation Results**: Confirmation that PRD file exists and is readable
3095
+ 2. **PRD Content Summary**: Brief summary enhanced with domain context
3096
+ 3. **Domain Analysis**: How domain knowledge applies to this PRD
3097
+ 4. **Identified Decisions**: List of all architectural decisions with domain context
3098
+ 5. **Generated ADRs**: Complete enhanced ADR content for each decision
3099
+ 6. **File Creation Plan**: File names, directory structure, and creation order
3100
+ 7. **Implementation Priority**: Recommended order considering domain best practices
3101
+
3102
+ ### Quality Assurance with Domain Enhancement
3103
+
3104
+ - Ensure each ADR leverages relevant domain knowledge
3105
+ - Verify decisions align with domain best practices
3106
+ - Check that domain considerations are properly documented
3107
+ - Validate that ADR content is enhanced beyond basic analysis
3108
+ `;
3109
+ }
1500
3110
  /**
1501
3111
  * ADR suggestion tool implementations
1502
3112
  */
@@ -1572,16 +3182,16 @@ ${newConfig.enabled ?
1572
3182
  }
1573
3183
  catch (error) {
1574
3184
  // If masking fails, log warning and return original response
1575
- console.warn('Output masking failed:', error);
3185
+ // Log to stderr to avoid corrupting MCP protocol
3186
+ console.error('[WARN] Output masking failed:', error);
1576
3187
  return response;
1577
3188
  }
1578
3189
  }
1579
3190
  /**
1580
- * Read MCP resource with caching
3191
+ * Read MCP resource with prompt-driven caching
1581
3192
  */
1582
3193
  async readResource(uri) {
1583
3194
  try {
1584
- const { getCachedOrGenerate } = await import('./utils/cache.js');
1585
3195
  // Parse URI to determine resource type and parameters
1586
3196
  const url = new globalThis.URL(uri);
1587
3197
  const resourceType = url.pathname.replace('/', '');
@@ -1590,7 +3200,8 @@ ${newConfig.enabled ?
1590
3200
  case 'architectural_knowledge_graph': {
1591
3201
  const { generateArchitecturalKnowledgeGraph } = await import('./resources/index.js');
1592
3202
  const projectPath = params['projectPath'] || process.cwd();
1593
- const result = await getCachedOrGenerate(`knowledge-graph:${projectPath}`, () => generateArchitecturalKnowledgeGraph(projectPath), { ttl: 3600 });
3203
+ // Generate resource directly (caching is now handled through AI delegation)
3204
+ const result = await generateArchitecturalKnowledgeGraph(projectPath);
1594
3205
  return {
1595
3206
  contents: [
1596
3207
  {
@@ -1605,7 +3216,8 @@ ${newConfig.enabled ?
1605
3216
  const { generateAnalysisReport } = await import('./resources/index.js');
1606
3217
  const projectPath = params['projectPath'] || process.cwd();
1607
3218
  const focusAreas = params['focusAreas'] ? params['focusAreas'].split(',') : undefined;
1608
- const result = await getCachedOrGenerate(`analysis-report:${projectPath}:${focusAreas?.join(',') || ''}`, () => generateAnalysisReport(projectPath, focusAreas), { ttl: 1800 });
3219
+ // Generate resource directly (caching is now handled through AI delegation)
3220
+ const result = await generateAnalysisReport(projectPath, focusAreas);
1609
3221
  return {
1610
3222
  contents: [
1611
3223
  {
@@ -1618,8 +3230,14 @@ ${newConfig.enabled ?
1618
3230
  }
1619
3231
  case 'adr_list': {
1620
3232
  const { generateAdrList } = await import('./resources/index.js');
1621
- const adrDirectory = params['adrDirectory'] || 'docs/adrs';
1622
- const result = await getCachedOrGenerate(`adr-list:${adrDirectory}`, () => generateAdrList(adrDirectory), { ttl: 900 });
3233
+ const { getAdrDirectoryPath } = await import('./utils/config.js');
3234
+ const path = await import('path');
3235
+ // Use absolute ADR path relative to project
3236
+ const absoluteAdrPath = params['adrDirectory'] ?
3237
+ path.resolve(this.config.projectPath, params['adrDirectory']) :
3238
+ getAdrDirectoryPath(this.config);
3239
+ // Generate resource directly (caching is now handled through AI delegation)
3240
+ const result = await generateAdrList(absoluteAdrPath, this.config.projectPath);
1623
3241
  return {
1624
3242
  contents: [
1625
3243
  {
@@ -1713,7 +3331,8 @@ Examples:
1713
3331
  }
1714
3332
  }
1715
3333
  // Start the server if this file is run directly
1716
- if (import.meta.url === `file://${process.argv[1]}`) {
3334
+ // Jest-compatible check: avoid import.meta.url which Jest cannot handle
3335
+ if (process.argv[1] && (process.argv[1].endsWith('index.js') || process.argv[1].endsWith('index.ts'))) {
1717
3336
  main().catch((error) => {
1718
3337
  console.error('Unhandled error:', error);
1719
3338
  process.exit(1);