leejunyoung5819mc-paper-plugin-test-mcp-26.3

공개

마인크래프트 26.3 Paper 서버의 플러그인 테스트를 하려는 AI 에이전트를 위한 MCP 도구

220줄9.9 KB
1// YAML scenario runner: ordered tool calls + assertions, with failure screenshots and a JSON report.
2import fs from 'node:fs';
3import path from 'node:path';
4import YAML from 'yaml';
5import { DIRS, ROOT, stamp } from './config.ts';
6import { TOOL_MAP, type Ctx } from './tools.ts';
7import { sleep } from './paper.ts';
8
9/** For `- tool: "string"` shorthand: which parameter the string fills. */
10const DEFAULT_ARG: Record<string, string> = {
11 rcon: 'command',
12 chat: 'text',
13 type_text: 'text',
14 key: 'key',
15 screenshot: 'label',
16 world_reset: 'name',
17 world_snapshot: 'name',
18 client_launch: 'name',
19 client_stop: 'client',
20 expect_rcon: 'command',
21 expect_chat: 'chat',
22 run_scenario: 'file',
23};
24
25interface StepResult {
26 phase: string;
27 index: number;
28 label?: string;
29 tool: string;
30 args: any;
31 ok: boolean;
32 ms: number;
33 result?: any;
34 error?: string;
35 skipped?: boolean;
36}
37
38function short(v: any, max = 1500): any {
39 const s = JSON.stringify(v);
40 if (s === undefined || s.length <= max) return v;
41 return s.slice(0, max) + `... (${s.length} chars)`;
42}
43
44function parseStep(raw: any): { tool: string; args: any; label?: string } {
45 if (typeof raw === 'string') return { tool: raw, args: {} };
46 const keys = Object.keys(raw).filter((k) => k !== 'label');
47 if (keys.length !== 1) throw new Error(`a step must have exactly one tool key (plus optional label): ${JSON.stringify(raw)}`);
48 const tool = keys[0];
49 let args = raw[tool];
50 if (args === null || args === undefined) args = {};
51 else if (typeof args !== 'object') {
52 if (tool === 'sleep') args = { ms: Number(args) };
53 else if (DEFAULT_ARG[tool]) args = { [DEFAULT_ARG[tool]]: args };
54 else throw new Error(`step '${tool}' needs an object of arguments`);
55 }
56 return { tool, args, label: raw.label };
57}
58
59function itemMatches(item: any, q: any): boolean {
60 if (!item) return false;
61 if (q.id && item.id !== q.id && item.id !== `minecraft:${q.id}`) return false;
62 if (q.name && !String(item.name).includes(q.name)) return false;
63 if (q.lore && !(item.lore ?? []).concat(item.tooltip ?? []).some((l: string) => l.includes(q.lore))) return false;
64 return true;
65}
66
67function compareCount(actual: number, q: any): boolean {
68 if (q.count !== undefined && actual !== q.count) return false;
69 if (q.min !== undefined && actual < q.min) return false;
70 if (q.max !== undefined && actual > q.max) return false;
71 return true;
72}
73
74export async function runScenario(ctx: Ctx, file: string, opts: { stopOnFail?: boolean } = {}): Promise<object> {
75 const abs = path.isAbsolute(file) ? file : path.join(ROOT, file);
76 const doc = YAML.parse(fs.readFileSync(abs, 'utf8')) ?? {};
77 const name = doc.name ?? path.basename(abs);
78 const stopOnFail = opts.stopOnFail ?? true;
79 const startSeq = ctx.server.running ? ctx.server.logSeq : 0;
80 const results: StepResult[] = [];
81 const screenshots: string[] = [];
82 const t0 = Date.now();
83 let failed = false;
84
85 const asserts: Record<string, (a: any) => Promise<any>> = {
86 sleep: async (a) => {
87 await sleep(a.ms ?? 500);
88 return { slept: a.ms ?? 500 };
89 },
90 expect_rcon: async (a) => {
91 const out: string = await ctx.server.command(a.command);
92 if (a.contains !== undefined && !out.includes(a.contains)) throw new Error(`rcon output does not contain ${JSON.stringify(a.contains)}: ${out}`);
93 if (a.not_contains !== undefined && out.includes(a.not_contains)) throw new Error(`rcon output contains ${JSON.stringify(a.not_contains)}: ${out}`);
94 if (a.matches !== undefined && !new RegExp(a.matches).test(out)) throw new Error(`rcon output does not match /${a.matches}/: ${out}`);
95 if (a.json !== undefined) {
96 const m = out.match(/\{.*\}/s);
97 if (!m) throw new Error(`rcon output has no JSON object: ${out}`);
98 const obj = JSON.parse(m[0]);
99 for (const [k, v] of Object.entries(a.json)) {
100 if (JSON.stringify(obj[k]) !== JSON.stringify(v)) throw new Error(`json.${k} = ${JSON.stringify(obj[k])}, expected ${JSON.stringify(v)} (full: ${m[0]})`);
101 }
102 }
103 return { output: out };
104 },
105 expect_chat: async (a) => TOOL_MAP.get('wait_for')!.run(ctx, { client: a.client, chat: a.chat, since: a.since, timeout_ms: a.timeout_ms ?? 5000 }),
106 expect_screen: async (a) => {
107 const scr = await ctx.clients.call(a.client, 'screen');
108 if (a.closed === true) {
109 if (scr.open) throw new Error(`expected no screen, but ${scr.class} "${scr.title}" is open`);
110 return { closed: true };
111 }
112 if (!scr.open) throw new Error('expected a screen to be open, but none is');
113 if (a.title !== undefined && !new RegExp(a.title).test(scr.title)) throw new Error(`screen title "${scr.title}" does not match /${a.title}/`);
114 if (a.has_item) {
115 const q = a.has_item;
116 const area = q.area ?? 'container';
117 const hits = (scr.slots ?? []).filter((s: any) => (area === 'any' || s.area === area) && itemMatches(s.item, q));
118 if (hits.length === 0) throw new Error(`no ${area} slot with ${JSON.stringify(q)}`);
119 if (q.slot !== undefined && !hits.some((h: any) => h.slot === q.slot)) throw new Error(`item found but not in slot ${q.slot}: ${hits.map((h: any) => h.slot)}`);
120 }
121 if (a.carried !== undefined) {
122 if (a.carried === null && scr.carried) throw new Error(`expected empty cursor, carrying ${JSON.stringify(scr.carried)}`);
123 if (a.carried && !itemMatches(scr.carried, a.carried)) throw new Error(`cursor item ${JSON.stringify(scr.carried)} != ${JSON.stringify(a.carried)}`);
124 }
125 return { title: scr.title, class: scr.class };
126 },
127 expect_inventory: async (a) => {
128 const st = await ctx.clients.call(a.client, 'state');
129 const total = (st.player?.inventory ?? [])
130 .filter((e: any) => itemMatches(e.item, a))
131 .reduce((n: number, e: any) => n + e.item.count, 0);
132 if (!compareCount(total, a)) throw new Error(`inventory has ${total} of ${JSON.stringify({ id: a.id, name: a.name })}, expected ${JSON.stringify({ count: a.count, min: a.min, max: a.max })}`);
133 return { count: total };
134 },
135 expect_no_server_errors: async (a) => {
136 const errs = ctx.server.errors(a.since ?? startSeq).filter((l) => !(a.ignore ?? []).some((ig: string) => new RegExp(ig).test(l.text)));
137 if (errs.length) throw new Error(`server logged ${errs.length} error line(s):\n${errs.slice(0, 20).map((l) => l.text).join('\n')}`);
138 return { errors: 0 };
139 },
140 expect_error: async (a) => {
141 // Run a nested step that MUST fail (e.g. clicking something that should be rejected).
142 const inner = parseStep(a.step);
143 try {
144 await exec(inner.tool, inner.args);
145 } catch (e) {
146 const msg = (e as Error).message;
147 if (a.matches && !new RegExp(a.matches).test(msg)) throw new Error(`step failed, but message /${a.matches}/ not matched: ${msg}`);
148 return { failedAsExpected: msg };
149 }
150 throw new Error(`expected step ${inner.tool} to fail, but it succeeded`);
151 },
152 };
153
154 async function exec(tool: string, args: any): Promise<any> {
155 if (asserts[tool]) return asserts[tool](args);
156 const t = TOOL_MAP.get(tool);
157 if (!t) throw new Error(`unknown step '${tool}'. Tools: ${[...TOOL_MAP.keys()].join(', ')}; assertions: ${Object.keys(asserts).join(', ')}`);
158 if (tool === 'run_scenario') throw new Error('nested run_scenario is not supported');
159 return t.run(ctx, args);
160 }
161
162 async function phase(phaseName: string, steps: any[] | undefined, always = false) {
163 for (const [i, raw] of (steps ?? []).entries()) {
164 let parsed: { tool: string; args: any; label?: string };
165 try {
166 parsed = parseStep(raw);
167 } catch (e) {
168 results.push({ phase: phaseName, index: i, tool: '?', args: raw, ok: false, ms: 0, error: (e as Error).message });
169 failed = true;
170 if (stopOnFail && !always) return;
171 continue;
172 }
173 if (failed && stopOnFail && !always) {
174 results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: false, ms: 0, skipped: true });
175 continue;
176 }
177 const s0 = Date.now();
178 try {
179 const result = await exec(parsed.tool, parsed.args);
180 if (result?.screenshot) screenshots.push(result.screenshot);
181 if (parsed.tool === 'screenshot' && result?.path) screenshots.push(result.path);
182 results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: true, ms: Date.now() - s0, result: short(result) });
183 } catch (e) {
184 failed = failed || !always;
185 const err = (e as Error).message;
186 results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: false, ms: Date.now() - s0, error: err });
187 // Evidence: screenshot every running client at the moment of failure.
188 for (const c of ctx.clients.running()) {
189 try {
190 const r = await TOOL_MAP.get('screenshot')!.run(ctx, { client: c, label: `FAIL-${parsed.tool}` });
191 screenshots.push(r.path);
192 } catch {
193 /* ignore */
194 }
195 }
196 }
197 }
198 }
199
200 await phase('setup', doc.setup);
201 await phase('steps', doc.steps);
202 await phase('teardown', doc.teardown, true);
203
204 const passed = !failed && results.every((r) => r.ok || r.phase === 'teardown');
205 const serverErrors = ctx.server.running || ctx.server.logSeq > 0 ? ctx.server.errors(startSeq).slice(0, 50).map((l) => l.text) : [];
206 const report = {
207 name,
208 file: path.relative(ROOT, abs),
209 passed,
210 durationMs: Date.now() - t0,
211 failures: results.filter((r) => !r.ok && !r.skipped).map((r) => ({ phase: r.phase, index: r.index, label: r.label, tool: r.tool, error: r.error })),
212 steps: results,
213 screenshots,
214 serverErrors,
215 };
216 fs.mkdirSync(DIRS.reports, { recursive: true });
217 const reportPath = path.join(DIRS.reports, `${stamp()}-${path.basename(abs).replace(/\.ya?ml$/, '')}.json`);
218 fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
219 return { ...report, report: reportPath };
220}