Skip to main content
Glama

analyze_deck

Get detailed deck analysis: mana curve, color distribution, type breakdown, mana base, and format legality checks.

Instructions

Analyze a Magic: The Gathering deck list. Paste a deck list (plain text format like '4 Lightning Bolt' per line, or MTGO .dek XML) and get mana curve, color distribution, type breakdown, mana base analysis, and format legality check. Use this when a user shares a deck list and wants feedback.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
deck_listYesThe deck list in plain text or MTGO .dek XML format
formatNoFormat to check legality against (e.g., "modern", "commander", "standard")

Implementation Reference

  • The main handler function that executes the analyze_deck tool logic. Parses a deck list, looks up cards in the database, computes mana curve, color distribution, type breakdown, mana base analysis, and format legality.
    export function handler(db: Database.Database, params: AnalyzeDeckParams): AnalyzeDeckResult {
      // 1. Parse the deck list
      let parsed: ParsedDeck;
      try {
        parsed = parseDeckList(params.deck_list);
      } catch (err) {
        return {
          success: false,
          message: `Failed to parse deck list: ${err instanceof Error ? err.message : String(err)}`,
        };
      }
    
      const allEntries = [...parsed.main, ...parsed.sideboard];
      if (allEntries.length === 0) {
        return { success: false, message: 'Deck list is empty — no cards found.' };
      }
    
      // 2. Look up each card
      const resolved: ResolvedCard[] = [];
      const notFound: CardNotFound[] = [];
    
      for (const entry of allEntries) {
        const result = lookupCard(db, entry.name);
        if (result.card) {
          resolved.push({ entry, card: result.card });
        } else {
          notFound.push({
            name: entry.name,
            suggestion: result.suggestion,
          });
        }
      }
    
      // Also resolve main-only for analysis (sideboard excluded from curve/type/color)
      const mainEntries = parsed.main;
      const resolvedMain: ResolvedCard[] = [];
      for (const entry of mainEntries) {
        const result = lookupCard(db, entry.name);
        if (result.card) {
          resolvedMain.push({ entry, card: result.card });
        }
      }
    
      // 3. Compute mana curve (main deck non-land cards only)
      const cmcBuckets: Record<string, number> = {};
      for (let i = 0; i <= 6; i++) cmcBuckets[String(i)] = 0;
      cmcBuckets['7+'] = 0;
    
      for (const { entry, card } of resolvedMain) {
        if (classifyType(getTypeLine(card)) === 'Land') continue;
        const cmc = card.cmc ?? 0;
        const key = cmc >= 7 ? '7+' : String(Math.floor(cmc));
        cmcBuckets[key] = (cmcBuckets[key] ?? 0) + entry.count;
      }
    
      const mana_curve: ManaCurveEntry[] = Object.entries(cmcBuckets).map(([cmc, count]) => ({
        cmc,
        count,
      }));
    
      // 4. Color distribution (main deck)
      const colorCounts: Record<string, number> = { W: 0, U: 0, B: 0, R: 0, G: 0, Colorless: 0 };
      for (const { entry, card } of resolvedMain) {
        const colors = extractColors(card);
        if (colors.length === 0) {
          colorCounts['Colorless'] += entry.count;
        } else {
          for (const c of colors) {
            colorCounts[c] = (colorCounts[c] ?? 0) + entry.count;
          }
        }
      }
    
      const color_distribution: ColorCount[] = Object.entries(colorCounts)
        .map(([color, count]) => ({
          color: COLOR_NAMES[color] ?? color,
          count,
        }));
    
      // 5. Type breakdown (main deck)
      const typeCounts: Record<string, number> = {};
      for (const type of [...TYPE_CATEGORIES, 'Other']) typeCounts[type] = 0;
    
      for (const { entry, card } of resolvedMain) {
        const type = classifyType(getTypeLine(card));
        typeCounts[type] = (typeCounts[type] ?? 0) + entry.count;
      }
    
      const type_breakdown: TypeCount[] = Object.entries(typeCounts)
        .filter(([, count]) => count > 0)
        .map(([type, count]) => ({ type, count }));
    
      // 6. Mana base analysis (main deck)
      const landCount = typeCounts['Land'] ?? 0;
      const mainCardCount = mainEntries.reduce((sum, e) => sum + e.count, 0);
      const landPercentage = mainCardCount > 0 ? (landCount / mainCardCount) * 100 : 0;
    
      // Color sources from lands
      const colorSources: Record<string, number> = {};
      for (const { entry, card } of resolvedMain) {
        if (classifyType(getTypeLine(card)) !== 'Land') continue;
        const producedColors = countColorSources(
          getTypeLine(card),
          card.oracle_text,
          extractColors(card),
        );
        for (const c of producedColors) {
          colorSources[c] = (colorSources[c] ?? 0) + entry.count;
        }
      }
    
      // Color requirements from mana costs
      const colorRequirements: Record<string, number> = {};
      for (const { entry, card } of resolvedMain) {
        const reqs = extractColorRequirements(card.mana_cost);
        for (const [c, n] of Object.entries(reqs)) {
          colorRequirements[c] = (colorRequirements[c] ?? 0) + (n * entry.count);
        }
      }
    
      // Unique colors in the deck
      const uniqueColors = new Set<string>();
      for (const { card } of resolvedMain) {
        for (const c of extractColors(card)) {
          uniqueColors.add(c);
        }
      }
    
      const format = params.format ?? (parsed.format_hint === 'commander' ? 'commander' : undefined);
      const recommendedLands = getRecommendedLands(mainCardCount, uniqueColors.size, format);
    
      const warnings: string[] = [];
      if (recommendedLands !== null) {
        const diff = landCount - recommendedLands;
        if (diff < -3) {
          warnings.push(`Land count (${landCount}) is ${Math.abs(diff)} below the recommended ${recommendedLands} for a ${mainCardCount}-card deck.`);
        } else if (diff > 3) {
          warnings.push(`Land count (${landCount}) is ${diff} above the recommended ${recommendedLands} for a ${mainCardCount}-card deck.`);
        }
      }
    
      // Check color source coverage
      for (const [color, reqCount] of Object.entries(colorRequirements)) {
        const sourceCount = colorSources[color] ?? 0;
        if (sourceCount < 8 && reqCount > 5) {
          const colorName = COLOR_NAMES[color] ?? color;
          warnings.push(`Low ${colorName} sources (${sourceCount}) for ${reqCount} ${colorName} pips in mana costs. Consider adding more ${colorName} sources.`);
        }
      }
    
      const mana_base: ManaBaseAnalysis = {
        land_count: landCount,
        land_percentage: Math.round(landPercentage * 10) / 10,
        recommended_lands: recommendedLands,
        color_sources: colorSources,
        color_requirements: colorRequirements,
        warnings,
      };
    
      // 7. Format legality check
      let format_legality: DeckAnalysis['format_legality'];
      if (params.format) {
        const illegalCards: Array<{ name: string; status: string }> = [];
        const checkedNames = new Set<string>();
    
        for (const { card } of resolved) {
          if (checkedNames.has(card.name)) continue;
          checkedNames.add(card.name);
    
          const legalities = db.prepare(
            'SELECT * FROM legalities WHERE card_id = ? AND LOWER(format) = LOWER(?)'
          ).get(card.id, params.format) as LegalityRow | undefined;
    
          if (!legalities) {
            illegalCards.push({ name: card.name, status: 'not_legal' });
          } else if (legalities.status !== 'legal') {
            illegalCards.push({ name: card.name, status: legalities.status });
          }
        }
    
        format_legality = {
          format: params.format,
          all_legal: illegalCards.length === 0,
          illegal_cards: illegalCards,
        };
      }
    
      // 8. Assemble result
      const sideboardCount = parsed.sideboard.reduce((sum, e) => sum + e.count, 0);
    
      const analysis: DeckAnalysis = {
        main_count: mainCardCount,
        sideboard_count: sideboardCount,
        commander: parsed.commander,
        format_hint: parsed.format_hint,
        mana_curve,
        color_distribution,
        type_breakdown,
        mana_base,
        format_legality,
        cards_not_found: notFound,
      };
    
      return { success: true, analysis };
    }
  • Input schema for the analyze_deck tool: requires a deck_list string and optional format string.
    export const AnalyzeDeckInput = z.object({
      deck_list: z.string().describe('The deck list in plain text or MTGO .dek XML format'),
      format: z.string().optional().describe('Format to check legality against (e.g., "modern", "commander", "standard")'),
    });
    
    export type AnalyzeDeckParams = z.infer<typeof AnalyzeDeckInput>;
  • Output types and interfaces for the deck analysis result, including ManaCurveEntry, ColorCount, TypeCount, ManaBaseAnalysis, DeckAnalysis, and the result union type.
    export interface ManaCurveEntry {
      cmc: string; // "0", "1", ..., "7+"
      count: number;
    }
    
    export interface ColorCount {
      color: string;
      count: number;
    }
    
    export interface TypeCount {
      type: string;
      count: number;
    }
    
    export interface ManaBaseAnalysis {
      land_count: number;
      land_percentage: number;
      recommended_lands: number | null;
      color_sources: Record<string, number>;
      color_requirements: Record<string, number>;
      warnings: string[];
    }
    
    export interface CardNotFound {
      name: string;
      suggestion?: string;
    }
    
    export interface DeckAnalysis {
      main_count: number;
      sideboard_count: number;
      commander?: string;
      format_hint?: string;
      mana_curve: ManaCurveEntry[];
      color_distribution: ColorCount[];
      type_breakdown: TypeCount[];
      mana_base: ManaBaseAnalysis;
      format_legality?: {
        format: string;
        all_legal: boolean;
        illegal_cards: Array<{ name: string; status: string }>;
      };
      cards_not_found: CardNotFound[];
    }
    
    export type AnalyzeDeckResult =
      | { success: true; analysis: DeckAnalysis }
      | { success: false; message: string };
  • src/server.ts:269-281 (registration)
    Registration of the 'analyze_deck' tool with the MCP server, wiring it to AnalyzeDeckInput schema and the handler function via server.tool().
    server.tool(
      'analyze_deck',
      'Analyze a Magic: The Gathering deck list. Paste a deck list (plain text format like \'4 Lightning Bolt\' per line, or MTGO .dek XML) and get mana curve, color distribution, type breakdown, mana base analysis, and format legality check. Use this when a user shares a deck list and wants feedback.',
      AnalyzeDeckInput.shape,
      async (params) => {
        try {
          const result = analyzeDeckHandler(db, params);
          return { content: [{ type: 'text' as const, text: formatAnalyzeDeck(result) }] };
        } catch (err) {
          return { content: [{ type: 'text' as const, text: `Error analyzing deck: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
        }
      },
    );
  • Formatter function that converts the analyze_deck result into a human-readable string for LLM consumption.
    export function formatAnalyzeDeck(result: AnalyzeDeckResult): string {
      if (!result.success) {
        return result.message;
      }
    
      const a = result.analysis;
      const lines: string[] = [];
    
      // Header
      const sideboardPart = a.sideboard_count > 0 ? `, ${a.sideboard_count} sideboard` : '';
      lines.push(`# Deck Analysis (${a.main_count} cards main${sideboardPart})`);
    
      if (a.commander) {
        lines.push(`Commander: ${a.commander}`);
      }
      if (a.format_hint) {
        lines.push(`Detected format: ${a.format_hint}`);
      }
    
      // Mana Curve
      lines.push('\n## Mana Curve');
      const maxCurve = Math.max(...a.mana_curve.map(e => e.count), 1);
      for (const entry of a.mana_curve) {
        const barLength = Math.round((entry.count / maxCurve) * 20);
        const bar = '\u2588'.repeat(barLength);
        lines.push(`${entry.cmc.padStart(2)}: ${bar} ${entry.count}`);
      }
    
      // Color Distribution
      lines.push('\n## Color Distribution');
      const colorParts = a.color_distribution
        .filter(c => c.count > 0)
        .map(c => `${c.color}: ${c.count}`);
      lines.push(colorParts.join(' | '));
    
      // Type Breakdown
      lines.push('\n## Type Breakdown');
      const typeParts = a.type_breakdown.map(t => `${t.type}: ${t.count}`);
      lines.push(typeParts.join(' | '));
    
      // Mana Base
      lines.push('\n## Mana Base');
      const recPart = a.mana_base.recommended_lands !== null
        ? ` — recommended ${a.mana_base.recommended_lands} for ${a.main_count}-card deck`
        : '';
      lines.push(`${a.mana_base.land_count} lands (${a.mana_base.land_percentage}%)${recPart}`);
    
      const sourceEntries = Object.entries(a.mana_base.color_sources);
      if (sourceEntries.length > 0) {
        const sourceParts = sourceEntries.map(([c, n]) => `${c}=${n}`);
        lines.push(`Color sources: ${sourceParts.join(', ')}`);
      }
    
      for (const warning of a.mana_base.warnings) {
        lines.push(`\u26a0 ${warning}`);
      }
    
      // Format Legality
      if (a.format_legality) {
        lines.push(`\n## Format Legality (${capitalize(a.format_legality.format)})`);
        if (a.format_legality.all_legal) {
          const totalCards = a.main_count + a.sideboard_count;
          lines.push(`\u2713 All ${totalCards} cards are legal in ${capitalize(a.format_legality.format)}`);
        } else {
          for (const card of a.format_legality.illegal_cards) {
            lines.push(`\u2717 ${card.name}: ${card.status}`);
          }
        }
      }
    
      // Cards Not Found
      if (a.cards_not_found.length > 0) {
        lines.push('\n## Cards Not Found');
        for (const card of a.cards_not_found) {
          if (card.suggestion) {
            lines.push(`- "${card.name}" \u2014 did you mean ${card.suggestion}?`);
          } else {
            lines.push(`- "${card.name}"`);
          }
        }
      }
    
      return lines.join('\n');
    }
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It mentions the outputs (mana curve, etc.) but does not disclose any behavioral traits like rate limits, statelessness, or if it modifies anything.

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?

Two sentences with no waste, front-loading the purpose. Efficient and well-structured.

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

Completeness4/5

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

The description covers inputs and expected outputs, but does not specify the output format (e.g., JSON, text). For a tool with no output schema, this would be helpful but is not critical.

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

Parameters5/5

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

The description adds significant meaning beyond the schema, explaining acceptable formats for deck_list (plain text with '4 Lightning Bolt' per line, or MTGO XML) and the purpose of format parameter for legality checks.

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 it analyzes an MTG deck list and lists specific analyses (mana curve, color distribution, etc.). The verb 'analyze' and resource 'deck list' are specific, and it distinguishes from sibling tools like analyze_commander and check_legality.

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

Usage Guidelines4/5

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

The description says 'Use this when a user shares a deck list and wants feedback,' providing clear context. However, it does not explicitly mention when not to use it or compare to alternatives like check_legality for legality-only checks.

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/gregario/mtg-oracle'

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