Skip to main content
Glama
bmurdock

Scryfall MCP Server

by bmurdock

search_alternatives

Identify budget-friendly, upgraded, or functionally similar Magic: The Gathering cards based on format legality, price constraints, and desired direction. Ideal for optimizing deck building.

Instructions

Find budget alternatives, upgrades, or functionally similar cards

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
directionYesType of alternative to find
formatNoFormat legality requirement
limitNoNumber of alternatives to return
max_priceNoMaximum price constraint
min_priceNoMinimum price constraint
preserve_functionNoMaintain similar functionality
target_cardYesCard to find alternatives for

Implementation Reference

  • The `execute` method that implements the core logic of the `search_alternatives` tool: validates input parameters, retrieves the target card, builds a Scryfall search query for alternatives, executes the search, filters results, formats output as text, and handles errors.
    async execute(args: unknown) {
      try {
        // Validate parameters
        const params = this.validateParams(args);
    
        // First, get the target card to analyze its properties
        let targetCard;
        try {
          targetCard = await this.scryfallClient.getCard({ identifier: params.target_card });
        } catch (error) {
          if (error instanceof ScryfallAPIError && error.status === 404) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Target card not found: "${params.target_card}". Please check the card name.`
                }
              ],
              isError: true
            };
          }
          throw error;
        }
    
        // Build search query for alternatives
        const query = this.buildAlternativesQuery(targetCard, params);
    
        // Execute search
        const results = await this.scryfallClient.searchCards({
          query,
          limit: params.limit,
          order: this.getOrderForDirection(params.direction)
        });
    
        // Filter out the original card from results
        const filteredResults = {
          ...results,
          data: results.data.filter(card => card.id !== targetCard.id)
        };
    
        // Format results
        let responseText = `**Alternatives for ${targetCard.name}** (${params.direction}):\n\n`;
        
        if (filteredResults.data.length === 0) {
          responseText += `No ${params.direction} alternatives found for "${targetCard.name}"`;
          if (params.format) {
            responseText += ` in ${params.format}`;
          }
          responseText += '. Try adjusting your search criteria.';
        } else {
          responseText += formatSearchResultsAsText(filteredResults);
        }
    
        return {
          content: [
            {
              type: 'text',
              text: responseText
            }
          ]
        };
    
      } catch (error) {
        // Handle validation errors
        if (error instanceof ValidationError) {
          return {
            content: [
              {
                type: 'text',
                text: `Validation error: ${error.message}`
              }
            ],
            isError: true
          };
        }
    
        // Generic error handling
        return {
          content: [
            {
              type: 'text',
              text: `Unexpected error: ${error instanceof Error ? error.message : 'Unknown error occurred'}`
            }
          ],
          isError: true
        };
      }
    }
  • Input schema defining the parameters for the tool, including required fields `target_card` and `direction`, optional format, price constraints, and result limit.
    readonly inputSchema = {
      type: 'object' as const,
      properties: {
        target_card: {
          type: 'string',
          description: 'Card to find alternatives for'
        },
        direction: {
          type: 'string',
          enum: ['cheaper', 'upgrade', 'similar'],
          description: 'Type of alternative to find'
        },
        format: {
          type: 'string',
          enum: ['standard', 'modern', 'legacy', 'vintage', 'commander', 'pioneer'],
          description: 'Format legality requirement'
        },
        max_price: {
          type: 'number',
          minimum: 0,
          description: 'Maximum price constraint'
        },
        min_price: {
          type: 'number',
          minimum: 0,
          description: 'Minimum price constraint'
        },
        preserve_function: {
          type: 'boolean',
          default: true,
          description: 'Maintain similar functionality'
        },
        limit: {
          type: 'number',
          default: 10,
          minimum: 1,
          maximum: 50,
          description: 'Number of alternatives to return'
        }
      },
      required: ['target_card', 'direction']
    };
  • src/server.ts:73-73 (registration)
    Registers the `SearchAlternativesTool` instance in the server's tools Map with the name 'search_alternatives'.
    this.tools.set("search_alternatives", new SearchAlternativesTool(this.scryfallClient));
  • Helper method to validate and parse input arguments, enforcing types, required fields, enums, and constraints before execution.
    private validateParams(args: unknown): {
      target_card: string;
      direction: string;
      format?: string;
      max_price?: number;
      min_price?: number;
      preserve_function: boolean;
      limit: number;
    } {
      if (!args || typeof args !== 'object') {
        throw new ValidationError('Invalid parameters');
      }
    
      const params = args as any;
    
      if (!params.target_card || typeof params.target_card !== 'string') {
        throw new ValidationError('Target card is required and must be a string');
      }
    
      if (!params.direction || typeof params.direction !== 'string') {
        throw new ValidationError('Direction is required and must be a string');
      }
    
      const validDirections = ['cheaper', 'upgrade', 'similar'];
      if (!validDirections.includes(params.direction)) {
        throw new ValidationError(`Direction must be one of: ${validDirections.join(', ')}`);
      }
    
      if (params.format) {
        const validFormats = ['standard', 'modern', 'legacy', 'vintage', 'commander', 'pioneer'];
        if (!validFormats.includes(params.format)) {
          throw new ValidationError(`Format must be one of: ${validFormats.join(', ')}`);
        }
      }
    
      if (params.max_price !== undefined) {
        if (typeof params.max_price !== 'number' || params.max_price < 0) {
          throw new ValidationError('Max price must be a non-negative number');
        }
      }
    
      if (params.min_price !== undefined) {
        if (typeof params.min_price !== 'number' || params.min_price < 0) {
          throw new ValidationError('Min price must be a non-negative number');
        }
      }
    
      const preserveFunction = params.preserve_function ?? true;
      if (typeof preserveFunction !== 'boolean') {
        throw new ValidationError('Preserve function must be a boolean');
      }
    
      const limit = params.limit || 10;
      if (typeof limit !== 'number' || limit < 1 || limit > 50) {
        throw new ValidationError('Limit must be a number between 1 and 50');
      }
    
      return {
        target_card: params.target_card.trim(),
        direction: params.direction,
        format: params.format,
        max_price: params.max_price,
        min_price: params.min_price,
        preserve_function: preserveFunction,
        limit
      };
    }
  • Helper method that constructs the Scryfall search query string based on target card properties, direction, format, function preservation, and price constraints.
    private buildAlternativesQuery(targetCard: any, params: {
      direction: string;
      format?: string;
      max_price?: number;
      min_price?: number;
      preserve_function: boolean;
    }): string {
      let query = '';
    
      // Add format constraint
      if (params.format) {
        query += `f:${params.format} `;
      }
    
      // Add functional similarity constraints if requested
      if (params.preserve_function) {
        // Match primary type
        const primaryType = targetCard.type_line.split(' ')[0];
        query += `t:${primaryType} `;
    
        // Match mana value (within 1)
        const cmc = targetCard.cmc || 0;
        if (cmc > 0) {
          query += `(cmc:${cmc} OR cmc:${Math.max(0, cmc - 1)} OR cmc:${cmc + 1}) `;
        }
      }
    
      // Add price constraints based on direction
      const targetPrice = parseFloat((targetCard.prices as any).usd || '0');
      
      if (params.direction === 'cheaper' && targetPrice > 0) {
        const maxPrice = params.max_price || targetPrice * 0.8; // 20% cheaper by default
        query += `usd<=${maxPrice} `;
      } else if (params.direction === 'upgrade' && targetPrice > 0) {
        const minPrice = params.min_price || targetPrice * 1.2; // 20% more expensive by default
        query += `usd>=${minPrice} `;
      }
    
      // Add explicit price constraints
      if (params.max_price !== undefined) {
        query += `usd<=${params.max_price} `;
      }
      if (params.min_price !== undefined) {
        query += `usd>=${params.min_price} `;
      }
    
      return query.trim();
    }
Behavior2/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 of behavioral disclosure. It mentions the tool finds alternatives based on budget, upgrades, or similarity, but does not describe key behaviors like data sources, rate limits, authentication needs, or what happens if no matches are found. For a tool with 7 parameters and no annotations, this is a significant gap.

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 a single, efficient sentence: 'Find budget alternatives, upgrades, or functionally similar cards.' It is front-loaded with the core purpose and contains no wasted words, making it highly concise and well-structured.

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

Completeness3/5

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

Given the tool's complexity (7 parameters, no annotations, no output schema), the description is minimally adequate. It states the purpose but lacks behavioral context, usage guidelines, and output details. The schema covers parameters well, but without annotations or output schema, the description should do more to compensate, resulting in a moderate score.

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 all parameters thoroughly. The description adds no additional meaning beyond what the schema provides, such as explaining how 'preserve_function' interacts with 'direction' or detailing price 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.

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: 'Find budget alternatives, upgrades, or functionally similar cards.' It specifies the verb ('Find') and resource ('cards'), but does not differentiate from sibling tools like 'search_cards' or 'find_synergistic_cards,' which might have overlapping purposes. The description is specific but lacks sibling distinction.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It does not mention sibling tools or contexts where other tools might be more appropriate, such as 'search_cards' for general searches or 'find_synergistic_cards' for combo-related queries. Usage is implied by the purpose but not explicitly stated.

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

Related 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/bmurdock/scryfall-mcp'

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