Skip to main content
Glama

generate_adr_from_decision

Convert architectural decision data into structured ADR documents using Nygard, MADR, or custom templates for documentation and reference.

Instructions

Generate a complete ADR from decision data. TIP: Reference @.mcp-server-context.md to align with existing architectural patterns and decisions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
decisionDataYes
templateFormatNoADR template format to usenygard
existingAdrsNoList of existing ADRs for numbering and references
adrDirectoryNoDirectory where ADRs are storeddocs/adrs

Implementation Reference

  • The main MCP tool handler function that processes input arguments, generates prompts using helpers, executes AI generation, and returns formatted ADR content with file creation instructions.
    export async function generateAdrFromDecision(args: {
      decisionData: {
        title: string;
        context: string;
        decision: string;
        consequences: string;
        alternatives?: string[];
        evidence?: string[];
      };
      templateFormat?: 'nygard' | 'madr' | 'custom';
      existingAdrs?: string[];
      adrDirectory?: string;
    }): Promise<any> {
      const {
        decisionData,
        templateFormat = 'nygard',
        existingAdrs = [],
        adrDirectory = 'docs/adrs',
      } = args;
    
      try {
        const { generateAdrFromDecision, generateNextAdrNumber, suggestAdrFilename } =
          await import('../utils/adr-suggestions.js');
    
        if (
          !decisionData.title ||
          !decisionData.context ||
          !decisionData.decision ||
          !decisionData.consequences
        ) {
          throw new McpAdrError(
            'Decision data must include title, context, decision, and consequences',
            'INVALID_INPUT'
          );
        }
    
        const result = await generateAdrFromDecision(decisionData, templateFormat, existingAdrs);
    
        // Generate suggested metadata
        const adrNumber = generateNextAdrNumber(existingAdrs);
        const filename = suggestAdrFilename(decisionData.title, adrNumber);
        const fullPath = `${adrDirectory}/${filename}`;
    
        // Execute ADR generation with AI if enabled
        const { executeADRGenerationPrompt } = await import('../utils/prompt-execution.js');
        const executionResult = await executeADRGenerationPrompt(
          result.generationPrompt,
          result.instructions,
          {
            temperature: 0.1,
            maxTokens: 6000,
            responseFormat: 'text',
          }
        );
    
        if (executionResult.isAIGenerated) {
          // AI execution successful - return actual ADR content
          return formatMCPResponse({
            ...executionResult,
            content: `# Generated ADR: ${decisionData.title}
    
    ## ADR Metadata
    - **ADR Number**: ${adrNumber}
    - **Filename**: ${filename}
    - **Full Path**: ${fullPath}
    - **Template Format**: ${templateFormat.toUpperCase()}
    
    ## Generated ADR Content
    
    ${executionResult.content}
    
    ## File Creation Instructions
    
    To save this ADR to your project:
    
    1. **Create the ADR directory** (if it doesn't exist):
       \`\`\`bash
       mkdir -p ${adrDirectory}
       \`\`\`
    
    2. **Save the ADR content** to the file:
       \`\`\`bash
       cat > "${fullPath}" << 'EOF'
       ${executionResult.content}
       EOF
       \`\`\`
    
    3. **Verify the file** was created successfully:
       \`\`\`bash
       ls -la "${fullPath}"
       \`\`\`
    
    ## Next Steps
    
    1. **Review the generated ADR** for accuracy and completeness
    2. **Save the file** using the instructions above
    3. **Update your ADR index** or catalog
    4. **Share with stakeholders** for review and approval
    5. **Plan implementation** of the architectural decision
    
    ## Quality Checklist
    
    - ✅ **Title** is clear and descriptive
    - ✅ **Context** explains the problem and constraints
    - ✅ **Decision** is specific and actionable
    - ✅ **Consequences** cover both positive and negative impacts
    - ✅ **Format** follows ${templateFormat.toUpperCase()} template standards
    - ✅ **Numbering** is sequential (${adrNumber})
    `,
          });
        } else {
          // Fallback to prompt-only mode
          const { ensureDirectoryCompat: ensureDirectory, writeFileCompat: writeFile } =
            await import('../utils/file-system.js');
          const ensureDirPrompt = await ensureDirectory(adrDirectory);
          const writeFilePrompt = await writeFile(fullPath, '[ADR_CONTENT_PLACEHOLDER]');
    
          return {
            content: [
              {
                type: 'text',
                text: `# ADR Generation: ${decisionData.title}
    
    ${result.instructions}
    
    ## Suggested ADR Metadata
    - **ADR Number**: ${adrNumber}
    - **Filename**: ${filename}
    - **Full Path**: ${fullPath}
    - **Template Format**: ${templateFormat.toUpperCase()}
    
    ## Step 1: Create ADR Directory
    ${ensureDirPrompt.prompt}
    
    ## Step 2: Generate ADR Content
    
    ${result.generationPrompt}
    
    ## Step 3: Save ADR to File
    
    After generating the ADR content from Step 2, create the ADR file:
    
    ${writeFilePrompt.prompt}
    
    **Important**: Replace \`[ADR_CONTENT_PLACEHOLDER]\` with the actual generated ADR content from Step 2.
    `,
              },
            ],
          };
        }
      } catch (error) {
        throw new McpAdrError(
          `Failed to generate ADR: ${error instanceof Error ? error.message : String(error)}`,
          'GENERATION_ERROR'
        );
      }
    }
  • TypeScript interface defining the input arguments for the generate_adr_from_decision tool.
    export interface GenerateAdrFromDecisionArgs {
      decisionData: DecisionData;
      templateFormat?: 'custom' | 'nygard' | 'madr';
      existingAdrs?: string[];
      adrDirectory?: string;
    }
  • Helper function that generates the AI prompt and instructions used by the handler to create ADR content.
    export async function generateAdrFromDecision(
      decisionData: {
        title: string;
        context: string;
        decision: string;
        consequences: string;
        alternatives?: string[];
        evidence?: string[];
      },
      templateFormat: 'nygard' | 'madr' | 'custom' = 'nygard',
      existingAdrs?: string[]
    ): Promise<{ generationPrompt: string; instructions: string }> {
      try {
        const { generateAdrTemplatePrompt } = await import('../prompts/adr-suggestion-prompts.js');
    
        const generationPrompt = generateAdrTemplatePrompt(decisionData, templateFormat, existingAdrs);
    
        const instructions = `
    # ADR Generation Instructions
    
    This will generate a complete Architectural Decision Record from the provided decision data.
    
    ## Decision Summary
    - **Title**: ${decisionData.title}
    - **Template Format**: ${templateFormat.toUpperCase()}
    - **Alternatives**: ${decisionData.alternatives?.length || 0} considered
    - **Evidence**: ${decisionData.evidence?.length || 0} pieces
    
    ## Next Steps
    1. **Submit the generation prompt** to an AI agent for ADR creation
    2. **Parse the JSON response** to get the complete ADR
    3. **Review the generated content** for quality and completeness
    4. **Save the ADR** to the appropriate location with suggested filename
    
    ## Expected AI Response Format
    The AI will return a JSON object with:
    - \`adr\`: Complete ADR with content, metadata, and filename
    - \`suggestions\`: Placement, numbering, and review suggestions
    - \`qualityChecks\`: Quality assessment and improvement suggestions
    
    ## Usage Example
    \`\`\`typescript
    const result = await generateAdrFromDecision(decisionData, 'nygard', existingAdrs);
    // Submit result.generationPrompt to AI agent
    // Parse AI response as GeneratedAdr
    \`\`\`
    `;
    
        return {
          generationPrompt,
          instructions,
        };
      } catch (error) {
        throw new McpAdrError(
          `Failed to generate ADR: ${error instanceof Error ? error.message : String(error)}`,
          'GENERATION_ERROR'
        );
      }
    }
  • Helper utility to generate the next ADR number based on existing ADRs.
    export function generateNextAdrNumber(existingAdrs: string[]): string {
      try {
        // Extract numbers from existing ADR filenames/titles
        const numbers = existingAdrs
          .map(adr => {
            const match = adr.match(/ADR[-_]?(\d+)/i) || adr.match(/(\d+)/);
            return match && match[1] ? parseInt(match[1], 10) : 0;
          })
          .filter(num => num > 0);
    
        const maxNumber = numbers.length > 0 ? Math.max(...numbers) : 0;
        const nextNumber = maxNumber + 1;
    
        return `ADR-${nextNumber.toString().padStart(4, '0')}`;
      } catch (error) {
        // Log to stderr to avoid corrupting MCP protocol
        console.error('[WARN] Failed to generate ADR number:', error);
        return 'ADR-0001';
      }
    }
  • Helper utility to suggest ADR filename based on title and ADR number.
    export function suggestAdrFilename(title: string, adrNumber?: string): string {
      try {
        const number = adrNumber || 'XXXX';
        const cleanTitle = title
          .toLowerCase()
          .replace(/[^a-z0-9\s-]/g, '')
          .replace(/\s+/g, '-')
          .replace(/-+/g, '-')
          .replace(/^-|-$/g, '');
    
        return `${number.toLowerCase()}-${cleanTitle}.md`;
      } catch (error) {
        // Log to stderr to avoid corrupting MCP protocol
        console.error('[WARN] Failed to suggest filename:', error);
        return 'adr-new-decision.md';
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions generating a 'complete ADR' but doesn't clarify what 'complete' means, whether this creates a file or returns text, what permissions are needed, or any side effects. The TIP about referencing context adds some guidance but doesn't cover core behavioral traits like output format or mutation implications.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with two sentences. The first sentence states the core purpose clearly. The second provides a useful tip without unnecessary elaboration. Both sentences earn their place, and the structure is front-loaded with the main functionality stated first.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (4 parameters with nested objects, no output schema, and no annotations), the description is insufficient. It doesn't explain what the tool returns (text, file path, structured data?), doesn't clarify the 'complete ADR' output format, and provides minimal guidance on parameter interactions. For a tool that likely creates architectural documentation, more context about output behavior and usage constraints is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 75%, providing good documentation for most parameters. The description adds no specific parameter semantics beyond what the schema already covers. It doesn't explain relationships between parameters (e.g., how 'existingAdrs' affects numbering) or provide additional context about parameter usage. This meets the baseline for high schema coverage but adds no extra value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Generate a complete ADR from decision data.' It specifies both the verb ('Generate') and resource ('ADR'), making it immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'generate_adr_bootstrap' or 'generate_adrs_from_prd', which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides some usage guidance with the TIP to reference context documentation for alignment with existing patterns. This implies when to use it (when needing to create ADRs consistent with established practices) but doesn't explicitly state when not to use it or mention alternatives among the many sibling tools. The guidance is helpful but incomplete.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/tosin2013/mcp-adr-analysis-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server