leejunyoung5819mc-paper-plugin-test-mcp-26.3

공개

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

289줄11 KB
1// Minimal Minecraft + Fabric launcher: resolves 26.x version metadata, downloads (cached, hash-verified)
2// client jar / libraries / assets / Fabric loader, and builds the java command line for one client.
3import fs from 'node:fs';
4import path from 'node:path';
5import os from 'node:os';
6import { DIRS, ROOT, expandGlob, type Config } from './config.ts';
7import { download, downloadAll, fetchJson, type DownloadSpec } from './download.ts';
8import type { Identity } from './auth.ts';
9
10const MANIFEST = 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json';
11const OS_NAME = process.platform === 'darwin' ? 'osx' : process.platform === 'win32' ? 'windows' : 'linux';
12const ARCH = os.arch() === 'x64' ? 'x86_64' : os.arch();
13
14interface Rule {
15 action: 'allow' | 'disallow';
16 os?: { name?: string; arch?: string };
17 features?: Record<string, boolean>;
18}
19
20function rulesAllow(rules: Rule[] | undefined, features: Record<string, boolean> = {}): boolean {
21 if (!rules || rules.length === 0) return true;
22 let allowed = false;
23 for (const r of rules) {
24 let match = true;
25 if (r.os?.name && r.os.name !== OS_NAME) match = false;
26 if (r.os?.arch && r.os.arch !== (ARCH === 'x86_64' ? 'x86_64' : ARCH)) match = false;
27 if (r.features) for (const [k, v] of Object.entries(r.features)) if ((features[k] ?? false) !== v) match = false;
28 if (match) allowed = r.action === 'allow';
29 }
30 return allowed;
31}
32
33function mavenPath(coord: string): string {
34 const [group, artifact, version, classifier] = coord.split(':');
35 const file = `${artifact}-${version}${classifier ? '-' + classifier : ''}.jar`;
36 return [...group.split('.'), artifact, version, file].join('/');
37}
38
39function libKey(coord: string): string {
40 const [g, a, , c] = coord.split(':');
41 return `${g}:${a}${c ? ':' + c : ''}`;
42}
43
44export interface Installation {
45 version: any;
46 fabric: any;
47 classpath: string[];
48 clientJar: string;
49 assetsDir: string;
50 assetIndex: string;
51 logConfig: string | null;
52 mods: string[];
53}
54
55let cached: Promise<Installation> | null = null;
56
57/** Download/verify everything needed to run the client. Safe to call repeatedly (cached per process). */
58export function install(cfg: Config, log: (m: string) => void = () => {}): Promise<Installation> {
59 if (!cached) cached = doInstall(cfg, log).catch((e) => {
60 cached = null;
61 throw e;
62 });
63 return cached;
64}
65
66async function doInstall(cfg: Config, log: (m: string) => void): Promise<Installation> {
67 const v = cfg.mcVersion;
68 const vdir = path.join(DIRS.cache, 'versions', v);
69 const vjsonPath = path.join(vdir, `${v}.json`);
70 let version: any;
71 if (fs.existsSync(vjsonPath)) {
72 version = JSON.parse(fs.readFileSync(vjsonPath, 'utf8'));
73 } else {
74 const manifest = await fetchJson(MANIFEST);
75 const entry = manifest.versions.find((x: any) => x.id === v);
76 if (!entry) throw new Error(`Minecraft version ${v} not in Mojang manifest`);
77 await download({ url: entry.url, dest: vjsonPath, sha1: entry.sha1 });
78 version = JSON.parse(fs.readFileSync(vjsonPath, 'utf8'));
79 }
80
81 const clientJar = path.join(vdir, `${v}.jar`);
82 await download({ url: version.downloads.client.url, dest: clientJar, sha1: version.downloads.client.sha1 });
83
84 // Fabric loader profile (26.x is unobfuscated: no intermediary needed).
85 const fabricPath = path.join(DIRS.cache, 'fabric', `${v}-${cfg.fabricLoader}.json`);
86 if (!fs.existsSync(fabricPath)) {
87 const prof = await fetchJson(`https://meta.fabricmc.net/v2/versions/loader/${v}/${cfg.fabricLoader}/profile/json`);
88 fs.mkdirSync(path.dirname(fabricPath), { recursive: true });
89 fs.writeFileSync(fabricPath, JSON.stringify(prof, null, 2));
90 }
91 const fabric = JSON.parse(fs.readFileSync(fabricPath, 'utf8'));
92
93 const libDir = path.join(DIRS.cache, 'libraries');
94 const specs: DownloadSpec[] = [];
95 const cp = new Map<string, string>();
96 for (const lib of version.libraries) {
97 if (!rulesAllow(lib.rules)) continue;
98 const a = lib.downloads?.artifact;
99 if (!a) continue;
100 const dest = path.join(libDir, a.path);
101 specs.push({ url: a.url, dest, sha1: a.sha1 });
102 cp.set(libKey(lib.name), dest);
103 }
104 for (const lib of fabric.libraries) {
105 const rel = mavenPath(lib.name);
106 const dest = path.join(libDir, rel);
107 const base = (lib.url as string).endsWith('/') ? lib.url : lib.url + '/';
108 specs.push({ url: base + rel, dest, sha1: lib.sha1 });
109 cp.set(libKey(lib.name), dest); // Fabric's versions win over vanilla duplicates (e.g. ASM)
110 }
111 log(`libraries: ${specs.length}`);
112 await downloadAll(specs, 16);
113
114 // Assets
115 const assetsDir = path.join(DIRS.cache, 'assets');
116 const ai = version.assetIndex;
117 const indexPath = path.join(assetsDir, 'indexes', `${ai.id}.json`);
118 await download({ url: ai.url, dest: indexPath, sha1: ai.sha1 });
119 const index = JSON.parse(fs.readFileSync(indexPath, 'utf8'));
120 const assetSpecs: DownloadSpec[] = Object.values<any>(index.objects).map((o) => ({
121 url: `https://resources.download.minecraft.net/${o.hash.slice(0, 2)}/${o.hash}`,
122 dest: path.join(assetsDir, 'objects', o.hash.slice(0, 2), o.hash),
123 sha1: o.hash,
124 }));
125 const missing = assetSpecs.filter((s) => !fs.existsSync(s.dest));
126 if (missing.length) {
127 log(`assets: downloading ${missing.length} objects`);
128 await downloadAll(missing, 32, (d, t) => log(`assets ${d}/${t}`));
129 }
130
131 let logConfig: string | null = null;
132 const lc = version.logging?.client?.file;
133 if (lc) {
134 logConfig = path.join(assetsDir, 'log_configs', lc.id);
135 await download({ url: lc.url, dest: logConfig, sha1: lc.sha1 });
136 }
137
138 // Mods: QA Bridge + Fabric API + user extras
139 const mods: string[] = [];
140 const bridge = expandGlob('qa-bridge/build/libs/qa-bridge-*.jar');
141 if (bridge.length === 0) throw new Error('qa-bridge jar not built: run `npm run build:mods` (or ./gradlew build in qa-bridge/)');
142 mods.push(bridge.sort().at(-1)!);
143 const fa = cfg.fabricApi;
144 const faUrl = `https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api/${encodeURIComponent(fa)}/fabric-api-${encodeURIComponent(fa)}.jar`;
145 const faSha1 = (await (await fetch(faUrl + '.sha1')).text()).trim().slice(0, 40);
146 const faDest = path.join(DIRS.cache, 'mods', `fabric-api-${fa}.jar`);
147 await download({ url: faUrl, dest: faDest, sha1: faSha1 });
148 mods.push(faDest);
149 for (const g of cfg.client.extraMods) mods.push(...expandGlob(g));
150
151 return {
152 version,
153 fabric,
154 classpath: [...cp.values(), clientJar],
155 clientJar,
156 assetsDir,
157 assetIndex: ai.id,
158 logConfig,
159 mods,
160 };
161}
162
163export interface LaunchPlan {
164 command: string;
165 args: string[];
166 cwd: string;
167 gameDir: string;
168}
169
170function writeOptions(gameDir: string, cfg: Config): void {
171 const file = path.join(gameDir, 'options.txt');
172 const existing = new Map<string, string>();
173 if (fs.existsSync(file)) {
174 for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
175 const i = line.indexOf(':');
176 if (i > 0) existing.set(line.slice(0, i), line.slice(i + 1));
177 }
178 }
179 const forced: Record<string, string> = {
180 onboardAccessibility: 'false',
181 skipMultiplayerWarning: 'true',
182 joinedFirstServer: 'true',
183 tutorialStep: 'none',
184 pauseOnLostFocus: 'false',
185 guiScale: String(cfg.client.guiScale),
186 renderDistance: '6',
187 simulationDistance: '5',
188 maxFps: '30',
189 inactivityFpsLimit: '"afk"',
190 enableVsync: 'false',
191 narrator: '0',
192 narratorHotkey: 'false',
193 realmsNotifications: 'false',
194 telemetryOptInExtra: 'false',
195 fullscreen: 'false',
196 soundCategory_master: '0.0',
197 musicToast: '"never"',
198 lang: cfg.client.lang,
199 chatLinksPrompt: 'false',
200 autoJump: 'false',
201 startedCleanly: 'true',
202 hideSplashTexts: 'true',
203 darkMojangStudiosBackground: 'true',
204 };
205 for (const [k, val] of Object.entries(forced)) existing.set(k, val);
206 fs.writeFileSync(file, [...existing].map(([k, val]) => `${k}:${val}`).join('\n') + '\n');
207}
208
209function syncMods(gameDir: string, mods: string[]): void {
210 const dir = path.join(gameDir, 'mods');
211 fs.mkdirSync(dir, { recursive: true });
212 for (const f of fs.readdirSync(dir)) if (f.endsWith('.jar')) fs.rmSync(path.join(dir, f));
213 for (const m of mods) fs.copyFileSync(m, path.join(dir, path.basename(m)));
214}
215
216export async function plan(
217 cfg: Config,
218 inst: Installation,
219 who: Identity,
220 opts: { gameDir: string; bridgePort: number; connect?: string | null },
221): Promise<LaunchPlan> {
222 const { gameDir } = opts;
223 fs.mkdirSync(gameDir, { recursive: true });
224 writeOptions(gameDir, cfg);
225 syncMods(gameDir, inst.mods);
226 const natives = path.join(gameDir, 'natives');
227 for (const sub of ['java', 'jna', 'lwjgl', 'netty']) fs.mkdirSync(path.join(natives, sub), { recursive: true });
228
229 const features: Record<string, boolean> = {
230 has_custom_resolution: true,
231 is_quick_play_multiplayer: !!opts.connect,
232 };
233 const vars: Record<string, string> = {
234 natives_directory: natives,
235 launcher_name: 'mc-tester',
236 launcher_version: '0.1.0',
237 classpath: inst.classpath.join(path.delimiter),
238 classpath_separator: path.delimiter,
239 library_directory: path.join(DIRS.cache, 'libraries'),
240 auth_player_name: who.name,
241 version_name: cfg.mcVersion,
242 game_directory: gameDir,
243 assets_root: inst.assetsDir,
244 assets_index_name: inst.assetIndex,
245 auth_uuid: who.uuid,
246 auth_access_token: who.accessToken,
247 clientid: '0',
248 auth_xuid: who.xuid,
249 user_type: who.userType,
250 version_type: 'release',
251 resolution_width: String(cfg.client.width),
252 resolution_height: String(cfg.client.height),
253 quickPlayMultiplayer: opts.connect ?? '',
254 };
255 const sub = (s: string) => s.replace(/\$\{([^}]+)\}/g, (_, k) => vars[k] ?? '');
256 const expand = (list: any[]): string[] => {
257 const out: string[] = [];
258 for (const a of list) {
259 if (typeof a === 'string') out.push(sub(a));
260 else if (rulesAllow(a.rules, features)) out.push(...(Array.isArray(a.value) ? a.value : [a.value]).map(sub));
261 }
262 return out;
263 };
264
265 const jvm = [
266 `-Xms1G`,
267 `-Xmx${cfg.client.memory}`,
268 '-XX:+UseZGC',
269 ...expand(inst.version.arguments.jvm),
270 ...(inst.fabric.arguments?.jvm ?? []),
271 `-Dqabridge.port=${opts.bridgePort}`,
272 `-Dqabridge.hideToasts=${cfg.client.hideToasts}`,
273 `-Dqabridge.acceptServerPacks=${cfg.client.acceptServerResourcePacks}`,
274 ];
275 if (inst.logConfig) jvm.push(sub(inst.version.logging.client.argument.replace('${path}', inst.logConfig)));
276 // quickPlayPath is feature-gated; we never enable it.
277 const game = expand(inst.version.arguments.game).filter((a) => a !== '--quickPlayPath');
278 const args = [...jvm, inst.fabric.mainClass, ...game];
279 return { command: 'java', args, cwd: gameDir, gameDir };
280}
281
282export function redactArgs(args: string[]): string[] {
283 const out = [...args];
284 const i = out.indexOf('--accessToken');
285 if (i >= 0 && i + 1 < out.length) out[i + 1] = '<redacted>';
286 return out;
287}
288
289export { ROOT };