leejunyoung5819mc-paper-plugin-test-mcp-26.3

공개

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

101줄4.0 KB
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>.
3import http from 'node:http';
4import fs from 'node:fs';
5import path from 'node:path';
6import { z } from 'zod';
7import { DIRS, ensureDirs, loadConfig } from './config.ts';
8import { PaperServer } from './paper.ts';
9import { ClientManager } from './clients.ts';
10import { TOOLS, TOOL_MAP, type Ctx } from './tools.ts';
11import { runScenario } from './scenario.ts';
12
13ensureDirs();
14const cfg = loadConfig();
15const logFile = fs.createWriteStream(path.join(DIRS.run, 'daemon.log'), { flags: 'a' });
16const log = (m: string) => {
17 const line = `${new Date().toISOString()} ${m}\n`;
18 logFile.write(line);
19 process.stderr.write(line);
20};
21
22const server = new PaperServer(cfg);
23const clients = new ClientManager(cfg, () => server.status().address, log);
24const ctx: Ctx = {
25 server,
26 clients,
27 marks: new Map(),
28 runScenario: (file, opts) => runScenario(ctx, file, opts),
29};
30
31function 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
40function 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
46let shuttingDown = false;
47async 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
58const 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});
88httpServer.requestTimeout = 0;
89httpServer.headersTimeout = 0;
90
91httpServer.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});
95httpServer.on('error', (e) => {
96 log(`daemon failed to listen: ${e.message}`);
97 process.exit(1);
98});
99
100process.on('SIGINT', () => void shutdown(0));
101process.on('SIGTERM', () => void shutdown(0));