Skip to main content
Glama

recommend_template

Read-onlyIdempotent

Recommends matching built-in templates for a described document purpose, preventing conversion errors from incorrect template guesses.

Instructions

Suggest the best built-in template(s) for a described purpose. Use this when the user describes WHAT the document is (e.g. 'Q4 board pack', 'API reference', 'wedding invitation', 'legal contract') without naming a template. Returns ranked recommendations with rationale.

Why this exists: AI assistants often guess template names that don't exist. This tool maps purpose → real template names from MDMagic's catalog, so convert_document doesn't fail with 'template not found'.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
purposeYesFree-text description of the document's purpose. Examples: 'Q4 board pack for investors', 'restaurant menu', 'developer API documentation', 'wedding invitation'.
topNNoHow many recommendations to return (1-5, default 3)

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
purposeNoEchoes back the purpose that was matched
rationaleNoWhy these templates were picked
recommendationsYesRanked list of template IDs to pass to convert_document

Implementation Reference

  • Main handler function for recommend_template. Parses input via Zod schema, scores purpose text against keyword rules, picks winning template recommendations, optionally validates them against the API, and returns a formatted text response.
    export async function handleRecommendTemplate(
      apiClient: MDMagicApiClient,
      args: any
    ): Promise<CallToolResult> {
      try {
        const input = recommendTemplateSchema.parse(args);
        console.error(`[recommend_template] Purpose: "${input.purpose}"`);
    
        // Score each rule by number of pattern matches against the purpose string
        const matched: Array<{ recommend: string[]; rationale: string; score: number }> = [];
        for (const rule of KEYWORD_RULES) {
          let score = 0;
          for (const pat of rule.patterns) {
            if (pat.test(input.purpose)) score++;
          }
          if (score > 0) matched.push({ ...rule, score });
        }
    
        // Pick winning rule (highest score; ties → first declared, which is most specific)
        matched.sort((a, b) => b.score - a.score);
        const winner = matched[0];
    
        let picked: string[];
        let rationale: string;
        if (winner) {
          picked = winner.recommend.slice(0, input.topN);
          rationale = winner.rationale;
        } else {
          // No strong match — recommend safe defaults that work for most prose
          picked = ['Professional_Azure', 'Executive_Platinum', 'Minimalist_Pro'].slice(0, input.topN);
          rationale = 'No strong keyword match — these are versatile templates that work for most general-purpose documents.';
        }
    
        // Optionally: validate the recommended templates exist on the API.
        // If the catalog has shifted, fall back gracefully without erroring.
        let validated = picked;
        try {
          const builtin = await apiClient.getTemplates();
          const known = new Set((builtin.templates || []).map(t => (t.id || '').toLowerCase()));
          validated = picked.filter(p => known.has(p.toLowerCase()));
          if (validated.length === 0) {
            validated = picked; // API returned nothing useful; show recommendations anyway
          }
        } catch {
          // Network/auth failure — keep the keyword-derived list
        }
    
        const lines = [
          `🎯 **Template recommendations for: "${input.purpose}"**`,
          '',
          `**Why these**: ${rationale}`,
          '',
          `**Top ${validated.length}:**`,
        ];
        validated.forEach((id, i) => {
          lines.push(`${i + 1}. \`${id}\``);
        });
        lines.push('');
        lines.push('💡 Pass any of these as `templateName` to `convert_document`. Call `list_all_templates` to see the full catalog including custom templates.');
    
        return { content: [{ type: 'text', text: lines.join('\n') }] };
      } catch (error: any) {
        console.error('[recommend_template] Error:', error.message);
        throw error;
      }
    }
  • Zod schema defining input validation: `purpose` (string) and `topN` (integer 1-5, default 3).
    export const recommendTemplateSchema = z.object({
      purpose: z.string().describe('What the document is for. Examples: "Q4 board pack", "API reference docs", "wedding invitation", "legal contract", "data analysis report".'),
      topN: z.number().int().min(1).max(5).default(3).describe('How many recommendations to return (1-5).')
    });
  • Switch-case registration dispatching 'recommend_template' tool name to handleRecommendTemplate.
    case 'recommend_template':
      return await handleRecommendTemplate(apiClient, request.params.arguments);
  • Import of handleRecommendTemplate from the recommendTemplate module.
    import { handleRecommendTemplate } from './recommendTemplate.js';
  • Keyword rule definitions mapping regex patterns to template recommendations with rationale. Covers legal, executive, finance, technical, data, creative, food, wellness, minimalist, and generic business categories.
    const KEYWORD_RULES: Array<{ patterns: RegExp[]; recommend: string[]; rationale: string }> = [
      // Legal / contracts
      {
        patterns: [/\b(legal|contract|agreement|nda|terms|policy|compliance|statute|brief|affidavit|deed|will|testament)\b/i],
        recommend: ['Legal_Burgundy', 'Modern_Legal', 'Executive_Platinum'],
        rationale: 'Legal templates emphasise traditional formatting, signature blocks, and section numbering.'
      },
      // Executive / board / strategy
      {
        patterns: [/\b(board|exec|executive|strategy|strategic|c[\-\s]?suite|leadership|quarterly|annual report|investor|stakeholder|q[1-4]\b)\b/i],
        recommend: ['Executive_Platinum', 'Premium_Bronze', 'Professional_Azure'],
        rationale: 'Executive-grade typography and conservative styling suited to leadership audiences.'
      },
      // Finance / numbers / accounting
      {
        patterns: [/\b(financial|finance|budget|accounting|p&l|balance sheet|forecast|invoice|revenue|earnings)\b/i],
        recommend: ['Financial_Blue', 'Executive_Platinum', 'Professional_Azure'],
        rationale: 'Financial templates handle tables, footnotes, and figure-heavy content cleanly.'
      },
      // Code / API / technical docs
      {
        patterns: [/\b(api|reference|sdk|developer|technical doc|architecture|engineering|spec(ification)?|readme|changelog|release notes|code|programming|library)\b/i],
        recommend: ['Code_Documentation', 'Deep_Data_Blue', 'Professional_Azure'],
        rationale: 'Technical templates render code blocks, diagrams, and structured headings well.'
      },
      // Data / analytics / research
      {
        patterns: [/\b(data|analytics|analysis|research|study|metrics|kpi|dashboard|report card|whitepaper|white paper)\b/i],
        recommend: ['Deep_Data_Blue', 'Financial_Blue', 'Code_Documentation'],
        rationale: 'Data-focused templates support charts, tables, and figure captions.'
      },
      // Creative / marketing / fun
      {
        patterns: [/\b(invitation|invite|wedding|party|birthday|menu|brochure|flyer|poster|marketing|campaign|brand|creative)\b/i],
        recommend: ['Designer_Indigo', 'Artistic_Aqua', 'Sunset_Vibes'],
        rationale: 'Creative templates use distinctive typography and colour to grab attention.'
      },
      // Food / restaurant / casual
      {
        patterns: [/\b(menu|recipe|food|restaurant|cafe|cooking)\b/i],
        recommend: ['Cheese_Burger', 'Sunset_Vibes', 'Designer_Indigo'],
        rationale: 'Casual, food-friendly typography that reads warm rather than corporate.'
      },
      // Wellness / lifestyle / mindfulness
      {
        patterns: [/\b(wellness|yoga|meditation|mindfulness|health|wellbeing|lifestyle|nature|garden|holistic)\b/i],
        recommend: ['Sage_Serenity', 'Artistic_Aqua', 'Minimalist_Pro'],
        rationale: 'Calm, nature-inspired styling appropriate for wellness/lifestyle content.'
      },
      // Minimalist / clean
      {
        patterns: [/\b(minimal|clean|simple|stripped|bare)\b/i],
        recommend: ['Minimalist_Pro', 'Professional_Azure', 'Designer_Indigo'],
        rationale: 'Clean, low-ornament templates that put content first.'
      },
      // Generic business / proposal / corporate
      {
        patterns: [/\b(business|corporate|proposal|pitch|deck|memo|briefing)\b/i],
        recommend: ['Professional_Azure', 'Business_Purple', 'Executive_Platinum'],
        rationale: 'General-purpose business templates suited to internal and external audiences.'
      },
    ];
