generate_deployment_guidance
Produce tailored deployment guidance from ADRs, including scripts, configurations, and validation steps for specific environments like development, staging, or production.
Instructions
Generate deployment guidance and instructions from ADRs with environment-specific configurations
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| adrDirectory | No | Directory containing ADR files | docs/adrs |
| customRequirements | No | Additional custom requirements | |
| environment | No | Target deployment environment | production |
| format | No | Output format for guidance | markdown |
| generateFiles | No | Actually generate files (vs just guidance) | |
| includeConfigs | No | Generate configuration files | |
| includeRollback | No | Include rollback procedures | |
| includeScripts | No | Generate deployment scripts | |
| includeValidation | No | Include validation and health checks | |
| projectPath | No | Project root path (optional, uses configured PROJECT_PATH if not provided) | |
| technologyFilter | No | Filter by specific technology categories |
Implementation Reference
- The core handler function that implements generate_deployment_guidance tool. Discovers ADRs, analyzes environment, generates comprehensive AI prompts for deployment guidance including prerequisites, infrastructure, database, application deployment, configs, validation, rollback with Mermaid diagrams.export async function generateDeploymentGuidance(args: { adrDirectory?: string; environment?: 'development' | 'staging' | 'production' | 'all'; format?: 'markdown' | 'scripts' | 'structured' | 'all'; projectPath?: string; includeScripts?: boolean; includeConfigs?: boolean; includeValidation?: boolean; technologyFilter?: string[]; customRequirements?: string[]; includeRollback?: boolean; generateFiles?: boolean; }): Promise<any> { const { adrDirectory = 'docs/adrs', environment = 'production', format = 'markdown', projectPath = process.cwd(), includeScripts = true, includeConfigs = true, includeValidation = true, technologyFilter, customRequirements, includeRollback = true, generateFiles = false, } = args; try { // Use existing ADR discovery const { discoverAdrsInDirectory } = await import('../utils/adr-discovery.js'); const discoveryResult = await discoverAdrsInDirectory(adrDirectory, projectPath, { includeContent: true, includeTimeline: false, }); if (discoveryResult.adrs.length === 0) { return { content: [ { type: 'text', text: `# No ADRs Found for Deployment Guidance ## Searched Location - **ADR Directory**: ${adrDirectory} - **Project Path**: ${projectPath} ## Recommendations 1. Create ADRs with deployment-relevant decisions 2. Include technology choices (Docker, databases, web servers) 3. Specify infrastructure requirements 4. Document configuration parameters ## Example ADR for Deployment \`\`\`markdown # ADR-001: Use Docker for Containerization ## Status Accepted ## Context We need consistent deployment across environments. ## Decision Use Docker containers with docker-compose for orchestration. ## Consequences - Consistent environment across dev/staging/production - Requires container registry and orchestration setup - Port 3000 for application, 5432 for PostgreSQL \`\`\` `, }, ], }; } // Research current deployment environment let environmentContext = ''; try { const orchestrator = new ResearchOrchestrator(projectPath, adrDirectory); const research = await orchestrator.answerResearchQuestion( `Analyze deployment requirements for ${environment} environment: 1. What deployment infrastructure is currently available? 2. What deployment patterns are documented in ADRs? 3. Are there existing deployment scripts or configurations? 4. What are the deployment constraints or requirements?` ); const envSource = research.sources.find(s => s.type === 'environment'); const capabilities = envSource?.data?.capabilities || []; environmentContext = ` ## ๐ Current Environment Analysis **Research Confidence**: ${(research.confidence * 100).toFixed(1)}% ### Available Infrastructure ${capabilities.length > 0 ? capabilities.map((c: string) => `- ${c}`).join('\n') : '- No infrastructure tools detected'} ### Deployment Context ${research.answer || 'No specific deployment context found'} ### Key Findings ${research.sources.map(s => `- ${s.type}: Consulted`).join('\n')} `; } catch (error) { environmentContext = `\n## โ ๏ธ Environment Analysis Failed\n${error instanceof Error ? error.message : String(error)}\n`; } // Create comprehensive deployment guidance prompt const deploymentPrompt = ` # Deployment Guidance Generation You are an expert DevOps engineer tasked with creating comprehensive deployment guidance from Architectural Decision Records (ADRs). ## Project Context - **Project**: ${projectPath.split('/').pop() || 'Unknown'} - **Target Environment**: ${environment} - **ADR Directory**: ${adrDirectory} - **Total ADRs**: ${discoveryResult.adrs.length} ${environmentContext} ## ADR Content ${discoveryResult.adrs .map( adr => ` ### ${adr.title} (${adr.filename}) **Status**: ${adr.status} **Content**: \`\`\`markdown ${adr.content?.slice(0, 1000) || 'No content available'}${adr.content && adr.content.length > 1000 ? '...' : ''} \`\`\` ` ) .join('\n')} ## Deployment Analysis Instructions Analyze the ADRs above and extract deployment-relevant information to create comprehensive deployment guidance: ### 1. **Technology Extraction** Identify technologies mentioned in ADRs that require deployment: - **Databases**: PostgreSQL, MySQL, MongoDB, Redis, etc. - **Web Servers**: Nginx, Apache, Node.js, Python, etc. - **Containers**: Docker, Kubernetes, container orchestration - **Infrastructure**: Cloud providers, servers, networking - **Security**: TLS, authentication, secrets management - **Monitoring**: Logging, metrics, health checks ### 2. **Configuration Requirements** Extract specific configuration details: - **Ports**: Application ports, database ports, service ports - **Environment Variables**: Required env vars for ${environment} - **Resource Limits**: Memory, CPU, storage requirements - **Dependencies**: Service dependencies and startup order ### 3. **Environment-Specific Considerations** For **${environment}** environment: ${ environment === 'production' ? ` - **Security**: TLS certificates, secure connections, secrets management - **Performance**: Load balancing, caching, optimization - **Reliability**: Backup procedures, monitoring, alerting - **Scalability**: Auto-scaling, resource allocation ` : environment === 'staging' ? ` - **Testing**: Staging-specific configurations - **Data**: Test data setup, database seeding - **Integration**: External service connections ` : ` - **Development**: Hot-reload, debugging, local services - **Convenience**: Simplified setup, development tools ` } ### 4. **Deployment Steps Generation** Create step-by-step deployment instructions: 1. **Prerequisites**: Required tools, access, dependencies 2. **Infrastructure Setup**: Server/cloud setup, networking 3. **Database Setup**: Database creation, schema, migrations 4. **Application Deployment**: Build, deploy, configure 5. **Service Configuration**: Web server, load balancer, SSL 6. **Verification**: Health checks, smoke tests, monitoring **IMPORTANT**: Include visual diagrams in your deployment guidance using mermaid syntax: #### Required Diagrams: 1. **Deployment Sequence Diagram** - Show the flow from ADRs โ Scripts โ Environment \`\`\`mermaid sequenceDiagram participant User as Developer participant Tool as Deployment Tool participant ADR as ADR Documents participant Script as Deploy Scripts participant Env as ${environment.charAt(0).toUpperCase() + environment.slice(1)} Environment User->>Tool: Generate deployment guidance Tool->>ADR: Read architectural decisions ADR-->>Tool: Technology stack & configs Tool->>Script: Generate deploy scripts Script->>Env: Deploy components Env-->>Script: Deployment status Script-->>User: Success & validation steps \`\`\` 2. **Deployment Workflow Diagram** - Show the phase-by-phase deployment process \`\`\`mermaid flowchart TD Start([Start Deployment]) --> Detect[Detect Platform from ADRs] Detect --> LoadADR[Read Technology Decisions] LoadADR --> GenScripts[Generate Deploy Scripts] GenScripts --> Phase1[Prerequisites Validation] Phase1 --> Phase2[Infrastructure Setup] Phase2 --> Phase3[Database Deployment] Phase3 --> Phase4[Application Deployment] Phase4 --> Validate{Validation<br/>Passed?} Validate -->|No| Fix[Auto-fix Issues] Fix --> Phase4 Validate -->|Yes| Success([โ Deployment Success]) style Start fill:#e1f5ff style Success fill:#d4edda style Fix fill:#f8d7da \`\`\` Include these diagrams in the appropriate sections of your deployment guidance. ${ includeScripts ? ` ### 5. **Script Generation** Generate deployment scripts: - **Shell scripts** for automated deployment - **Docker commands** for containerized deployment - **Configuration files** (nginx.conf, docker-compose.yml, .env) ` : '' } ${ includeValidation ? ` ### 6. **Validation & Health Checks** Create verification procedures: - **Health check endpoints** and commands - **Service connectivity tests** - **Performance validation** - **Security verification** ` : '' } ${ includeRollback ? ` ### 7. **Rollback Procedures** Document rollback steps: - **Rollback commands** in reverse order - **Data migration rollback** if applicable - **Service restoration** procedures ` : '' } ## Output Format Generate deployment guidance in the following structure: \`\`\`markdown # Deployment Guide: [Project Name] **Environment**: ${environment} **Generated**: [Current Date] ## ๐ Prerequisites - List all required tools, access, and dependencies ## ๐๏ธ Infrastructure Setup - Cloud/server setup steps - Network configuration - Security setup ## ๐๏ธ Database Setup - Database installation/configuration - Schema creation/migration - Connection setup ## ๐ Application Deployment 1. **Build Steps** \`\`\`bash # Build commands \`\`\` 2. **Deploy Steps** \`\`\`bash # Deployment commands \`\`\` 3. **Configuration** \`\`\`bash # Configuration commands \`\`\` ## โ๏ธ Configuration Files ### .env (Environment Variables) \`\`\` KEY=value \`\`\` ### docker-compose.yml (if applicable) \`\`\`yaml # Docker configuration \`\`\` ## ๐ Health Checks & Verification \`\`\`bash # Health check commands \`\`\` ## ๐ Rollback Procedure \`\`\`bash # Rollback commands (in reverse order) \`\`\` ## ๐ ๏ธ Troubleshooting - Common issues and solutions ## ๐ Reference ADRs - Links to relevant ADRs \`\`\` ## Analysis Requirements - **Be specific**: Include actual commands, ports, and configurations - **Environment-aware**: Tailor guidance for ${environment} - **Security-focused**: Include security best practices - **Actionable**: Every step should be executable - **Complete**: Cover entire deployment lifecycle - **Evidence-based**: Base all recommendations on ADR content ${ technologyFilter && technologyFilter.length > 0 ? ` ## Technology Filter Focus only on these technologies: ${technologyFilter.join(', ')} ` : '' } ${ customRequirements && customRequirements.length > 0 ? ` ## Custom Requirements Additionally address these requirements: ${customRequirements.map(req => `- ${req}`).join('\n')} ` : '' } Begin deployment guidance generation now. `; // Return the prompt for AI execution return { content: [ { type: 'text', text: `# Deployment Guidance Generation ## Analysis Complete - **Found ${discoveryResult.adrs.length} ADRs** for deployment analysis - **Target Environment**: ${environment} - **Format**: ${format} - **Include Scripts**: ${includeScripts} - **Include Configs**: ${includeConfigs} - **Include Validation**: ${includeValidation} - **Include Rollback**: ${includeRollback} ## AI Analysis Prompt ${deploymentPrompt} ## Instructions 1. **Submit the prompt above** to an AI agent for comprehensive deployment guidance 2. **Review the generated guidance** for completeness and accuracy 3. **Customize configurations** for your specific environment 4. **Test deployment steps** in staging before production 5. **Save guidance** as DEPLOYMENT.md or similar documentation ## Expected Output The AI will generate: - **Step-by-step deployment instructions** - **Environment-specific configurations** - **Shell scripts and configuration files** - **Health checks and validation procedures** - **Rollback procedures** - **Troubleshooting guidance** All based on the architectural decisions documented in your ADRs. ${ generateFiles ? ` ## File Generation Mode **Note**: File generation is enabled. The AI guidance will include instructions for creating actual deployment files in your project. ` : '' } ## ADR Sources ${discoveryResult.adrs.map(adr => `- **${adr.title}** (${adr.filename})`).join('\n')} `, }, ], }; } catch (error) { throw new McpAdrError( `Deployment guidance generation failed: ${error instanceof Error ? error.message : String(error)}`, 'DEPLOYMENT_GUIDANCE_ERROR' ); } }
- src/tools/tool-chain-orchestrator.ts:43-69 (registration)Lists 'generate_deployment_guidance' in the AVAILABLE_TOOLS array used by the tool chain orchestrator for AI planning.const AVAILABLE_TOOLS = [ 'analyze_project_ecosystem', 'generate_adrs_from_prd', 'suggest_adrs', 'analyze_content_security', 'generate_rules', 'generate_adr_todo', 'compare_adr_progress', 'manage_todo', 'generate_deployment_guidance', 'smart_score', 'troubleshoot_guided_workflow', 'smart_git_push', 'generate_research_questions', 'validate_rules', 'analyze_code_patterns', 'suggest_improvements', 'generate_test_scenarios', 'create_documentation', 'security_audit', 'performance_analysis', 'dependency_analysis', 'refactoring_suggestions', 'api_documentation', 'deployment_checklist', 'release_notes', ] as const;
- src/tools/tool-chain-orchestrator.ts:72-98 (registration)Provides description for generate_deployment_guidance in TOOL_CAPABILITIES mapping used in AI prompts for tool selection.const TOOL_CAPABILITIES = { analyze_project_ecosystem: 'Analyze technology stack, dependencies, and architectural patterns', generate_adrs_from_prd: 'Convert Product Requirements Documents to Architectural Decision Records', suggest_adrs: 'Auto-suggest ADRs based on code analysis and project patterns', analyze_content_security: 'Detect and mask sensitive information in project content', generate_rules: 'Extract architectural rules and constraints from project analysis', generate_adr_todo: 'Generate TODO.md from ADRs with comprehensive task breakdown', compare_adr_progress: 'Validate TODO vs ADRs vs actual environment state', manage_todo: 'Comprehensive TODO.md lifecycle management and progress tracking', generate_deployment_guidance: 'AI-driven deployment procedures from architectural decisions', smart_score: 'Project health scoring with cross-tool synchronization', troubleshoot_guided_workflow: 'Systematic troubleshooting with ADR/TODO alignment', smart_git_push: 'Intelligent release readiness analysis and git operations', generate_research_questions: 'Generate targeted research questions for project analysis', validate_rules: 'Validate architectural rule compliance across the project', analyze_code_patterns: 'Identify code patterns and architectural consistency', suggest_improvements: 'Provide targeted improvement recommendations', generate_test_scenarios: 'Create comprehensive test scenarios and strategies', create_documentation: 'Generate project documentation from code and ADRs', security_audit: 'Comprehensive security analysis and vulnerability detection', performance_analysis: 'Analyze performance bottlenecks and optimization opportunities', dependency_analysis: 'Analyze project dependencies and potential issues', refactoring_suggestions: 'Suggest code refactoring based on architectural principles', api_documentation: 'Generate API documentation from code analysis', deployment_checklist: 'Create deployment checklists based on ADRs and project state', release_notes: 'Generate release notes from commits, ADRs, and TODO completion',
- Maps 'generate' keyword to include generate_deployment_guidance in fallback intent analysis for tool suggestions.const repeatedTools = Object.entries(toolCounts).filter(([_, count]) => count > 3); if (repeatedTools.length > 0) { riskScore += repeatedTools.length; confusionIndicators.push( `Excessive repetition of tools: ${repeatedTools.map(([tool, count]) => `${tool}(${count}x)`).join(', ')}` ); recommendations.push('Break the repetition cycle with human override or different approach'); } } // Confusion indicators in the request const confusionKeywords = [ 'confused', 'not working', 'stuck', 'help', 'what should', "don't know", 'error', 'failed', ]; const foundKeywords = confusionKeywords.filter(keyword => request.includes(keyword)); if (foundKeywords.length > 0) { riskScore += foundKeywords.length; confusionIndicators.push(`Confusion keywords detected: ${foundKeywords.join(', ')}`); recommendations.push('LLM expressing uncertainty - human override recommended'); } // Stuck on same task if (sessionCtx?.stuckOnTask) { riskScore += 3; confusionIndicators.push(`Stuck on task: ${sessionCtx.stuckOnTask}`); recommendations.push('Use human override to force progress on stuck task'); } // Suggest actions based on risk level const hallucinationRisk: 'low' | 'medium' | 'high' = riskScore >= 5 ? 'high' : riskScore >= 2 ? 'medium' : 'low'; if (hallucinationRisk === 'high') { suggestedActions.push( 'IMMEDIATE: Start fresh session with analyze_project_ecosystem to reload context', 'Avoid further AI planning - use predefined task patterns', 'Consider resetting the conversation context' ); } else if (hallucinationRisk === 'medium') { suggestedActions.push( 'Use predefined task patterns for critical tasks', 'Limit AI planning to simple operations', 'Monitor for increasing confusion indicators' ); } else { suggestedActions.push( 'Continue with AI-assisted planning', 'Monitor session for confusion indicators', 'Keep human override available as backup' ); } return { hallucinationRisk, confusionIndicators, recommendations, suggestedActions, }; } /** * Session guidance - Provide structured guidance for long sessions */ function generateSessionGuidance(args: ToolChainOrchestratorArgs): { sessionStatus: 'healthy' | 'concerning' | 'critical'; guidance: string[]; recommendedNextStep: string; humanInterventionNeeded: boolean; } { const realityCheck = performRealityCheck(args); const sessionCtx = args.sessionContext; const guidance: string[] = []; let sessionStatus: 'healthy' | 'concerning' | 'critical' = 'healthy'; let humanInterventionNeeded = false; let recommendedNextStep = 'Continue with current approach'; // Assess session health if (realityCheck.hallucinationRisk === 'high') { sessionStatus = 'critical'; humanInterventionNeeded = true; recommendedNextStep = 'Start fresh session with analyze_project_ecosystem'; guidance.push('๐จ CRITICAL: High hallucination risk detected'); guidance.push('LLM appears confused or stuck in loops'); guidance.push('Fresh session with context reload strongly recommended'); } else if (realityCheck.hallucinationRisk === 'medium') { sessionStatus = 'concerning'; recommendedNextStep = 'Consider fresh session for critical tasks'; guidance.push('โ ๏ธ WARNING: Session showing signs of confusion'); guidance.push('Monitor closely and prepare to restart with fresh context'); } else { guidance.push('โ Session appears healthy'); guidance.push('AI planning can continue safely'); } // Add specific guidance based on context if (sessionCtx?.conversationLength && sessionCtx.conversationLength > 15) { guidance.push( `๐ Long session (${sessionCtx.conversationLength} messages) - consider summarizing progress` ); } if (sessionCtx?.lastSuccessfulAction) { guidance.push(`โ Last successful action: ${sessionCtx.lastSuccessfulAction}`); guidance.push('Consider building on this success rather than trying new approaches'); } // Add actionable next steps guidance.push('', '๐ฏ Recommended Actions:'); guidance.push(...realityCheck.suggestedActions.map(action => `โข ${action}`)); return { sessionStatus, guidance, recommendedNextStep, humanInterventionNeeded, }; } /** * Fallback intent analysis using keywords */ function fallbackIntentAnalysis(userRequest: string): { intent: string; category: string; complexity: 'simple' | 'moderate' | 'complex'; suggestedTools: string[]; confidence: number; } { const request = userRequest.toLowerCase(); // Simple keyword matching const keywordMap = { analyze: ['analyze_project_ecosystem', 'analyze_content_security'], generate: ['generate_adrs_from_prd', 'generate_adr_todo', 'generate_deployment_guidance'],
- Input schema defined by TypeScript interface in function parameters for tool arguments.export async function generateDeploymentGuidance(args: { adrDirectory?: string; environment?: 'development' | 'staging' | 'production' | 'all'; format?: 'markdown' | 'scripts' | 'structured' | 'all'; projectPath?: string; includeScripts?: boolean; includeConfigs?: boolean; includeValidation?: boolean; technologyFilter?: string[]; customRequirements?: string[]; includeRollback?: boolean; generateFiles?: boolean;