leejunyoung5819 mc-paper-plugin-test-mcp-26.3
공개마인크래프트 26.3 Paper 서버의 플러그인 테스트를 하려는 AI 에이전트를 위한 MCP 도구
| 1 | // Launches and talks to real Minecraft clients (each with the QA Bridge mod on its own localhost port). |
| 2 | import fs from 'node:fs'; |
| 3 | import path from 'node:path'; |
| 4 | import net from 'node:net'; |
| 5 | import { spawn, type ChildProcess } from 'node:child_process'; |
| 6 | import { DIRS, type Config } from './config.ts'; |
| 7 | import { install, plan, redactArgs } from './launcher.ts'; |
| 8 | import { hasMicrosoftCache, microsoftIdentity, offlineIdentity, type Identity } from './auth.ts'; |
| 9 | import { sleep } from './paper.ts'; |
| 10 | |
| 11 | export interface LaunchOptions { |
| 12 | account?: 'offline' | 'microsoft'; |
| 13 | /** Microsoft token cache profile (see `mct login`). */ |
| 14 | msProfile?: string; |
| 15 | /** Server to join on startup; true/undefined = the harness server, false = stay on title screen. */ |
| 16 | connect?: boolean | string; |
| 17 | display?: 'xvfb' | 'host'; |
| 18 | timeoutMs?: number; |
| 19 | } |
| 20 | |
| 21 | interface ClientProc { |
| 22 | key: string; |
| 23 | name: string; |
| 24 | account: 'offline' | 'microsoft'; |
| 25 | port: number; |
| 26 | proc: ChildProcess; |
| 27 | xvfb: ChildProcess | null; |
| 28 | display: string; |
| 29 | gameDir: string; |
| 30 | startedAt: number; |
| 31 | tail: string[]; |
| 32 | exit: string | null; |
| 33 | } |
| 34 | |
| 35 | export class BridgeError extends Error { |
| 36 | status: number; |
| 37 | constructor(message: string, status: number) { |
| 38 | super(message); |
| 39 | this.status = status; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | function portFree(port: number): Promise<boolean> { |
| 44 | return new Promise((resolve) => { |
| 45 | const s = net.createServer(); |
| 46 | s.once('error', () => resolve(false)); |
| 47 | s.listen(port, '127.0.0.1', () => s.close(() => resolve(true))); |
| 48 | }); |
| 49 | } |
| 50 | |
| 51 | export class ClientManager { |
| 52 | private cfg: Config; |
| 53 | private clients = new Map<string, ClientProc>(); |
| 54 | private serverAddress: () => string; |
| 55 | log: (m: string) => void; |
| 56 | |
| 57 | constructor(cfg: Config, serverAddress: () => string, log: (m: string) => void = () => {}) { |
| 58 | this.cfg = cfg; |
| 59 | this.serverAddress = serverAddress; |
| 60 | this.log = log; |
| 61 | } |
| 62 | |
| 63 | list() { |
| 64 | return [...this.clients.values()].map((c) => ({ |
| 65 | name: c.name, |
| 66 | account: c.account, |
| 67 | bridgePort: c.port, |
| 68 | display: c.display, |
| 69 | pid: c.proc.pid, |
| 70 | running: c.proc.exitCode === null, |
| 71 | exit: c.exit, |
| 72 | uptimeSec: Math.round((Date.now() - c.startedAt) / 1000), |
| 73 | })); |
| 74 | } |
| 75 | |
| 76 | /** Resolve a client by name; if omitted and exactly one client runs, use it. */ |
| 77 | get(name?: string): ClientProc { |
| 78 | if (!name) { |
| 79 | const running = [...this.clients.values()].filter((c) => c.proc.exitCode === null); |
| 80 | if (running.length === 1) return running[0]; |
| 81 | if (running.length === 0) throw new Error('no client is running (call client_launch first)'); |
| 82 | throw new Error(`several clients are running (${running.map((c) => c.name).join(', ')}); pass client`); |
| 83 | } |
| 84 | const c = this.clients.get(name.toLowerCase()); |
| 85 | if (!c) throw new Error(`no client named '${name}'. Running: ${this.list().map((x) => x.name).join(', ') || '(none)'}`); |
| 86 | if (c.proc.exitCode !== null) throw new Error(`client '${name}' has exited (${c.exit}). Last output:\n${c.tail.slice(-30).join('\n')}`); |
| 87 | return c; |
| 88 | } |
| 89 | |
| 90 | async call(name: string | undefined, route: string, body: object = {}, timeoutMs = 30_000): Promise<any> { |
| 91 | const c = this.get(name); |
| 92 | return this.callPort(c.port, route, body, timeoutMs); |
| 93 | } |
| 94 | |
| 95 | private async callPort(port: number, route: string, body: object, timeoutMs: number): Promise<any> { |
| 96 | const res = await fetch(`http://127.0.0.1:${port}/${route.replace(/^\//, '')}`, { |
| 97 | method: 'POST', |
| 98 | headers: { 'Content-Type': 'application/json' }, |
| 99 | body: JSON.stringify(body), |
| 100 | signal: AbortSignal.timeout(timeoutMs), |
| 101 | }); |
| 102 | const json: any = await res.json(); |
| 103 | if (!json.ok) throw new BridgeError(json.error ?? `bridge ${route} failed`, res.status); |
| 104 | delete json.ok; |
| 105 | return json; |
| 106 | } |
| 107 | |
| 108 | private async nextPort(): Promise<number> { |
| 109 | const used = new Set([...this.clients.values()].filter((c) => c.proc.exitCode === null).map((c) => c.port)); |
| 110 | for (let p = this.cfg.client.bridgeBasePort; p < this.cfg.client.bridgeBasePort + 100; p++) { |
| 111 | if (!used.has(p) && (await portFree(p))) return p; |
| 112 | } |
| 113 | throw new Error('no free bridge port'); |
| 114 | } |
| 115 | |
| 116 | private async startXvfb(): Promise<{ proc: ChildProcess; display: string }> { |
| 117 | const { width, height } = this.cfg.client; |
| 118 | for (let n = 140; n < 240; n++) { |
| 119 | if (fs.existsSync(`/tmp/.X11-unix/X${n}`) || fs.existsSync(`/tmp/.X${n}-lock`)) continue; |
| 120 | const proc = spawn('Xvfb', [`:${n}`, '-screen', '0', `${width}x${height}x24`, '-nolisten', 'tcp', '-noreset', '+extension', 'GLX'], { |
| 121 | stdio: 'ignore', |
| 122 | }); |
| 123 | const t0 = Date.now(); |
| 124 | while (Date.now() - t0 < 5000) { |
| 125 | if (fs.existsSync(`/tmp/.X11-unix/X${n}`)) return { proc, display: `:${n}` }; |
| 126 | if (proc.exitCode !== null) break; |
| 127 | await sleep(100); |
| 128 | } |
| 129 | proc.kill(); |
| 130 | } |
| 131 | throw new Error('could not start Xvfb (is it installed? `sudo apt install xvfb`)'); |
| 132 | } |
| 133 | |
| 134 | async launch(name: string, opts: LaunchOptions = {}): Promise<object> { |
| 135 | const key = name.toLowerCase(); |
| 136 | const existing = this.clients.get(key); |
| 137 | if (existing && existing.proc.exitCode === null) return { alreadyRunning: true, ...(await this.call(name, 'state')) }; |
| 138 | |
| 139 | const account = opts.account ?? 'offline'; |
| 140 | let who: Identity; |
| 141 | if (account === 'microsoft') { |
| 142 | const profile = opts.msProfile ?? 'default'; |
| 143 | if (!hasMicrosoftCache(profile)) { |
| 144 | throw new Error(`Microsoft account not logged in for profile '${profile}'. A human must run: npm run mct -- login ${profile}`); |
| 145 | } |
| 146 | who = await microsoftIdentity(profile, undefined, false); |
| 147 | } else { |
| 148 | if (this.cfg.server.onlineMode && opts.connect !== false && typeof opts.connect !== 'string') { |
| 149 | throw new Error('server is online-mode: offline test players cannot join. Use account "microsoft" or set server.onlineMode=false'); |
| 150 | } |
| 151 | who = offlineIdentity(name); |
| 152 | } |
| 153 | |
| 154 | this.log(`client ${who.name}: preparing install`); |
| 155 | const inst = await install(this.cfg, this.log); |
| 156 | const port = await this.nextPort(); |
| 157 | const gameDir = path.join(DIRS.clients, who.name); |
| 158 | const connect = opts.connect === false ? null : typeof opts.connect === 'string' ? opts.connect : this.serverAddress(); |
| 159 | const lp = await plan(this.cfg, inst, who, { gameDir, bridgePort: port, connect }); |
| 160 | |
| 161 | const displayMode = opts.display ?? this.cfg.client.display; |
| 162 | let xvfb: ChildProcess | null = null; |
| 163 | const env: NodeJS.ProcessEnv = { ...process.env, QA_BRIDGE_PORT: String(port) }; |
| 164 | let display = 'host'; |
| 165 | if (displayMode === 'xvfb') { |
| 166 | const x = await this.startXvfb(); |
| 167 | xvfb = x.proc; |
| 168 | display = x.display; |
| 169 | env.DISPLAY = x.display; |
| 170 | delete env.WAYLAND_DISPLAY; |
| 171 | env.SDL_VIDEODRIVER = 'x11'; |
| 172 | env.__GLX_VENDOR_LIBRARY_NAME = 'mesa'; |
| 173 | env.LIBGL_ALWAYS_SOFTWARE = '1'; |
| 174 | } |
| 175 | |
| 176 | const outFile = path.join(gameDir, 'mct-client.log'); |
| 177 | fs.writeFileSync(outFile, `# ${new Date().toISOString()} java ${redactArgs(lp.args).join(' ')}\n`); |
| 178 | const proc = spawn(lp.command, lp.args, { cwd: lp.cwd, env, stdio: ['ignore', 'pipe', 'pipe'] }); |
| 179 | const c: ClientProc = { |
| 180 | key, |
| 181 | name: who.name, |
| 182 | account, |
| 183 | port, |
| 184 | proc, |
| 185 | xvfb, |
| 186 | display, |
| 187 | gameDir, |
| 188 | startedAt: Date.now(), |
| 189 | tail: [], |
| 190 | exit: null, |
| 191 | }; |
| 192 | this.clients.set(key, c); |
| 193 | const out = fs.createWriteStream(outFile, { flags: 'a' }); |
| 194 | const onData = (d: Buffer) => { |
| 195 | out.write(d); |
| 196 | for (const line of d.toString('utf8').split('\n')) if (line.trim()) c.tail.push(line); |
| 197 | if (c.tail.length > 400) c.tail.splice(0, c.tail.length - 400); |
| 198 | }; |
| 199 | proc.stdout!.on('data', onData); |
| 200 | proc.stderr!.on('data', onData); |
| 201 | proc.on('exit', (code, sig) => { |
| 202 | c.exit = `code=${code} signal=${sig}`; |
| 203 | out.end(); |
| 204 | xvfb?.kill(); |
| 205 | }); |
| 206 | |
| 207 | const timeout = opts.timeoutMs ?? 240_000; |
| 208 | const t0 = Date.now(); |
| 209 | this.log(`client ${who.name}: starting (bridge :${port}, display ${display})`); |
| 210 | // 1) wait for the bridge HTTP server (mod initialised) |
| 211 | for (;;) { |
| 212 | if (proc.exitCode !== null) throw new Error(`client exited during startup (${c.exit}). Log: ${outFile}\n${c.tail.slice(-40).join('\n')}`); |
| 213 | if (Date.now() - t0 > timeout) throw new Error(`client bridge not up after ${timeout}ms. Log: ${outFile}`); |
| 214 | try { |
| 215 | await this.callPort(port, 'health', {}, 2000); |
| 216 | break; |
| 217 | } catch { |
| 218 | await sleep(500); |
| 219 | } |
| 220 | } |
| 221 | // 2) optionally wait until we are in the world |
| 222 | let state: any = await this.callPort(port, 'state', {}, 10_000); |
| 223 | if (connect) { |
| 224 | for (;;) { |
| 225 | if (proc.exitCode !== null) throw new Error(`client exited while connecting (${c.exit}). Log: ${outFile}`); |
| 226 | state = await this.callPort(port, 'state', {}, 10_000); |
| 227 | if (state.inWorld && !state.screen?.open) break; |
| 228 | if (state.inWorld && state.screen?.class && !/Loading|Receiving|Connect/i.test(state.screen.class)) break; |
| 229 | if (state.screen?.class === 'DisconnectedScreen') { |
| 230 | const scr = await this.callPort(port, 'screen', {}, 10_000); |
| 231 | throw new Error(`client was disconnected while joining ${connect}: ${JSON.stringify(scr.widgets?.map((w: any) => w.label))}`); |
| 232 | } |
| 233 | if (Date.now() - t0 > timeout) throw new Error(`client not in world after ${timeout}ms (screen: ${state.screen?.class})`); |
| 234 | await sleep(500); |
| 235 | } |
| 236 | } |
| 237 | return { launched: who.name, account, bridgePort: port, display, seconds: (Date.now() - t0) / 1000, connectedTo: connect, state }; |
| 238 | } |
| 239 | |
| 240 | async stop(name: string | undefined): Promise<object> { |
| 241 | const c = this.get(name); |
| 242 | try { |
| 243 | await this.callPort(c.port, 'quit', {}, 3000); |
| 244 | } catch { |
| 245 | /* ignore */ |
| 246 | } |
| 247 | const t0 = Date.now(); |
| 248 | while (c.proc.exitCode === null && Date.now() - t0 < 20_000) await sleep(200); |
| 249 | if (c.proc.exitCode === null) c.proc.kill('SIGKILL'); |
| 250 | c.xvfb?.kill(); |
| 251 | this.clients.delete(c.key); |
| 252 | return { stopped: c.name }; |
| 253 | } |
| 254 | |
| 255 | async stopAll(): Promise<void> { |
| 256 | for (const c of [...this.clients.values()]) { |
| 257 | if (c.proc.exitCode === null) await this.stop(c.name).catch(() => c.proc.kill('SIGKILL')); |
| 258 | c.xvfb?.kill(); |
| 259 | } |
| 260 | this.clients.clear(); |
| 261 | } |
| 262 | |
| 263 | running(): string[] { |
| 264 | return [...this.clients.values()].filter((c) => c.proc.exitCode === null).map((c) => c.name); |
| 265 | } |
| 266 | |
| 267 | artifactsDir(): string { |
| 268 | return DIRS.artifacts; |
| 269 | } |
| 270 | } |