Behavior4/5

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

Annotations already declare the tool as read-only and idempotent. The description adds value by stating that it 'returns ranked recommendations with rationale', which is behavioral context not covered by annotations. No contradictions.

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

Conciseness5/5

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

The description is concise and front-loaded, with the first sentence stating the core action. Two paragraphs: one for usage and one for rationale. Every sentence adds value without redundancy.

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

Completeness5/5

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

The description is complete for a two-parameter tool with existing output schema. It explains the input, output (ranked recommendations with rationale), and the problem it solves, linking to the sibling tool convert_document.

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?

Input schema has 100% coverage with detailed descriptions for both parameters (purpose and topN). The tool description does not add further explanation beyond the schema, so baseline score of 3 applies.

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

Purpose5/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: 'Suggest the best built-in template(s) for a described purpose.' It uses the specific verb 'suggest' and resource 'built-in templates', and explicitly distinguishes from sibling tools like list_all_templates by noting that this tool maps purpose to real template names to avoid conversion failures.

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

Usage Guidelines5/5

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

The description explicitly states when to use this tool: 'when the user describes WHAT the document is (e.g. ...) without naming a template.' It also explains why it exists (to prevent AI assistants from guessing non-existent templates) and implicitly indicates not to use when a template name is already known.

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/MDMagic-MCP/mdmagic-mcp-server'

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