Skip to main content
Glama

analyze_deck

Analyze Magic: The Gathering deck lists to provide mana curve, color distribution, type breakdown, mana base analysis, 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 deck analysis by parsing the deck list, looking up cards in the database, computing mana curves, color distribution, type breakdown, mana base analysis, and format legality checks.
    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 };
    }
  • The Zod schema defining the input parameters for the 'analyze_deck' tool.
    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")'),
    });
  • src/server.ts:281-287 (registration)
    Registration of the 'analyze_deck' tool in the server implementation, connecting the tool name, schema, and handler.
    '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) }] };
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 describes what the tool does (analysis with specific outputs) and input format requirements (plain text or MTGO .dek XML), but it lacks details on behavioral traits like error handling, performance characteristics, or response format. This is adequate but has gaps for a tool with no annotations.

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 front-loaded with the core purpose and key outputs, followed by usage guidance. Both sentences earn their place by providing essential information without redundancy. It is appropriately sized and structured for clarity.

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?

Given the tool's complexity (analysis with multiple outputs) and no annotations or output schema, the description does a good job covering purpose, usage, and input requirements. However, it lacks details on output structure or error cases, which could be helpful for an agent. It's mostly complete but has minor gaps.

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 100%, so the schema already documents both parameters thoroughly. The description adds minimal value beyond the schema by mentioning the deck list format examples and implying format usage for legality checks, but it doesn't provide additional syntax or constraints. Baseline 3 is appropriate when the schema does the heavy lifting.

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 specific action ('analyze') and resource ('Magic: The Gathering deck list'), and it distinguishes this tool from siblings by listing unique analysis outputs (mana curve, color distribution, type breakdown, mana base analysis, format legality check). It goes beyond a simple restatement of the name.

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 a user shares a deck list and wants feedback.' It also implies alternatives by specifying the tool's focus on analysis rather than other functions like legality checking alone (handled by sibling 'check_legality') or commander analysis (handled by sibling 'analyze_commander'), providing clear context for selection.

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