leejunyoung5819 mc-paper-plugin-test-mcp-26.3
공개마인크래프트 26.3 Paper 서버의 플러그인 테스트를 하려는 AI 에이전트를 위한 MCP 도구
| 1 | // Long-lived harness daemon: owns the Paper server and all clients so several agents / MCP sessions |
| 2 | // can share them. JSON RPC over http://127.0.0.1:<daemonPort>. |
| 3 | import http from 'node:http'; |
| 4 | import fs from 'node:fs'; |
| 5 | import path from 'node:path'; |
| 6 | import { z } from 'zod'; |
| 7 | import { DIRS, ensureDirs, loadConfig } from './config.ts'; |
| 8 | import { PaperServer } from './paper.ts'; |
| 9 | import { ClientManager } from './clients.ts'; |
| 10 | import { TOOLS, TOOL_MAP, type Ctx } from './tools.ts'; |
| 11 | import { runScenario } from './scenario.ts'; |
| 12 | |
| 13 | ensureDirs(); |
| 14 | const cfg = loadConfig(); |
| 15 | const logFile = fs.createWriteStream(path.join(DIRS.run, 'daemon.log'), { flags: 'a' }); |
| 16 | const log = (m: string) => { |
| 17 | const line = `${new Date().toISOString()} ${m}\n`; |
| 18 | logFile.write(line); |
| 19 | process.stderr.write(line); |
| 20 | }; |
| 21 | |
| 22 | const server = new PaperServer(cfg); |
| 23 | const clients = new ClientManager(cfg, () => server.status().address, log); |
| 24 | const ctx: Ctx = { |
| 25 | server, |
| 26 | clients, |
| 27 | marks: new Map(), |
| 28 | runScenario: (file, opts) => runScenario(ctx, file, opts), |
| 29 | }; |
| 30 | |
| 31 | function readBody(req: http.IncomingMessage): Promise<string> { |
| 32 | return new Promise((resolve, reject) => { |
| 33 | const chunks: Buffer[] = []; |
| 34 | req.on('data', (c) => chunks.push(c)); |
| 35 | req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); |
| 36 | req.on('error', reject); |
| 37 | }); |
| 38 | } |
| 39 | |
| 40 | function send(res: http.ServerResponse, status: number, body: unknown) { |
| 41 | const s = JSON.stringify(body); |
| 42 | res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); |
| 43 | res.end(s); |
| 44 | } |
| 45 | |
| 46 | let shuttingDown = false; |
| 47 | async function shutdown(code = 0) { |
| 48 | if (shuttingDown) return; |
| 49 | shuttingDown = true; |
| 50 | log('shutting down: stopping clients and server'); |
| 51 | httpServer.close(); // stop accepting new requests right away |
| 52 | await clients.stopAll().catch((e) => log(`stopAll: ${e}`)); |
| 53 | await server.stop().catch((e) => log(`server stop: ${e}`)); |
| 54 | fs.rmSync(path.join(DIRS.run, 'daemon.json'), { force: true }); |
| 55 | process.exit(code); |
| 56 | } |
| 57 | |
| 58 | const httpServer = http.createServer(async (req, res) => { |
| 59 | try { |
| 60 | const url = new URL(req.url ?? '/', 'http://localhost'); |
| 61 | if (shuttingDown) return send(res, 503, { ok: false, error: 'daemon is shutting down' }); |
| 62 | if (url.pathname === '/health') return send(res, 200, { ok: true, pid: process.pid }); |
| 63 | if (url.pathname === '/tools') return send(res, 200, { ok: true, tools: TOOLS.map((t) => ({ name: t.name, description: t.description })) }); |
| 64 | if (url.pathname === '/shutdown' && req.method === 'POST') { |
| 65 | send(res, 200, { ok: true }); |
| 66 | setTimeout(() => void shutdown(0), 50); |
| 67 | return; |
| 68 | } |
| 69 | if (url.pathname !== '/rpc' || req.method !== 'POST') return send(res, 404, { ok: false, error: 'POST /rpc {tool, params}' }); |
| 70 | const { tool, params } = JSON.parse((await readBody(req)) || '{}'); |
| 71 | const t = TOOL_MAP.get(tool); |
| 72 | if (!t) return send(res, 400, { ok: false, error: `unknown tool '${tool}'` }); |
| 73 | const parsed = z.object(t.shape).strict().safeParse(params ?? {}); |
| 74 | if (!parsed.success) return send(res, 400, { ok: false, error: `invalid params for ${tool}: ${parsed.error.message}` }); |
| 75 | const t0 = Date.now(); |
| 76 | try { |
| 77 | const result = await t.run(ctx, parsed.data); |
| 78 | log(`${tool} ok ${Date.now() - t0}ms`); |
| 79 | send(res, 200, { ok: true, result }); |
| 80 | } catch (e) { |
| 81 | log(`${tool} FAILED ${Date.now() - t0}ms: ${(e as Error).message.split('\n')[0]}`); |
| 82 | send(res, 200, { ok: false, error: (e as Error).message }); |
| 83 | } |
| 84 | } catch (e) { |
| 85 | send(res, 500, { ok: false, error: (e as Error).stack ?? String(e) }); |
| 86 | } |
| 87 | }); |
| 88 | httpServer.requestTimeout = 0; |
| 89 | httpServer.headersTimeout = 0; |
| 90 | |
| 91 | httpServer.listen(cfg.daemonPort, '127.0.0.1', () => { |
| 92 | fs.writeFileSync(path.join(DIRS.run, 'daemon.json'), JSON.stringify({ pid: process.pid, port: cfg.daemonPort })); |
| 93 | log(`mc-tester daemon listening on 127.0.0.1:${cfg.daemonPort} (client display: ${cfg.client.display})`); |
| 94 | }); |
| 95 | httpServer.on('error', (e) => { |
| 96 | log(`daemon failed to listen: ${e.message}`); |
| 97 | process.exit(1); |
| 98 | }); |
| 99 | |
| 100 | process.on('SIGINT', () => void shutdown(0)); |
| 101 | process.on('SIGTERM', () => void shutdown(0)); |