@olaservo/scryfall-mcp-server 1.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,35 @@
1
+ import { type CallToolResult, type McpServer, type ServerContext } from "@modelcontextprotocol/server";
2
+ export declare const CITATIONS_EXTENSION = "io.modelcontextprotocol/citations";
3
+ type Party = {
4
+ type: "Organization";
5
+ name: string;
6
+ };
7
+ export interface Citation {
8
+ id?: string;
9
+ name?: string;
10
+ url?: string;
11
+ text?: string;
12
+ datePublished?: string;
13
+ author?: Party;
14
+ publisher?: Party;
15
+ license?: string;
16
+ "mcp:annotations"?: {
17
+ lastModified?: string;
18
+ };
19
+ }
20
+ export declare const WIZARDS: Party;
21
+ export declare const SCRYFALL: Party;
22
+ /** Collects citations and hands out their markers. */
23
+ export declare class CitationList {
24
+ readonly items: Citation[];
25
+ /** Adds a citation and returns its marker, such as `[c1]`. */
26
+ cite(citation: Omit<Citation, "id">): string;
27
+ /** Link definitions for the markers, to end the text with. */
28
+ linkDefinitions(): string;
29
+ /**
30
+ * A tool result with the text and its link definitions. The citations go in
31
+ * `_meta` only for a client that declared support, as SEP-3094 asks.
32
+ */
33
+ result(server: McpServer, ctx: ServerContext, text: string, structuredContent?: Record<string, unknown>): CallToolResult;
34
+ }
35
+ export {};
@@ -0,0 +1,45 @@
1
+ // Citations in the shape of SEP-3094, carried in the result's `_meta` as in
2
+ // https://github.com/olaservo/citation-audit-demo. The text the model reads has
3
+ // `[cN]` markers and link definitions. The `_meta` entries carry the details.
4
+ import { CLIENT_CAPABILITIES_META_KEY, } from "@modelcontextprotocol/server";
5
+ export const CITATIONS_EXTENSION = "io.modelcontextprotocol/citations";
6
+ export const WIZARDS = { type: "Organization", name: "Wizards of the Coast" };
7
+ export const SCRYFALL = { type: "Organization", name: "Scryfall" };
8
+ /**
9
+ * Whether the client declared the citations extension. Capabilities arrive per
10
+ * request on 2026-07-28 and from `initialize` before that.
11
+ */
12
+ function declaresCitations(server, ctx) {
13
+ const envelope = ctx.mcpReq.envelope;
14
+ const caps = envelope?.[CLIENT_CAPABILITIES_META_KEY] ?? server.server.getClientCapabilities();
15
+ return caps?.extensions?.[CITATIONS_EXTENSION] !== undefined;
16
+ }
17
+ /** Collects citations and hands out their markers. */
18
+ export class CitationList {
19
+ items = [];
20
+ /** Adds a citation and returns its marker, such as `[c1]`. */
21
+ cite(citation) {
22
+ const id = `c${this.items.length + 1}`;
23
+ this.items.push({ id, ...citation });
24
+ return `[${id}]`;
25
+ }
26
+ /** Link definitions for the markers, to end the text with. */
27
+ linkDefinitions() {
28
+ return this.items
29
+ .filter((c) => c.url)
30
+ .map((c) => `[${c.id}]: ${c.url}`)
31
+ .join("\n");
32
+ }
33
+ /**
34
+ * A tool result with the text and its link definitions. The citations go in
35
+ * `_meta` only for a client that declared support, as SEP-3094 asks.
36
+ */
37
+ result(server, ctx, text, structuredContent) {
38
+ const links = this.linkDefinitions();
39
+ return {
40
+ content: [{ type: "text", text: links ? `${text}\n\n${links}` : text }],
41
+ ...(structuredContent && { structuredContent }),
42
+ ...(this.items.length > 0 && declaresCitations(server, ctx) && { _meta: { [CITATIONS_EXTENSION]: this.items } }),
43
+ };
44
+ }
45
+ }
@@ -0,0 +1,48 @@
1
+ export interface Rule {
2
+ /** "1" for a chapter, "702" for a section, "702.19" or "702.19b" for a rule. */
3
+ number: string;
4
+ /** The rule text as printed, without its number. Headings hold their title. */
5
+ text: string;
6
+ examples: string[];
7
+ }
8
+ export interface GlossaryEntry {
9
+ term: string;
10
+ text: string;
11
+ }
12
+ export interface ComprehensiveRules {
13
+ /** ISO date from the "These rules are effective as of ..." line. */
14
+ effectiveDate: string;
15
+ sourceUrl: string;
16
+ rules: Map<string, Rule>;
17
+ /** Rule numbers in document order. */
18
+ order: string[];
19
+ glossary: GlossaryEntry[];
20
+ }
21
+ /** Parses the text file Wizards publishes. */
22
+ export declare function parseComprehensiveRules(raw: string, sourceUrl: string): ComprehensiveRules;
23
+ /**
24
+ * The current Comprehensive Rules. Checks the rules page for a new release once
25
+ * a day, and keeps serving the loaded copy if that check fails.
26
+ */
27
+ export declare function getComprehensiveRules(): Promise<ComprehensiveRules>;
28
+ /** "Rule 702.19b." becomes "702.19b". Returns undefined if it is not a rule number. */
29
+ export declare function normalizeRuleNumber(input: string): string | undefined;
30
+ /** The parent of "702.19b" is "702.19", of "702.19" is "702", of "702" is "7". */
31
+ export declare function parentNumber(number: string): string | undefined;
32
+ /** Rules one level below `number`, in document order. */
33
+ export declare function childNumbers(cr: ComprehensiveRules, number: string): string[];
34
+ /** Lowercase, straight quotes, single spaces. */
35
+ export declare function normalizeText(s: string): string;
36
+ export type SearchHit = {
37
+ kind: "glossary";
38
+ entry: GlossaryEntry;
39
+ } | {
40
+ kind: "rule";
41
+ rule: Rule;
42
+ };
43
+ /**
44
+ * Glossary terms and rules that contain every word of the query. Exact glossary
45
+ * terms and headings come first, then text with the whole phrase, then the rest,
46
+ * each in document order.
47
+ */
48
+ export declare function searchRules(cr: ComprehensiveRules, query: string, limit: number): SearchHit[];
@@ -0,0 +1,192 @@
1
+ import { USER_AGENT } from "../scryfall-api.js";
2
+ // Wizards links the current Comprehensive Rules text file from this page.
3
+ const RULES_PAGE = "https://magic.wizards.com/en/rules";
4
+ const REFRESH_MS = 24 * 60 * 60 * 1000;
5
+ const MONTHS = [
6
+ "january", "february", "march", "april", "may", "june",
7
+ "july", "august", "september", "october", "november", "december",
8
+ ];
9
+ const CHAPTER = /^(\d)\. (.+)$/;
10
+ const SECTION = /^(\d{3})\. (.+)$/;
11
+ const RULE = /^(\d{3}\.\d+[a-z]*)\.? (.+)$/;
12
+ function effectiveDate(lines) {
13
+ for (const line of lines.slice(0, 10)) {
14
+ const m = /effective as of (\w+) (\d{1,2}), (\d{4})/.exec(line);
15
+ const month = m && MONTHS.indexOf(m[1].toLowerCase());
16
+ if (m && month !== null && month >= 0) {
17
+ return `${m[3]}-${String(month + 1).padStart(2, "0")}-${m[2].padStart(2, "0")}`;
18
+ }
19
+ }
20
+ throw new Error("Comprehensive Rules: no effective date in the file header");
21
+ }
22
+ /** Parses the text file Wizards publishes. */
23
+ export function parseComprehensiveRules(raw, sourceUrl) {
24
+ const lines = raw.replace(/^/, "").split(/\r?\n/).map((l) => l.trimEnd());
25
+ // "Glossary" and "Credits" each appear twice: once in the contents, once as a heading.
26
+ const glossaryAt = lines.lastIndexOf("Glossary");
27
+ const creditsAt = lines.lastIndexOf("Credits");
28
+ const contentsCreditsAt = lines.indexOf("Credits");
29
+ const bodyAt = lines.findIndex((l, i) => i > contentsCreditsAt && CHAPTER.test(l));
30
+ if (glossaryAt < 0 || creditsAt < glossaryAt || bodyAt < 0 || bodyAt > glossaryAt) {
31
+ throw new Error("Comprehensive Rules: unexpected file layout");
32
+ }
33
+ const rules = new Map();
34
+ const order = [];
35
+ let last;
36
+ for (const line of lines.slice(bodyAt, glossaryAt)) {
37
+ if (line.trim() === "")
38
+ continue;
39
+ const m = CHAPTER.exec(line) ?? SECTION.exec(line) ?? RULE.exec(line);
40
+ if (m) {
41
+ last = { number: m[1], text: m[2], examples: [] };
42
+ rules.set(last.number, last);
43
+ order.push(last.number);
44
+ }
45
+ else if (!last) {
46
+ continue;
47
+ }
48
+ else if (line.startsWith("Example: ")) {
49
+ last.examples.push(line.slice("Example: ".length));
50
+ }
51
+ else {
52
+ // An indented line continues the rule above it.
53
+ last.text += "\n" + line;
54
+ }
55
+ }
56
+ const glossary = [];
57
+ let entry = [];
58
+ for (const line of [...lines.slice(glossaryAt + 1, creditsAt), ""]) {
59
+ if (line.trim() !== "") {
60
+ entry.push(line);
61
+ }
62
+ else if (entry.length > 0) {
63
+ glossary.push({ term: entry[0], text: entry.slice(1).join("\n") });
64
+ entry = [];
65
+ }
66
+ }
67
+ return { effectiveDate: effectiveDate(lines), sourceUrl, rules, order, glossary };
68
+ }
69
+ async function get(url) {
70
+ const res = await fetch(url, { headers: { "User-Agent": USER_AGENT, Accept: "*/*" } });
71
+ if (!res.ok)
72
+ throw new Error(`GET ${url} returned ${res.status}`);
73
+ return res;
74
+ }
75
+ /** The URL of the current rules text file, or MTG_CR_URL if set. */
76
+ async function discoverUrl() {
77
+ if (process.env.MTG_CR_URL)
78
+ return process.env.MTG_CR_URL;
79
+ const html = await (await get(RULES_PAGE)).text();
80
+ const m = /https:\/\/media\.wizards\.com\/[^"'<>]*?MagicCompRules[^"'<>]*?\.txt/i.exec(html);
81
+ if (!m)
82
+ throw new Error(`No Comprehensive Rules .txt link on ${RULES_PAGE}`);
83
+ // The page links the file with a literal space in its name.
84
+ return new URL(m[0]).href;
85
+ }
86
+ function decode(bytes) {
87
+ try {
88
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
89
+ }
90
+ catch {
91
+ // Older releases were Windows-1252.
92
+ return new TextDecoder("windows-1252").decode(bytes);
93
+ }
94
+ }
95
+ let cached;
96
+ let loading;
97
+ async function load() {
98
+ const url = await discoverUrl();
99
+ if (cached && cached.cr.sourceUrl === url)
100
+ return cached.cr;
101
+ const res = await get(url);
102
+ const cr = parseComprehensiveRules(decode(await res.arrayBuffer()), url);
103
+ if (cr.order.length < 1000 || cr.glossary.length < 100) {
104
+ throw new Error(`Comprehensive Rules: parsed only ${cr.order.length} rules and ${cr.glossary.length} glossary entries from ${url}`);
105
+ }
106
+ return cr;
107
+ }
108
+ /**
109
+ * The current Comprehensive Rules. Checks the rules page for a new release once
110
+ * a day, and keeps serving the loaded copy if that check fails.
111
+ */
112
+ export function getComprehensiveRules() {
113
+ if (cached && Date.now() - cached.checkedAt < REFRESH_MS)
114
+ return Promise.resolve(cached.cr);
115
+ loading ??= load()
116
+ .catch((err) => {
117
+ if (!cached)
118
+ throw err;
119
+ console.error("Comprehensive Rules refresh failed, keeping the loaded copy:", err);
120
+ return cached.cr;
121
+ })
122
+ .then((cr) => {
123
+ cached = { cr, checkedAt: Date.now() };
124
+ return cr;
125
+ })
126
+ .finally(() => {
127
+ loading = undefined;
128
+ });
129
+ return loading;
130
+ }
131
+ const RULE_NUMBER = /^(\d|\d{3}|\d{3}\.\d+[a-z]*)$/;
132
+ /** "Rule 702.19b." becomes "702.19b". Returns undefined if it is not a rule number. */
133
+ export function normalizeRuleNumber(input) {
134
+ const n = input.trim().toLowerCase().replace(/^(cr|rule)\s*/, "").replace(/\.$/, "");
135
+ return RULE_NUMBER.test(n) ? n : undefined;
136
+ }
137
+ /** The parent of "702.19b" is "702.19", of "702.19" is "702", of "702" is "7". */
138
+ export function parentNumber(number) {
139
+ if (/[a-z]$/.test(number))
140
+ return number.replace(/[a-z]+$/, "");
141
+ if (number.includes("."))
142
+ return number.split(".")[0];
143
+ if (number.length === 3)
144
+ return number[0];
145
+ return undefined;
146
+ }
147
+ /** Rules one level below `number`, in document order. */
148
+ export function childNumbers(cr, number) {
149
+ return cr.order.filter((n) => parentNumber(n) === number);
150
+ }
151
+ /** Lowercase, straight quotes, single spaces. */
152
+ export function normalizeText(s) {
153
+ return s
154
+ .toLowerCase()
155
+ .replace(/[‘’]/g, "'")
156
+ .replace(/[“”]/g, '"')
157
+ .replace(/\s+/g, " ")
158
+ .trim();
159
+ }
160
+ /**
161
+ * Glossary terms and rules that contain every word of the query. Exact glossary
162
+ * terms and headings come first, then text with the whole phrase, then the rest,
163
+ * each in document order.
164
+ */
165
+ export function searchRules(cr, query, limit) {
166
+ const phrase = normalizeText(query);
167
+ const words = phrase.split(" ").filter(Boolean);
168
+ if (words.length === 0)
169
+ return [];
170
+ const scored = [];
171
+ cr.glossary.forEach((entry, index) => {
172
+ const term = normalizeText(entry.term);
173
+ const body = term + " " + normalizeText(entry.text);
174
+ if (!words.every((w) => body.includes(w)))
175
+ return;
176
+ const score = term === phrase ? 4 : term.includes(phrase) ? 3 : body.includes(phrase) ? 2 : 1;
177
+ scored.push({ hit: { kind: "glossary", entry }, score, index });
178
+ });
179
+ cr.order.forEach((number, i) => {
180
+ const rule = cr.rules.get(number);
181
+ const text = normalizeText(rule.text);
182
+ if (!words.every((w) => text.includes(w)))
183
+ return;
184
+ const heading = !/[a-z]$/.test(number) && rule.text.length < 60;
185
+ const score = heading && text === phrase ? 4 : text.includes(phrase) ? 2 : 1;
186
+ scored.push({ hit: { kind: "rule", rule }, score, index: cr.glossary.length + i });
187
+ });
188
+ return scored
189
+ .sort((a, b) => b.score - a.score || a.index - b.index)
190
+ .slice(0, limit)
191
+ .map((s) => s.hit);
192
+ }
@@ -1,5 +1,7 @@
1
+ export declare const USER_AGENT = "scryfall-mcp-server/1.0 (+https://github.com/olaservo/scryfall-mcp-app)";
1
2
  export interface ScryfallCard {
2
3
  id: string;
4
+ oracle_id?: string;
3
5
  name: string;
4
6
  scryfall_uri: string;
5
7
  set: string;
@@ -31,6 +33,15 @@ export interface ScryfallError {
31
33
  status: number;
32
34
  body: string;
33
35
  }
34
- export declare function isScryfallError(result: ScryfallSearchResponse | ScryfallCard | ScryfallError): result is ScryfallError;
36
+ export interface ScryfallRuling {
37
+ oracle_id: string;
38
+ /** "wotc" for Wizards of the Coast, "scryfall" for Scryfall's own notes. */
39
+ source: "wotc" | "scryfall";
40
+ published_at: string;
41
+ comment: string;
42
+ }
43
+ export declare function isScryfallError<T extends object>(result: T | ScryfallError): result is ScryfallError;
35
44
  export declare function searchCards(query: string): Promise<ScryfallSearchResponse | ScryfallError>;
36
45
  export declare function fetchCard(id: string): Promise<ScryfallCard | ScryfallError>;
46
+ export declare function fetchCardByName(name: string): Promise<ScryfallCard | ScryfallError>;
47
+ export declare function fetchRulings(id: string): Promise<ScryfallRuling[] | ScryfallError>;
@@ -1,5 +1,5 @@
1
1
  const BASE_URL = "https://api.scryfall.com";
2
- const USER_AGENT = "scryfall-mcp-server/1.0 (+https://github.com/olaservo/scryfall-mcp-app)";
2
+ export const USER_AGENT = "scryfall-mcp-server/1.0 (+https://github.com/olaservo/scryfall-mcp-app)";
3
3
  const MIN_DELAY_MS = 120; // ~8-9 rps (Scryfall asks for 50-100ms & <10 rps)
4
4
  let lastCall = 0;
5
5
  async function rateLimit() {
@@ -38,3 +38,22 @@ export async function fetchCard(id) {
38
38
  }
39
39
  return (await res.json());
40
40
  }
41
+ export async function fetchCardByName(name) {
42
+ await rateLimit();
43
+ const url = new URL(`${BASE_URL}/cards/named`);
44
+ url.searchParams.set("fuzzy", name);
45
+ const res = await fetch(url.toString(), { headers: headers() });
46
+ if (!res.ok) {
47
+ return { status: res.status, body: await res.text() };
48
+ }
49
+ return (await res.json());
50
+ }
51
+ export async function fetchRulings(id) {
52
+ await rateLimit();
53
+ const url = `${BASE_URL}/cards/${encodeURIComponent(id)}/rulings`;
54
+ const res = await fetch(url, { headers: headers() });
55
+ if (!res.ok) {
56
+ return { status: res.status, body: await res.text() };
57
+ }
58
+ return (await res.json()).data;
59
+ }
package/dist/server.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
2
  export declare function createServer(): McpServer;
package/dist/server.js CHANGED
@@ -1,9 +1,9 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
2
  import { registerTools } from "./tools/index.js";
3
3
  export function createServer() {
4
4
  const server = new McpServer({
5
5
  name: "scryfall-mcp-server",
6
- version: "1.0.0",
6
+ version: "2.1.0",
7
7
  }, {
8
8
  capabilities: {
9
9
  tools: {},
@@ -11,7 +11,10 @@ export function createServer() {
11
11
  },
12
12
  instructions: "Search and fetch Magic: The Gathering card data from Scryfall. " +
13
13
  "Use the 'search' tool with Scryfall full-text query syntax to find cards, " +
14
- "then use 'fetch' with a card ID to get full details.",
14
+ "then use 'fetch' with a card ID to get full details. " +
15
+ "For rules questions, use 'get_rule' and 'search_rules' for the Comprehensive Rules " +
16
+ "and 'get_rulings' for a card's Oracle text and rulings. " +
17
+ "Cite them with the [cN] markers and links they return, and give the rules' effective date.",
15
18
  });
16
19
  registerTools(server);
17
20
  return server;
@@ -1,3 +1,3 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
2
  export declare const CARD_VIEWER_URI = "ui://scryfall/card-viewer.html";
3
3
  export declare const registerFetchTool: (server: McpServer) => void;
@@ -1,14 +1,12 @@
1
1
  import { z } from "zod";
2
2
  import { fetchCard, isScryfallError } from "../scryfall-api.js";
3
- import { registerAppTool } from "@modelcontextprotocol/ext-apps/server";
3
+ import { registerAppTool } from "../ui-meta.js";
4
4
  export const CARD_VIEWER_URI = "ui://scryfall/card-viewer.html";
5
- const FetchInputShape = {
5
+ const FetchSchema = z.object({
6
6
  id: z
7
- .string()
8
7
  .uuid()
9
8
  .describe("Scryfall card UUID (obtained from the search tool results)"),
10
- };
11
- const FetchSchema = z.object(FetchInputShape);
9
+ });
12
10
  function formatCardText(card) {
13
11
  const parts = [];
14
12
  // Card faces or single card text
@@ -50,7 +48,7 @@ export const registerFetchTool = (server) => {
50
48
  description: "Fetch detailed information for a single Magic: The Gathering card by its Scryfall UUID. " +
51
49
  "Returns the card's full oracle text, type line, mana cost, colors, set info, rarity, " +
52
50
  "prices, and image URIs. Handles double-faced cards (e.g., transform, modal DFC).",
53
- inputSchema: FetchInputShape,
51
+ inputSchema: FetchSchema,
54
52
  annotations: {
55
53
  readOnlyHint: true,
56
54
  destructiveHint: false,
@@ -60,8 +58,7 @@ export const registerFetchTool = (server) => {
60
58
  _meta: {
61
59
  ui: { resourceUri: CARD_VIEWER_URI },
62
60
  },
63
- }, async (args) => {
64
- const { id } = FetchSchema.parse(args);
61
+ }, async ({ id }) => {
65
62
  const result = await fetchCard(id);
66
63
  if (isScryfallError(result)) {
67
64
  return {
@@ -1,2 +1,2 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
2
  export declare const registerTools: (server: McpServer) => void;
@@ -1,6 +1,8 @@
1
- import { registerAppResource, RESOURCE_MIME_TYPE, } from "@modelcontextprotocol/ext-apps/server";
1
+ import { registerAppResource, RESOURCE_MIME_TYPE } from "../ui-meta.js";
2
2
  import { registerSearchTool } from "./search.js";
3
3
  import { registerFetchTool, CARD_VIEWER_URI } from "./fetch.js";
4
+ import { registerRulesTools } from "./rules.js";
5
+ import { registerRulingsTool } from "./rulings.js";
4
6
  import fs from "node:fs/promises";
5
7
  import path from "node:path";
6
8
  import { fileURLToPath } from "node:url";
@@ -16,6 +18,8 @@ function getDistDir() {
16
18
  export const registerTools = (server) => {
17
19
  registerSearchTool(server);
18
20
  registerFetchTool(server);
21
+ registerRulesTools(server);
22
+ registerRulingsTool(server);
19
23
  registerAppResource(server, CARD_VIEWER_URI, CARD_VIEWER_URI, { mimeType: RESOURCE_MIME_TYPE }, async () => {
20
24
  const distDir = getDistDir();
21
25
  const html = await fs.readFile(path.join(distDir, "card-viewer.html"), "utf-8");
@@ -0,0 +1,2 @@
1
+ import type { McpServer } from "@modelcontextprotocol/server";
2
+ export declare const registerRulesTools: (server: McpServer) => void;
@@ -0,0 +1,128 @@
1
+ import { z } from "zod";
2
+ import { CitationList, WIZARDS } from "../citations.js";
3
+ import { childNumbers, getComprehensiveRules, normalizeRuleNumber, parentNumber, searchRules, } from "../rules/comprehensive-rules.js";
4
+ const ANNOTATIONS = {
5
+ readOnlyHint: true,
6
+ destructiveHint: false,
7
+ idempotentHint: true,
8
+ openWorldHint: true,
9
+ };
10
+ function errorResult(message) {
11
+ return { content: [{ type: "text", text: message }], isError: true };
12
+ }
13
+ function header(cr) {
14
+ return `Magic: The Gathering Comprehensive Rules, effective ${cr.effectiveDate}.`;
15
+ }
16
+ function citeRule(list, cr, rule) {
17
+ return list.cite({
18
+ name: `Magic: The Gathering Comprehensive Rules, rule ${rule.number}`,
19
+ url: cr.sourceUrl,
20
+ text: rule.text,
21
+ publisher: WIZARDS,
22
+ "mcp:annotations": { lastModified: cr.effectiveDate },
23
+ });
24
+ }
25
+ function citeGlossary(list, cr, entry) {
26
+ return list.cite({
27
+ name: `Magic: The Gathering Comprehensive Rules, glossary: ${entry.term}`,
28
+ url: cr.sourceUrl,
29
+ text: entry.text,
30
+ publisher: WIZARDS,
31
+ "mcp:annotations": { lastModified: cr.effectiveDate },
32
+ });
33
+ }
34
+ function formatRule(rule, marker) {
35
+ return [`${rule.number} ${rule.text} ${marker}`, ...rule.examples.map((e) => `Example: ${e}`)].join("\n");
36
+ }
37
+ function truncate(s, n) {
38
+ const line = s.split("\n")[0];
39
+ return line.length > n ? line.slice(0, n - 1) + "…" : line;
40
+ }
41
+ function structuredRule(rule) {
42
+ return { number: rule.number, text: rule.text, examples: rule.examples };
43
+ }
44
+ const GetRuleSchema = z.object({
45
+ number: z
46
+ .string()
47
+ .min(1)
48
+ .describe('A rule number: "702.19b" for one subrule, "702.19" for a rule and its subrules, ' +
49
+ '"702" for a section\'s contents, "7" for a chapter\'s contents.'),
50
+ });
51
+ const SearchRulesSchema = z.object({
52
+ query: z
53
+ .string()
54
+ .min(1)
55
+ .describe('Words to find in rule text and glossary terms, e.g. "trample", "mana pool empties".'),
56
+ limit: z.number().int().min(1).max(50).default(10).describe("Most results to return. Default 10."),
57
+ });
58
+ export const registerRulesTools = (server) => {
59
+ server.registerTool("get_rule", {
60
+ title: "Get Comprehensive Rule",
61
+ description: "Look up the Magic: The Gathering Comprehensive Rules by rule number. " +
62
+ "Returns the rule text with its examples, the subrules of a rule, or the contents of a section. " +
63
+ "Each answer states the effective date of the rules it came from and carries citation markers " +
64
+ "to quote when answering a rules question.",
65
+ inputSchema: GetRuleSchema,
66
+ annotations: ANNOTATIONS,
67
+ }, async ({ number: input }, ctx) => {
68
+ const number = normalizeRuleNumber(input);
69
+ if (!number)
70
+ return errorResult(`"${input}" is not a rule number. Use a form like 702.19b, 702.19, 702 or 7.`);
71
+ const cr = await getComprehensiveRules();
72
+ const rule = cr.rules.get(number);
73
+ if (!rule)
74
+ return errorResult(`${header(cr)}\nThere is no rule ${number}. Try search_rules.`);
75
+ const list = new CitationList();
76
+ const parts = [header(cr)];
77
+ const isHeading = !number.includes(".");
78
+ if (isHeading) {
79
+ // A chapter or section: list its contents without citing each one.
80
+ const children = childNumbers(cr, number).map((n) => cr.rules.get(n));
81
+ parts.push(`${rule.number}. ${rule.text} ${citeRule(list, cr, rule)}`, children.map((c) => `${c.number} ${truncate(c.text, 100)}`).join("\n"), "Call get_rule with one of these numbers for its full text.");
82
+ return list.result(server, ctx, parts.join("\n\n"), {
83
+ effective_date: cr.effectiveDate,
84
+ source_url: cr.sourceUrl,
85
+ rule: structuredRule(rule),
86
+ contents: children.map((c) => ({ number: c.number, text: truncate(c.text, 100) })),
87
+ });
88
+ }
89
+ const shown = [];
90
+ const parent = /[a-z]$/.test(number) ? cr.rules.get(parentNumber(number)) : undefined;
91
+ if (parent)
92
+ shown.push(parent);
93
+ shown.push(rule);
94
+ if (!parent)
95
+ shown.push(...childNumbers(cr, number).map((n) => cr.rules.get(n)));
96
+ parts.push(shown.map((r) => formatRule(r, citeRule(list, cr, r))).join("\n\n"));
97
+ return list.result(server, ctx, parts.join("\n\n"), {
98
+ effective_date: cr.effectiveDate,
99
+ source_url: cr.sourceUrl,
100
+ rules: shown.map(structuredRule),
101
+ });
102
+ });
103
+ server.registerTool("search_rules", {
104
+ title: "Search Comprehensive Rules",
105
+ description: "Search the Magic: The Gathering Comprehensive Rules and their glossary for rules that contain every word of the query. " +
106
+ "Exact glossary terms and rule headings come first. Use get_rule on a result's number for its subrules and examples. " +
107
+ "Each answer states the effective date of the rules and carries citation markers.",
108
+ inputSchema: SearchRulesSchema,
109
+ annotations: ANNOTATIONS,
110
+ }, async ({ query, limit }, ctx) => {
111
+ const cr = await getComprehensiveRules();
112
+ const hits = searchRules(cr, query, limit);
113
+ if (hits.length === 0) {
114
+ return { content: [{ type: "text", text: `${header(cr)}\nNo rule or glossary entry contains every word of "${query}".` }] };
115
+ }
116
+ const list = new CitationList();
117
+ const lines = hits.map((hit) => hit.kind === "glossary"
118
+ ? `Glossary: ${hit.entry.term}\n${hit.entry.text} ${citeGlossary(list, cr, hit.entry)}`
119
+ : `${hit.rule.number} ${hit.rule.text} ${citeRule(list, cr, hit.rule)}`);
120
+ return list.result(server, ctx, [header(cr), ...lines].join("\n\n"), {
121
+ effective_date: cr.effectiveDate,
122
+ source_url: cr.sourceUrl,
123
+ results: hits.map((hit) => hit.kind === "glossary"
124
+ ? { kind: "glossary", term: hit.entry.term, text: hit.entry.text }
125
+ : { kind: "rule", number: hit.rule.number, text: hit.rule.text }),
126
+ });
127
+ });
128
+ };
@@ -0,0 +1,2 @@
1
+ import type { McpServer } from "@modelcontextprotocol/server";
2
+ export declare const registerRulingsTool: (server: McpServer) => void;