Skip to main content
Glama

lookup_rule

Retrieve official Magic: The Gathering rules by section number or search text. Find exact rule text and interactions.

Instructions

Look up a specific section of the Magic: The Gathering Comprehensive Rules by section number (e.g., "702", "702.1") or search rules text. Use this when a user asks about specific game rules, rule interactions, or needs the official rule text. Returns the rule and its subsections.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sectionNoRule section number to look up (e.g. "702" or "702.1"). Returns exact match plus all subsections.
queryNoText to search for across all rule titles and text (case-insensitive).

Implementation Reference

  • Main handler function and helper functions (lookupBySection, searchByText, toEntry) implementing the lookup_rule tool logic. Dispatches to lookupBySection or searchByText based on params.
    export function handler(db: Database.Database, params: LookupRuleParams): LookupRuleResult {
      if (params.section) {
        return lookupBySection(db, params.section);
      }
      return searchByText(db, params.query!);
    }
    
    function lookupBySection(db: Database.Database, section: string): LookupRuleResult {
      // Exact match
      const exact = db.prepare(
        'SELECT * FROM rules WHERE section = ?'
      ).get(section) as RuleRow | undefined;
    
      // Subsections: match anything starting with "section." (e.g. "702" matches "702.1", "702.1a")
      const subsections = db.prepare(
        'SELECT * FROM rules WHERE section LIKE ? AND section != ? ORDER BY section'
      ).all(`${section}.%`, section) as RuleRow[];
    
      // Also get sub-subsections for sections like "702" → "702.1a"
      const subSubsections = db.prepare(
        'SELECT * FROM rules WHERE section LIKE ? AND section NOT LIKE ? AND section != ? ORDER BY section'
      ).all(`${section}%`, `${section}.%`, section) as RuleRow[];
    
      // Filter subSubsections to only those not already in subsections
      const subsectionSections = new Set(subsections.map(r => r.section));
      const additional = subSubsections.filter(r => !subsectionSections.has(r.section) && r.section !== section);
    
      const allRules: RuleEntry[] = [];
    
      if (exact) {
        allRules.push(toEntry(exact));
      }
    
      for (const r of [...subsections, ...additional]) {
        allRules.push(toEntry(r));
      }
    
      if (allRules.length === 0) {
        return {
          found: false,
          message: `No rule found for section "${section}"`,
        };
      }
    
      // Include parent context if the exact rule has a parent
      const result: LookupRuleResult = { found: true, rules: allRules };
    
      if (exact?.parent_section) {
        const parent = db.prepare(
          'SELECT * FROM rules WHERE section = ?'
        ).get(exact.parent_section) as RuleRow | undefined;
        if (parent) {
          result.parent = toEntry(parent);
        }
      }
    
      return result;
    }
    
    function searchByText(db: Database.Database, query: string): LookupRuleResult {
      const pattern = `%${query}%`;
      const rows = db.prepare(
        'SELECT * FROM rules WHERE LOWER(title) LIKE LOWER(?) OR LOWER(text) LIKE LOWER(?) ORDER BY section LIMIT 20'
      ).all(pattern, pattern) as RuleRow[];
    
      if (rows.length === 0) {
        return {
          found: false,
          message: `No rules found matching "${query}"`,
        };
      }
    
      return {
        found: true,
        rules: rows.map(toEntry),
      };
    }
    
    function toEntry(row: RuleRow): RuleEntry {
      return {
        section: row.section,
        title: row.title,
        text: row.text,
        parent_section: row.parent_section,
      };
    }
  • Input schema (LookupRuleInput) with optional 'section' and 'query' fields, and output types (RuleEntry, LookupRuleResult) for the lookup_rule tool.
    export const LookupRuleInput = z.object({
      section: z.string().optional().describe('Rule section number to look up (e.g. "702" or "702.1"). Returns exact match plus all subsections.'),
      query: z.string().optional().describe('Text to search for across all rule titles and text (case-insensitive).'),
    }).refine(data => data.section || data.query, {
      message: 'Either section or query must be provided',
    });
    
    export type LookupRuleParams = z.infer<typeof LookupRuleInput>;
    
    // --- Output types ---
    
    export interface RuleEntry {
      section: string;
      title: string | null;
      text: string;
      parent_section: string | null;
    }
    
    export type LookupRuleResult = {
      found: true;
      rules: RuleEntry[];
      parent?: RuleEntry;
    } | {
      found: false;
      message: string;
    };
  • src/server.ts:151-163 (registration)
    Registration of the 'lookup_rule' tool on the MCP server, binding the schema, handler, and formatter.
    server.tool(
      'lookup_rule',
      'Look up a specific section of the Magic: The Gathering Comprehensive Rules by section number (e.g., "702", "702.1") or search rules text. Use this when a user asks about specific game rules, rule interactions, or needs the official rule text. Returns the rule and its subsections.',
      LookupRuleInput.innerType().shape,
      async (params) => {
        try {
          const result = lookupRuleHandler(db, params);
          return { content: [{ type: 'text' as const, text: formatLookupRule(result) }] };
        } catch (err) {
          return { content: [{ type: 'text' as const, text: `Error looking up rule: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
        }
      },
    );
  • Formatter for LookupRuleResult, converting the result into human-readable markdown text.
    export function formatLookupRule(result: LookupRuleResult): string {
      if (!result.found) {
        return result.message;
      }
    
      const lines: string[] = [];
    
      if (result.parent) {
        lines.push(`(Parent: ${result.parent.section} — ${result.parent.title ?? result.parent.text})\n`);
      }
    
      for (const rule of result.rules) {
        const titlePart = rule.title ? ` — ${rule.title}` : '';
        lines.push(`**${rule.section}${titlePart}**`);
        lines.push(rule.text);
        lines.push('');
      }
    
      return lines.join('\n').trimEnd();
  • RuleRow interface defining the database row shape used by the lookup_rule handler.
    export interface RuleRow {
      section: string;
      title: string | null;
      text: string;
      parent_section: string | null;
    }
Behavior2/5

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

No annotations are provided, so the description must fully cover behavior. It states 'Returns the rule and its subsections' but omits details like read-only behavior, potential rate limits, or that no modifications occur. For a safe lookup tool, more clarity on safety would improve transparency.

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 filler. The first sentence states action and provides an example. Every word contributes to understanding the tool's function.

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?

For a simple lookup tool with no output schema and two parameters, the description covers purpose, usage, and return behavior. It could briefly mention whether both parameters can be used together, but overall it's sufficiently complete.

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

Parameters4/5

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

Schema description coverage is 100%, but the description adds value by explaining that 'section' returns exact match plus subsections and that 'query' is case-insensitive search across all text. This goes beyond the schema's parameter names.

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 uses specific verbs ('look up', 'search') and clearly identifies the resource ('Magic: The Gathering Comprehensive Rules') and methods (by section number or text search). It distinguishes from siblings like get_card or get_rulings which are for different purposes.

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?

Provides explicit guidance on when to use ('when a user asks about specific game rules, rule interactions, or needs the official rule text'). Does not explicitly mention when not to use or list alternatives, but the context is clear enough.

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