leejunyoung5819 mc-paper-plugin-test-mcp-26.3
공개마인크래프트 26.3 Paper 서버의 플러그인 테스트를 하려는 AI 에이전트를 위한 MCP 도구
| 1 | // Paper test server: download, configure, start/stop, logs, RCON, world snapshots. |
| 2 | import fs from 'node:fs'; |
| 3 | import path from 'node:path'; |
| 4 | import { spawn, type ChildProcess } from 'node:child_process'; |
| 5 | import { DIRS, secrets, type Config } from './config.ts'; |
| 6 | import { resolvePlugins } from './plugins.ts'; |
| 7 | import { download, fetchJson } from './download.ts'; |
| 8 | import { Rcon } from './rcon.ts'; |
| 9 | |
| 10 | export interface LogLine { |
| 11 | seq: number; |
| 12 | time: number; |
| 13 | text: string; |
| 14 | } |
| 15 | |
| 16 | const ERROR_RE = /(\bERROR\]|Exception|Caused by:|\bat [\w.$]+\([\w.]+:\d+\))/; |
| 17 | |
| 18 | export class PaperServer { |
| 19 | private cfg: Config; |
| 20 | private proc: ChildProcess | null = null; |
| 21 | private rcon: Rcon | null = null; |
| 22 | private lines: LogLine[] = []; |
| 23 | private seq = 0; |
| 24 | private ready = false; |
| 25 | private exitInfo: string | null = null; |
| 26 | |
| 27 | constructor(cfg: Config) { |
| 28 | this.cfg = cfg; |
| 29 | } |
| 30 | |
| 31 | get dir(): string { |
| 32 | return DIRS.server; |
| 33 | } |
| 34 | |
| 35 | /** Live config shared with the daemon (plugins_set edits server.plugins in place). */ |
| 36 | get config(): Config { |
| 37 | return this.cfg; |
| 38 | } |
| 39 | |
| 40 | get running(): boolean { |
| 41 | return this.proc !== null && this.proc.exitCode === null; |
| 42 | } |
| 43 | |
| 44 | status() { |
| 45 | return { |
| 46 | running: this.running, |
| 47 | ready: this.ready, |
| 48 | pid: this.proc?.pid ?? null, |
| 49 | address: `127.0.0.1:${this.cfg.server.port}`, |
| 50 | onlineMode: this.cfg.server.onlineMode, |
| 51 | logSeq: this.seq, |
| 52 | lastExit: this.exitInfo, |
| 53 | plugins: this.installedPlugins(), |
| 54 | }; |
| 55 | } |
| 56 | |
| 57 | private installedPlugins(): string[] { |
| 58 | const p = path.join(this.dir, 'plugins'); |
| 59 | if (!fs.existsSync(p)) return []; |
| 60 | return fs.readdirSync(p).filter((f) => f.endsWith('.jar')); |
| 61 | } |
| 62 | |
| 63 | async ensureJar(): Promise<string> { |
| 64 | const v = this.cfg.mcVersion; |
| 65 | const builds = await fetchJson<any[]>(`https://fill.papermc.io/v3/projects/paper/versions/${v}/builds`); |
| 66 | const want = this.cfg.server.paperBuild; |
| 67 | const build = want === 'latest' ? builds.find((b) => b.channel === 'STABLE') ?? builds[0] : builds.find((b) => b.id === want); |
| 68 | if (!build) throw new Error(`Paper build ${want} for ${v} not found`); |
| 69 | const dl = build.downloads['server:default']; |
| 70 | const dest = path.join(DIRS.cache, 'paper', dl.name); |
| 71 | await download({ url: dl.url, dest, sha256: dl.checksums?.sha256 }); |
| 72 | return dest; |
| 73 | } |
| 74 | |
| 75 | private writeConfig(): void { |
| 76 | const s = this.cfg.server; |
| 77 | fs.mkdirSync(this.dir, { recursive: true }); |
| 78 | // The user accepted the Minecraft EULA (https://aka.ms/MinecraftEULA) when setting up this harness. |
| 79 | fs.writeFileSync(path.join(this.dir, 'eula.txt'), 'eula=true\n'); |
| 80 | const propsFile = path.join(this.dir, 'server.properties'); |
| 81 | const props: Record<string, string> = {}; |
| 82 | if (fs.existsSync(propsFile)) { |
| 83 | for (const line of fs.readFileSync(propsFile, 'utf8').split('\n')) { |
| 84 | const m = line.match(/^([^#=]+)=(.*)$/); |
| 85 | if (m) props[m[1].trim()] = m[2]; |
| 86 | } |
| 87 | } |
| 88 | const forced: Record<string, string | number | boolean> = { |
| 89 | 'server-ip': '127.0.0.1', |
| 90 | 'server-port': s.port, |
| 91 | 'online-mode': s.onlineMode, |
| 92 | 'enforce-secure-profile': s.onlineMode, |
| 93 | 'enable-rcon': true, |
| 94 | 'rcon.port': s.rconPort, |
| 95 | 'rcon.password': secrets().rconPassword, |
| 96 | 'broadcast-rcon-to-ops': false, |
| 97 | 'level-seed': 'mc-tester', |
| 98 | 'level-type': 'minecraft\\:flat', |
| 99 | 'generator-settings': JSON.stringify({ |
| 100 | layers: [ |
| 101 | { block: 'minecraft:bedrock', height: 1 }, |
| 102 | { block: 'minecraft:dirt', height: 2 }, |
| 103 | { block: 'minecraft:grass_block', height: 1 }, |
| 104 | ], |
| 105 | biome: 'minecraft:plains', |
| 106 | }).replace(/:/g, '\\:'), |
| 107 | 'spawn-protection': 0, |
| 108 | 'view-distance': 6, |
| 109 | 'simulation-distance': 6, |
| 110 | 'allow-flight': true, |
| 111 | 'difficulty': 'peaceful', |
| 112 | 'gamemode': 'survival', |
| 113 | 'motd': 'mc-tester QA server', |
| 114 | 'max-players': 50, |
| 115 | 'white-list': false, |
| 116 | 'enforce-whitelist': false, |
| 117 | 'sync-chunk-writes': false, |
| 118 | ...s.properties, |
| 119 | }; |
| 120 | // Drop keys that came from a previous `server.properties` override but are no longer configured, |
| 121 | // so removing an override really reverts it (Paper re-adds the default on start). |
| 122 | const overridesFile = path.join(this.dir, '.mct-properties.json'); |
| 123 | const previousOverrides: string[] = fs.existsSync(overridesFile) ? JSON.parse(fs.readFileSync(overridesFile, 'utf8')) : []; |
| 124 | for (const k of previousOverrides) if (!(k in s.properties)) delete props[k]; |
| 125 | fs.writeFileSync(overridesFile, JSON.stringify(Object.keys(s.properties))); |
| 126 | for (const [k, v] of Object.entries(forced)) props[k] = String(v); |
| 127 | fs.writeFileSync(propsFile, Object.entries(props).map(([k, v]) => `${k}=${v}`).join('\n') + '\n'); |
| 128 | } |
| 129 | |
| 130 | /** Copy the resolved plugin jars (one per plugin, newest build) into plugins/, removing what we copied last time. */ |
| 131 | private syncPlugins(): { copied: string[]; skipped: { file: string; reason: string }[] } { |
| 132 | const res = resolvePlugins(this.cfg.server.plugins); |
| 133 | if (res.unmatched.length) { |
| 134 | throw new Error(`plugin pattern(s) matched no jar: ${res.unmatched.join(', ')} (build the plugin first, or fix the path with plugins_set)`); |
| 135 | } |
| 136 | const pdir = path.join(this.dir, 'plugins'); |
| 137 | fs.mkdirSync(pdir, { recursive: true }); |
| 138 | const manifest = path.join(this.dir, '.mct-plugins.json'); |
| 139 | const previous: string[] = fs.existsSync(manifest) ? JSON.parse(fs.readFileSync(manifest, 'utf8')) : []; |
| 140 | for (const f of previous) fs.rmSync(path.join(pdir, f), { force: true }); |
| 141 | const copied: string[] = []; |
| 142 | for (const j of res.selected) { |
| 143 | const name = path.basename(j.file); |
| 144 | fs.copyFileSync(j.file, path.join(pdir, name)); |
| 145 | copied.push(name); |
| 146 | } |
| 147 | fs.writeFileSync(manifest, JSON.stringify(copied)); |
| 148 | return { copied, skipped: res.skipped.map((j) => ({ file: j.file, reason: j.reason })) }; |
| 149 | } |
| 150 | |
| 151 | private push(text: string): void { |
| 152 | this.lines.push({ seq: ++this.seq, time: Date.now(), text }); |
| 153 | if (this.lines.length > 20000) this.lines.splice(0, this.lines.length - 20000); |
| 154 | } |
| 155 | |
| 156 | async start(timeoutMs = 180_000): Promise<object> { |
| 157 | if (this.running) return { alreadyRunning: true, ...this.status() }; |
| 158 | const jar = await this.ensureJar(); |
| 159 | this.writeConfig(); |
| 160 | const plugins = this.syncPlugins(); |
| 161 | this.ready = false; |
| 162 | this.exitInfo = null; |
| 163 | const mem = this.cfg.server.memory; |
| 164 | const proc = spawn('java', [`-Xms${mem}`, `-Xmx${mem}`, '-Dterminal.jline=false', '-Dterminal.ansi=false', '-jar', jar, '--nogui'], { |
| 165 | cwd: this.dir, |
| 166 | stdio: ['pipe', 'pipe', 'pipe'], |
| 167 | env: { ...process.env, TERM: 'dumb' }, |
| 168 | }); |
| 169 | this.proc = proc; |
| 170 | const startSeq = this.seq; |
| 171 | let partial = ''; |
| 172 | const onChunk = (d: Buffer) => { |
| 173 | partial += d.toString('utf8'); |
| 174 | const parts = partial.split('\n'); |
| 175 | partial = parts.pop() ?? ''; |
| 176 | for (const raw of parts) { |
| 177 | // Strip ANSI and the console prompt redraw ("> \r \r") that JLine interleaves. |
| 178 | const line = (raw.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').split('\r').filter((x) => x.trim()).pop() ?? '').replace(/^> /, ''); |
| 179 | this.push(line); |
| 180 | if (/Done \([\d.,]+s\)! For help/.test(line)) this.ready = true; |
| 181 | } |
| 182 | }; |
| 183 | proc.stdout!.on('data', onChunk); |
| 184 | proc.stderr!.on('data', onChunk); |
| 185 | proc.on('exit', (code, sig) => { |
| 186 | this.exitInfo = `exited code=${code} signal=${sig}`; |
| 187 | this.push(`[mc-tester] server ${this.exitInfo}`); |
| 188 | this.ready = false; |
| 189 | this.rcon?.close(); |
| 190 | this.rcon = null; |
| 191 | }); |
| 192 | const t0 = Date.now(); |
| 193 | while (!this.ready) { |
| 194 | if (!this.running) throw new Error(`server exited during startup (${this.exitInfo}). Last log:\n${this.tail(40, startSeq)}`); |
| 195 | if (Date.now() - t0 > timeoutMs) throw new Error(`server not ready after ${timeoutMs}ms. Last log:\n${this.tail(40, startSeq)}`); |
| 196 | await sleep(250); |
| 197 | } |
| 198 | const onStart: Record<string, string> = {}; |
| 199 | for (const c of this.cfg.server.onStart) onStart[c] = await this.command(c); |
| 200 | return { ...this.status(), started: true, seconds: (Date.now() - t0) / 1000, copiedPlugins: plugins.copied, skippedJars: plugins.skipped, onStart }; |
| 201 | } |
| 202 | |
| 203 | async stop(timeoutMs = 60_000): Promise<object> { |
| 204 | if (!this.running) return { running: false }; |
| 205 | const proc = this.proc!; |
| 206 | try { |
| 207 | await this.command('stop', 5000); |
| 208 | } catch { |
| 209 | proc.stdin?.write('stop\n'); |
| 210 | } |
| 211 | const t0 = Date.now(); |
| 212 | while (proc.exitCode === null && Date.now() - t0 < timeoutMs) await sleep(200); |
| 213 | if (proc.exitCode === null) proc.kill('SIGKILL'); |
| 214 | return { stopped: true, seconds: (Date.now() - t0) / 1000 }; |
| 215 | } |
| 216 | |
| 217 | async command(cmd: string, timeoutMs = 15_000): Promise<string> { |
| 218 | if (!this.running) throw new Error('server is not running (call server_start)'); |
| 219 | const c = cmd.replace(/^\//, ''); |
| 220 | for (let attempt = 1; ; attempt++) { |
| 221 | if (!this.rcon || !this.rcon.connected) { |
| 222 | this.rcon = new Rcon('127.0.0.1', this.cfg.server.rconPort, secrets().rconPassword); |
| 223 | } |
| 224 | try { |
| 225 | return await this.rcon.command(c, timeoutMs); |
| 226 | } catch (e) { |
| 227 | // The server drops idle RCON sockets; reconnect once and retry. |
| 228 | const msg = (e as Error).message; |
| 229 | if (attempt >= 2 || !/closed|ECONNRESET|EPIPE|ECONNREFUSED/.test(msg) || !this.running) throw e; |
| 230 | this.rcon?.close(); |
| 231 | this.rcon = null; |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | log(since = 0, grep?: string, limit = 200): { next: number; lines: LogLine[] } { |
| 237 | let out = this.lines.filter((l) => l.seq > since); |
| 238 | if (grep) { |
| 239 | const re = new RegExp(grep, 'i'); |
| 240 | out = out.filter((l) => re.test(l.text)); |
| 241 | } |
| 242 | return { next: this.seq, lines: out.slice(-limit) }; |
| 243 | } |
| 244 | |
| 245 | errors(since: number): LogLine[] { |
| 246 | return this.lines.filter((l) => l.seq > since && ERROR_RE.test(l.text)); |
| 247 | } |
| 248 | |
| 249 | get logSeq(): number { |
| 250 | return this.seq; |
| 251 | } |
| 252 | |
| 253 | tail(n: number, since = 0): string { |
| 254 | return this.lines.filter((l) => l.seq > since).slice(-n).map((l) => l.text).join('\n'); |
| 255 | } |
| 256 | |
| 257 | // ---------------------------------------------------------------- snapshots |
| 258 | |
| 259 | private snapshotEntries(): string[] { |
| 260 | const out: string[] = []; |
| 261 | for (const inc of this.cfg.server.snapshotInclude) { |
| 262 | if (inc.endsWith('/*')) { |
| 263 | const base = inc.slice(0, -2); |
| 264 | const abs = path.join(this.dir, base); |
| 265 | if (!fs.existsSync(abs)) continue; |
| 266 | for (const e of fs.readdirSync(abs, { withFileTypes: true })) if (e.isDirectory()) out.push(path.join(base, e.name)); |
| 267 | } else if (fs.existsSync(path.join(this.dir, inc))) { |
| 268 | out.push(inc); |
| 269 | } |
| 270 | } |
| 271 | return out; |
| 272 | } |
| 273 | |
| 274 | async snapshot(name: string): Promise<object> { |
| 275 | if (!/^[\w.-]+$/.test(name)) throw new Error('snapshot name must be [A-Za-z0-9_.-]'); |
| 276 | const wasRunning = this.running; |
| 277 | if (wasRunning) { |
| 278 | await this.command('save-off'); |
| 279 | await this.command('save-all flush', 60_000); |
| 280 | } |
| 281 | try { |
| 282 | const dest = path.join(DIRS.snapshots, name); |
| 283 | fs.rmSync(dest, { recursive: true, force: true }); |
| 284 | const entries = this.snapshotEntries(); |
| 285 | for (const e of entries) { |
| 286 | fs.cpSync(path.join(this.dir, e), path.join(dest, e), { recursive: true, filter: (src) => !src.endsWith('session.lock') }); |
| 287 | } |
| 288 | fs.writeFileSync(path.join(dest, '.mct-snapshot.json'), JSON.stringify({ entries, created: new Date().toISOString() })); |
| 289 | return { snapshot: name, entries }; |
| 290 | } finally { |
| 291 | if (wasRunning) await this.command('save-on'); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | listSnapshots(): string[] { |
| 296 | if (!fs.existsSync(DIRS.snapshots)) return []; |
| 297 | return fs.readdirSync(DIRS.snapshots).filter((d) => fs.existsSync(path.join(DIRS.snapshots, d, '.mct-snapshot.json'))); |
| 298 | } |
| 299 | |
| 300 | /** Stop -> replace snapshot paths -> start. Caller reconnects clients. */ |
| 301 | async restore(name: string): Promise<object> { |
| 302 | const src = path.join(DIRS.snapshots, name); |
| 303 | const metaFile = path.join(src, '.mct-snapshot.json'); |
| 304 | if (!fs.existsSync(metaFile)) throw new Error(`no snapshot '${name}'. Existing: ${this.listSnapshots().join(', ') || '(none)'}`); |
| 305 | const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8')) as { entries: string[] }; |
| 306 | const wasRunning = this.running; |
| 307 | if (wasRunning) await this.stop(); |
| 308 | for (const e of this.snapshotEntries()) fs.rmSync(path.join(this.dir, e), { recursive: true, force: true }); |
| 309 | for (const e of meta.entries) fs.cpSync(path.join(src, e), path.join(this.dir, e), { recursive: true }); |
| 310 | const started = wasRunning ? await this.start() : null; |
| 311 | return { restored: name, entries: meta.entries, restarted: wasRunning, started }; |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | export function sleep(ms: number): Promise<void> { |
| 316 | return new Promise((r) => setTimeout(r, ms)); |
| 317 | } |