leejunyoung5819 mc-paper-plugin-test-mcp-26.3
공개마인크래프트 26.3 Paper 서버의 플러그인 테스트를 하려는 AI 에이전트를 위한 MCP 도구
| 1 | // Single source of truth for every harness operation: name, description (what agents read), |
| 2 | // zod parameter schema, and the implementation (runs inside the daemon). |
| 3 | import path from 'node:path'; |
| 4 | import { z } from 'zod'; |
| 5 | import { DIRS, ROOT, stamp, updateUserConfig } from './config.ts'; |
| 6 | import { resolvePlugins } from './plugins.ts'; |
| 7 | import path2 from 'node:path'; |
| 8 | import type { PaperServer } from './paper.ts'; |
| 9 | import type { ClientManager } from './clients.ts'; |
| 10 | import { sleep } from './paper.ts'; |
| 11 | |
| 12 | export interface Ctx { |
| 13 | server: PaperServer; |
| 14 | clients: ClientManager; |
| 15 | /** chat seq recorded right before the last action per client (default `since` for wait_for chat). */ |
| 16 | marks: Map<string, number>; |
| 17 | runScenario: (file: string, opts: { stopOnFail?: boolean }) => Promise<object>; |
| 18 | } |
| 19 | |
| 20 | export interface Tool { |
| 21 | name: string; |
| 22 | description: string; |
| 23 | shape: z.ZodRawShape; |
| 24 | run: (ctx: Ctx, p: any) => Promise<any>; |
| 25 | } |
| 26 | |
| 27 | const client = z.string().optional().describe('Client (player) name. Optional when exactly one client is running.'); |
| 28 | const shot = z.boolean().optional().describe('Also take a screenshot ~150ms after the action and return it.'); |
| 29 | |
| 30 | async function mark(ctx: Ctx, name: string | undefined): Promise<void> { |
| 31 | try { |
| 32 | const r = await ctx.clients.call(name, 'chat_log', { since: Number.MAX_SAFE_INTEGER }); |
| 33 | ctx.marks.set((name ?? ctx.clients.running()[0] ?? '').toLowerCase(), r.next); |
| 34 | } catch { |
| 35 | /* not fatal */ |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | async function screenshot(ctx: Ctx, name: string | undefined, label = 'shot'): Promise<any> { |
| 40 | const c = ctx.clients.get(name); |
| 41 | const safe = label.replace(/[^\w.-]+/g, '_').slice(0, 60); |
| 42 | const file = path.join(DIRS.artifacts, c.name, `${stamp()}-${safe}.png`); |
| 43 | return ctx.clients.call(c.name, 'screenshot', { path: file }, 30_000); |
| 44 | } |
| 45 | |
| 46 | /** Run a bridge action, recording the chat mark first and optionally screenshotting afterwards. */ |
| 47 | async function act(ctx: Ctx, p: any, route: string, body: object, label: string): Promise<any> { |
| 48 | await mark(ctx, p.client); |
| 49 | const r = await ctx.clients.call(p.client, route, body, 60_000); |
| 50 | if (p.screenshot) { |
| 51 | await sleep(150); |
| 52 | r.screenshot = (await screenshot(ctx, p.client, label)).path; |
| 53 | } |
| 54 | return r; |
| 55 | } |
| 56 | |
| 57 | function matchItem(item: any, q: { name?: string; id?: string; lore?: string }): boolean { |
| 58 | if (!item) return false; |
| 59 | if (q.id && item.id !== q.id && item.id !== `minecraft:${q.id}`) return false; |
| 60 | if (q.name && !String(item.name).includes(q.name)) return false; |
| 61 | if (q.lore && !(item.lore ?? []).concat(item.tooltip ?? []).some((l: string) => l.includes(q.lore!))) return false; |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | export const TOOLS: Tool[] = [ |
| 66 | // ---------------------------------------------------------------- server |
| 67 | { |
| 68 | name: 'server_start', |
| 69 | description: |
| 70 | 'Start the Paper test server (127.0.0.1, RCON enabled). Copies the configured plugin jars into plugins/ first, so rebuild your plugin then restart to test new code. Returns once the server logged "Done".', |
| 71 | shape: {}, |
| 72 | run: (ctx) => ctx.server.start(), |
| 73 | }, |
| 74 | { |
| 75 | name: 'server_stop', |
| 76 | description: 'Stop the Paper test server gracefully (saves the world).', |
| 77 | shape: {}, |
| 78 | run: (ctx) => ctx.server.stop(), |
| 79 | }, |
| 80 | { |
| 81 | name: 'server_restart', |
| 82 | description: 'Restart the server (e.g. after rebuilding the plugin) and reconnect every running client.', |
| 83 | shape: {}, |
| 84 | run: async (ctx) => { |
| 85 | const inWorld = await connectedClients(ctx); |
| 86 | await ctx.server.stop(); |
| 87 | const started = await ctx.server.start(); |
| 88 | const reconnected = await reconnect(ctx, inWorld); |
| 89 | return { started, reconnected }; |
| 90 | }, |
| 91 | }, |
| 92 | { |
| 93 | name: 'server_status', |
| 94 | description: 'Server status: running/ready, address, installed plugins, current log sequence number.', |
| 95 | shape: {}, |
| 96 | run: async (ctx) => ({ ...ctx.server.status(), clients: ctx.clients.list(), snapshots: ctx.server.listSnapshots() }), |
| 97 | }, |
| 98 | { |
| 99 | name: 'rcon', |
| 100 | description: |
| 101 | 'Run a server console command over RCON and return its text output (no leading slash needed). Use it to set up state (give, tp, op, gamemode, your plugin admin commands) and to verify server-side truth (e.g. "data get entity Bot1 Inventory", your plugin\'s debug/JSON commands).', |
| 102 | shape: { command: z.string().describe('e.g. "give Bot1 emerald 10"') }, |
| 103 | run: async (ctx, p) => ({ output: await ctx.server.command(p.command) }), |
| 104 | }, |
| 105 | { |
| 106 | name: 'server_log', |
| 107 | description: |
| 108 | 'Read server console lines after a sequence number (use the returned "next" as the next since). Optional regex filter. errors_only returns only ERROR lines / exceptions / stack frames.', |
| 109 | shape: { |
| 110 | since: z.number().optional(), |
| 111 | grep: z.string().optional().describe('Case-insensitive regex filter'), |
| 112 | limit: z.number().optional(), |
| 113 | errors_only: z.boolean().optional(), |
| 114 | }, |
| 115 | run: async (ctx, p) => { |
| 116 | if (p.errors_only) return { next: ctx.server.logSeq, lines: ctx.server.errors(p.since ?? 0).slice(-(p.limit ?? 200)) }; |
| 117 | return ctx.server.log(p.since ?? 0, p.grep, p.limit ?? 200); |
| 118 | }, |
| 119 | }, |
| 120 | { |
| 121 | name: 'plugins_list', |
| 122 | description: |
| 123 | 'Show which plugin jars the test server loads: the configured patterns (server.plugins in mct.config.json), the exact jar each resolves to (plugin name/version from plugin.yml, build time), older builds that are skipped, patterns that match nothing, and what is installed in the running server.', |
| 124 | shape: {}, |
| 125 | run: async (ctx) => { |
| 126 | const patterns = ctx.server.config.server.plugins; |
| 127 | const res = resolvePlugins(patterns); |
| 128 | const rel = (f: string) => path2.relative(ROOT, f); |
| 129 | return { |
| 130 | patterns, |
| 131 | selected: res.selected.map((j) => ({ plugin: j.plugin, version: j.version, file: rel(j.file), builtAt: j.mtime, pattern: j.pattern })), |
| 132 | skipped: res.skipped.map((j) => ({ file: rel(j.file), reason: j.reason })), |
| 133 | unmatched: res.unmatched, |
| 134 | installedInServer: ctx.server.status().plugins, |
| 135 | note: 'Changes take effect on server_start / server_restart.', |
| 136 | }; |
| 137 | }, |
| 138 | }, |
| 139 | { |
| 140 | name: 'plugins_set', |
| 141 | description: |
| 142 | 'Change which plugin jars the test server loads and save it to mct.config.json (server.plugins). Give the full list with `plugins`, or use `add` / `remove`. Entries are jar paths or patterns relative to the mc-tester repo (or absolute); * is allowed in the file name, e.g. "../my-server/build/libs/MyPlugin-*.jar". Several builds of the same plugin resolve to the newest. Every entry must match a jar unless allow_unmatched is true. restart:true restarts the server (and reconnects clients) so the change applies now.', |
| 143 | shape: { |
| 144 | plugins: z.array(z.string()).optional().describe('Replace the whole list'), |
| 145 | add: z.array(z.string()).optional(), |
| 146 | remove: z.array(z.string()).optional().describe('Exact entries to remove'), |
| 147 | restart: z.boolean().optional(), |
| 148 | allow_unmatched: z.boolean().optional().describe('Save even if an entry matches no jar yet (e.g. not built yet)'), |
| 149 | }, |
| 150 | run: async (ctx, p) => { |
| 151 | if (!p.plugins && !p.add && !p.remove) throw new Error('give plugins, add or remove'); |
| 152 | const before: string[] = [...ctx.server.config.server.plugins]; |
| 153 | let next: string[] = p.plugins ? [...p.plugins] : [...before]; |
| 154 | for (const a of p.add ?? []) if (!next.includes(a)) next.push(a); |
| 155 | const notFound = (p.remove ?? []).filter((r: string) => !next.includes(r)); |
| 156 | if (notFound.length) throw new Error(`not in the list: ${notFound.join(', ')}; current: ${JSON.stringify(next)}`); |
| 157 | next = next.filter((x) => !(p.remove ?? []).includes(x)); |
| 158 | const res = resolvePlugins(next); |
| 159 | if (res.unmatched.length && !p.allow_unmatched) { |
| 160 | throw new Error(`these entries match no jar: ${res.unmatched.join(', ')} (paths are relative to ${ROOT}; build first or pass allow_unmatched:true). Nothing was saved.`); |
| 161 | } |
| 162 | ctx.server.config.server.plugins = next; |
| 163 | const file = updateUserConfig((c) => { |
| 164 | c.server = { ...(c.server ?? {}), plugins: next }; |
| 165 | }); |
| 166 | const out: any = { |
| 167 | saved: file, |
| 168 | before, |
| 169 | after: next, |
| 170 | willLoad: res.selected.map((j) => ({ plugin: j.plugin, version: j.version, file: path2.relative(ROOT, j.file) })), |
| 171 | skipped: res.skipped.map((j) => ({ file: path2.relative(ROOT, j.file), reason: j.reason })), |
| 172 | unmatched: res.unmatched, |
| 173 | }; |
| 174 | if (p.restart) out.restart = await TOOL_MAP.get('server_restart')!.run(ctx, {}); |
| 175 | else out.note = ctx.server.running ? 'Saved. Run server_restart to load the new plugin set.' : 'Saved. Applies on the next server_start.'; |
| 176 | return out; |
| 177 | }, |
| 178 | }, |
| 179 | { |
| 180 | name: 'world_snapshot', |
| 181 | description: |
| 182 | 'Save the current world + plugin data folders (plugins/*/) as a named snapshot. Works while the server runs (save-off/flush). Make a clean "base" snapshot once, then world_reset to it before each test.', |
| 183 | shape: { name: z.string() }, |
| 184 | run: (ctx, p) => ctx.server.snapshot(p.name), |
| 185 | }, |
| 186 | { |
| 187 | name: 'world_reset', |
| 188 | description: |
| 189 | 'Restore a snapshot: stops the server, replaces world + plugin data, starts it again and reconnects running clients. Use for deterministic tests.', |
| 190 | shape: { name: z.string() }, |
| 191 | run: async (ctx, p) => { |
| 192 | const inWorld = await connectedClients(ctx); |
| 193 | const restored = await ctx.server.restore(p.name); |
| 194 | const reconnected = await reconnect(ctx, inWorld); |
| 195 | return { restored, reconnected }; |
| 196 | }, |
| 197 | }, |
| 198 | |
| 199 | // ---------------------------------------------------------------- clients |
| 200 | { |
| 201 | name: 'client_launch', |
| 202 | description: |
| 203 | 'Launch a real Minecraft 26.3 client (Fabric + QA Bridge) as player `name` and join the test server. account "offline" (default) = any test name, needs offline-mode server; "microsoft" = the real logged-in account (one at a time). Takes ~30-90s the first time.', |
| 204 | shape: { |
| 205 | name: z.string().describe('Player name for offline accounts (3-16 chars). For microsoft, a label; the real profile name is used.'), |
| 206 | account: z.enum(['offline', 'microsoft']).optional(), |
| 207 | connect: z.union([z.boolean(), z.string()]).optional().describe('true (default) = join the test server; false = stay on title screen; "host:port" = join that server'), |
| 208 | display: z.enum(['xvfb', 'host']).optional().describe('xvfb = invisible virtual display (default from config); host = visible window on the desktop'), |
| 209 | }, |
| 210 | run: (ctx, p) => ctx.clients.launch(p.name, { account: p.account, connect: p.connect, display: p.display }), |
| 211 | }, |
| 212 | { |
| 213 | name: 'client_stop', |
| 214 | description: 'Quit a client.', |
| 215 | shape: { client }, |
| 216 | run: (ctx, p) => ctx.clients.stop(p.client), |
| 217 | }, |
| 218 | { |
| 219 | name: 'client_list', |
| 220 | description: 'List launched clients and whether they are running.', |
| 221 | shape: {}, |
| 222 | run: async (ctx) => ({ clients: ctx.clients.list() }), |
| 223 | }, |
| 224 | { |
| 225 | name: 'client_connect', |
| 226 | description: 'Make a client (re)join a server (default: the test server) and wait until it is in the world.', |
| 227 | shape: { client, address: z.string().optional() }, |
| 228 | run: async (ctx, p) => { |
| 229 | await ctx.clients.call(p.client, 'connect', { address: p.address ?? ctx.server.status().address }); |
| 230 | return waitInWorld(ctx, p.client, 60_000); |
| 231 | }, |
| 232 | }, |
| 233 | { |
| 234 | name: 'client_disconnect', |
| 235 | description: 'Disconnect a client from the server (back to title screen).', |
| 236 | shape: { client }, |
| 237 | run: (ctx, p) => ctx.clients.call(p.client, 'disconnect'), |
| 238 | }, |
| 239 | |
| 240 | // ---------------------------------------------------------------- observe |
| 241 | { |
| 242 | name: 'state', |
| 243 | description: |
| 244 | 'Player state as the client sees it: position, rotation, health, food, game mode, dimension, selected hotbar slot, full inventory (item id/count/name/lore/tooltip), open screen, and what the crosshair targets.', |
| 245 | shape: { client }, |
| 246 | run: (ctx, p) => ctx.clients.call(p.client, 'state'), |
| 247 | }, |
| 248 | { |
| 249 | name: 'screen', |
| 250 | description: |
| 251 | 'Describe the open GUI exactly as the client has it. For container GUIs (chests/shops/custom menus): title, menuType, every non-empty slot with menu slot index, area (container|player), GUI x/y, and item (id, count, name, lore, full tooltip), plus the carried (cursor) item. For any screen: widgets (buttons, text boxes, labels) with index, label, position. Set screenshot=true to also get an image.', |
| 252 | shape: { client, includeEmpty: z.boolean().optional(), screenshot: shot }, |
| 253 | run: async (ctx, p) => { |
| 254 | const r = await ctx.clients.call(p.client, 'screen', { includeEmpty: !!p.includeEmpty }); |
| 255 | if (p.screenshot) r.screenshot = (await screenshot(ctx, p.client, 'screen')).path; |
| 256 | return r; |
| 257 | }, |
| 258 | }, |
| 259 | { |
| 260 | name: 'screenshot', |
| 261 | description: 'Take a screenshot of what the client renders right now (world, HUD and any open GUI), returned as an image and saved under .mct/artifacts/<client>/.', |
| 262 | shape: { client, label: z.string().optional().describe('Short label used in the file name') }, |
| 263 | run: (ctx, p) => screenshot(ctx, p.client, p.label ?? 'shot'), |
| 264 | }, |
| 265 | { |
| 266 | name: 'chat_log', |
| 267 | description: 'Messages the client received (chat, system/game messages, action bar) after seq `since`. Use returned "next" as the next since.', |
| 268 | shape: { client, since: z.number().optional() }, |
| 269 | run: (ctx, p) => ctx.clients.call(p.client, 'chat_log', { since: p.since ?? 0 }), |
| 270 | }, |
| 271 | { |
| 272 | name: 'entities', |
| 273 | description: 'Entities near the player (id, type, name/customName, position, distance), nearest first. Use to find NPCs.', |
| 274 | shape: { client, radius: z.number().optional(), name: z.string().optional().describe('substring filter on display name') }, |
| 275 | run: (ctx, p) => ctx.clients.call(p.client, 'entities', { radius: p.radius, name: p.name }), |
| 276 | }, |
| 277 | { |
| 278 | name: 'wait_for', |
| 279 | description: |
| 280 | 'Wait until a condition holds (polls every 100ms). chat: regex that a message received after the client\'s last action (or after `since`) must match. screen_title: regex for the open screen title. screen_closed: wait until no screen. Returns what matched; fails on timeout with the current state.', |
| 281 | shape: { |
| 282 | client, |
| 283 | chat: z.string().optional(), |
| 284 | since: z.number().optional(), |
| 285 | screen_title: z.string().optional(), |
| 286 | screen_closed: z.boolean().optional(), |
| 287 | timeout_ms: z.number().optional(), |
| 288 | screenshot: shot, |
| 289 | }, |
| 290 | run: async (ctx, p) => { |
| 291 | const c = ctx.clients.get(p.client); |
| 292 | const timeout = p.timeout_ms ?? 10_000; |
| 293 | const since = p.since ?? ctx.marks.get(c.name.toLowerCase()) ?? 0; |
| 294 | const t0 = Date.now(); |
| 295 | let last: any = null; |
| 296 | for (;;) { |
| 297 | if (p.chat) { |
| 298 | const log = await ctx.clients.call(c.name, 'chat_log', { since }); |
| 299 | const re = new RegExp(p.chat); |
| 300 | const hit = log.messages.find((m: any) => re.test(m.text)); |
| 301 | last = { recentChat: log.messages.slice(-10).map((m: any) => m.text) }; |
| 302 | if (hit) return done({ matched: 'chat', message: hit }); |
| 303 | } |
| 304 | if (p.screen_title !== undefined || p.screen_closed) { |
| 305 | const st = await ctx.clients.call(c.name, 'state'); |
| 306 | last = { ...last, screen: st.screen }; |
| 307 | if (p.screen_closed && !st.screen.open) return done({ matched: 'screen_closed' }); |
| 308 | if (p.screen_title !== undefined && st.screen.open && new RegExp(p.screen_title).test(st.screen.title ?? '')) |
| 309 | return done({ matched: 'screen_title', screen: st.screen }); |
| 310 | } |
| 311 | if (!p.chat && p.screen_title === undefined && !p.screen_closed) throw new Error('give chat, screen_title or screen_closed'); |
| 312 | if (Date.now() - t0 > timeout) throw new Error(`wait_for timed out after ${timeout}ms; last seen: ${JSON.stringify(last)}`); |
| 313 | await sleep(100); |
| 314 | } |
| 315 | async function done(r: any) { |
| 316 | if (p.screenshot) r.screenshot = (await screenshot(ctx, c.name, 'wait_for')).path; |
| 317 | return r; |
| 318 | } |
| 319 | }, |
| 320 | }, |
| 321 | |
| 322 | // ---------------------------------------------------------------- GUI input |
| 323 | { |
| 324 | name: 'click_slot', |
| 325 | description: |
| 326 | 'Click a slot of the open container GUI by menu slot index (from `screen`). Sends exactly what the real client sends. mode: PICKUP (normal click; button 0=left 1=right), QUICK_MOVE (shift-click), SWAP (number key; button=hotbar 0-8, 40=offhand), CLONE (middle click), THROW (Q; button 0=one 1=stack), PICKUP_ALL (double-click collect), QUICK_CRAFT (drag). slot -999 = click outside the window.', |
| 327 | shape: { |
| 328 | client, |
| 329 | slot: z.number(), |
| 330 | button: z.number().optional(), |
| 331 | mode: z.enum(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'QUICK_CRAFT', 'PICKUP_ALL']).optional(), |
| 332 | screenshot: shot, |
| 333 | }, |
| 334 | run: (ctx, p) => act(ctx, p, 'click_slot', { slot: p.slot, button: p.button ?? 0, mode: p.mode ?? 'PICKUP' }, `click-${p.slot}`), |
| 335 | }, |
| 336 | { |
| 337 | name: 'click_item', |
| 338 | description: |
| 339 | 'Find a slot in the open GUI by item name / id / lore text (substring) and click it - robust against layout changes. area limits the search to "container" (the GUI) or "player" (own inventory). Same button/mode semantics as click_slot.', |
| 340 | shape: { |
| 341 | client, |
| 342 | name: z.string().optional(), |
| 343 | id: z.string().optional().describe('e.g. minecraft:diamond'), |
| 344 | lore: z.string().optional(), |
| 345 | area: z.enum(['container', 'player', 'any']).optional(), |
| 346 | button: z.number().optional(), |
| 347 | mode: z.enum(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'QUICK_CRAFT', 'PICKUP_ALL']).optional(), |
| 348 | screenshot: shot, |
| 349 | }, |
| 350 | run: async (ctx, p) => { |
| 351 | if (!p.name && !p.id && !p.lore) throw new Error('give name, id or lore'); |
| 352 | const scr = await ctx.clients.call(p.client, 'screen'); |
| 353 | if (!scr.container) throw new Error(`no container GUI open (screen: ${scr.class ?? 'none'})`); |
| 354 | const area = p.area ?? 'container'; |
| 355 | const hit = scr.slots.find((s: any) => (area === 'any' || s.area === area) && matchItem(s.item, p)); |
| 356 | if (!hit) { |
| 357 | const seen = scr.slots.filter((s: any) => area === 'any' || s.area === area).map((s: any) => `${s.slot}:${s.item?.name}`); |
| 358 | throw new Error(`no ${area} slot matches ${JSON.stringify({ name: p.name, id: p.id, lore: p.lore })}; slots: ${seen.join(', ')}`); |
| 359 | } |
| 360 | const r = await act(ctx, p, 'click_slot', { slot: hit.slot, button: p.button ?? 0, mode: p.mode ?? 'PICKUP' }, `click-${hit.slot}`); |
| 361 | return { ...r, item: hit.item }; |
| 362 | }, |
| 363 | }, |
| 364 | { |
| 365 | name: 'mouse', |
| 366 | description: |
| 367 | 'Raw mouse input on the open screen at GUI coordinates (the x/y space used by `screen` slots and widgets), injected through the client\'s real mouse handler. Use for custom GUIs, dialogs and buttons. action: click|double|down|up|move. shift/ctrl hold modifiers.', |
| 368 | shape: { |
| 369 | client, |
| 370 | x: z.number(), |
| 371 | y: z.number(), |
| 372 | button: z.enum(['left', 'right', 'middle']).optional(), |
| 373 | action: z.enum(['click', 'double', 'down', 'up', 'move']).optional(), |
| 374 | shift: z.boolean().optional(), |
| 375 | ctrl: z.boolean().optional(), |
| 376 | screenshot: shot, |
| 377 | }, |
| 378 | run: (ctx, p) => act(ctx, p, 'mouse', { x: p.x, y: p.y, button: p.button ?? 'left', action: p.action ?? 'click', shift: !!p.shift, ctrl: !!p.ctrl }, 'mouse'), |
| 379 | }, |
| 380 | { |
| 381 | name: 'click_widget', |
| 382 | description: 'Click a button/widget on the open screen by its label (substring) or index from `screen`.widgets, through the real mouse handler.', |
| 383 | shape: { client, label: z.string().optional(), index: z.number().optional(), screenshot: shot }, |
| 384 | run: async (ctx, p) => { |
| 385 | const scr = await ctx.clients.call(p.client, 'screen'); |
| 386 | if (!scr.open) throw new Error('no screen open'); |
| 387 | const w = |
| 388 | p.index !== undefined |
| 389 | ? scr.widgets.find((x: any) => x.index === p.index) |
| 390 | : scr.widgets.find((x: any) => p.label && x.label.includes(p.label)); |
| 391 | if (!w) throw new Error(`no widget ${p.label ?? p.index}; widgets: ${scr.widgets.map((x: any) => `${x.index}:${x.type}:"${x.label}"`).join(', ')}`); |
| 392 | const r = await act(ctx, p, 'mouse', { x: w.cx, y: w.cy, button: 'left', action: 'click' }, 'widget'); |
| 393 | return { ...r, widget: w }; |
| 394 | }, |
| 395 | }, |
| 396 | { |
| 397 | name: 'key', |
| 398 | description: |
| 399 | 'Press a keyboard key through the client\'s real keyboard handler (works in GUIs and in the world): escape, enter, tab, backspace, e (inventory), t (chat), 1-9 (hotbar / swap while hovering a slot), q, f1-f12, arrows... action press|down|up.', |
| 400 | shape: { client, key: z.string(), action: z.enum(['press', 'down', 'up']).optional(), shift: z.boolean().optional(), ctrl: z.boolean().optional(), screenshot: shot }, |
| 401 | run: (ctx, p) => act(ctx, p, 'key', { key: p.key, action: p.action ?? 'press', shift: !!p.shift, ctrl: !!p.ctrl }, `key-${p.key}`), |
| 402 | }, |
| 403 | { |
| 404 | name: 'type_text', |
| 405 | description: 'Type text into the focused text field of the open screen (sign editor, anvil, chat box, dialog input, search box). Korean and other Unicode are fine.', |
| 406 | shape: { client, text: z.string(), screenshot: shot }, |
| 407 | run: (ctx, p) => act(ctx, p, 'type', { text: p.text }, 'type'), |
| 408 | }, |
| 409 | { |
| 410 | name: 'close_screen', |
| 411 | description: 'Close the open screen (like pressing Esc; for containers sends the close-container packet).', |
| 412 | shape: { client, screenshot: shot }, |
| 413 | run: (ctx, p) => act(ctx, p, 'close_screen', {}, 'close'), |
| 414 | }, |
| 415 | |
| 416 | // ---------------------------------------------------------------- world input |
| 417 | { |
| 418 | name: 'chat', |
| 419 | description: 'Send a chat message, or a command if it starts with "/" (runs with the player\'s own permissions).', |
| 420 | shape: { client, text: z.string(), screenshot: shot }, |
| 421 | run: (ctx, p) => act(ctx, p, 'chat', { text: p.text }, 'chat'), |
| 422 | }, |
| 423 | { |
| 424 | name: 'teleport', |
| 425 | description: 'Teleport the player (server-side tp via RCON) and wait until the client sees the new position.', |
| 426 | shape: { client, x: z.number(), y: z.number(), z: z.number(), yaw: z.number().optional(), pitch: z.number().optional() }, |
| 427 | run: async (ctx, p) => { |
| 428 | const c = ctx.clients.get(p.client); |
| 429 | const rot = p.yaw !== undefined ? ` ${p.yaw} ${p.pitch ?? 0}` : ''; |
| 430 | const out = await ctx.server.command(`tp ${c.name} ${p.x} ${p.y} ${p.z}${rot}`); |
| 431 | const t0 = Date.now(); |
| 432 | for (;;) { |
| 433 | const st = await ctx.clients.call(c.name, 'state'); |
| 434 | const pos = st.player?.pos; |
| 435 | if (pos && Math.abs(pos.x - p.x) < 1.5 && Math.abs(pos.z - p.z) < 1.5 && Math.abs(pos.y - p.y) < 3) { |
| 436 | await sleep(500); // let chunks/entities around the new position arrive |
| 437 | return { output: out, pos }; |
| 438 | } |
| 439 | if (Date.now() - t0 > 10_000) throw new Error(`client did not arrive at ${p.x} ${p.y} ${p.z} (server said: ${out}; client pos ${JSON.stringify(pos)})`); |
| 440 | await sleep(150); |
| 441 | } |
| 442 | }, |
| 443 | }, |
| 444 | { |
| 445 | name: 'look', |
| 446 | description: 'Turn the camera: give yaw/pitch, or x/y/z to look at a point, or id/name to look at an entity.', |
| 447 | shape: { client, yaw: z.number().optional(), pitch: z.number().optional(), x: z.number().optional(), y: z.number().optional(), z: z.number().optional(), id: z.number().optional(), name: z.string().optional() }, |
| 448 | run: (ctx, p) => { |
| 449 | const { client: _c, ...rest } = p; |
| 450 | return ctx.clients.call(p.client, 'look', rest); |
| 451 | }, |
| 452 | }, |
| 453 | { |
| 454 | name: 'interact_entity', |
| 455 | description: |
| 456 | 'Aim at an entity (NPC, villager, item frame, armor stand...) by id or name substring, verify the crosshair is on it, then right-click it like a player (action "attack" = left-click). Must be within reach (~3 blocks): teleport next to it first.', |
| 457 | shape: { client, id: z.number().optional(), name: z.string().optional(), action: z.enum(['use', 'attack']).optional(), screenshot: shot }, |
| 458 | run: (ctx, p) => act(ctx, p, 'interact_entity', { id: p.id, name: p.name, action: p.action ?? 'use' }, 'interact'), |
| 459 | }, |
| 460 | { |
| 461 | name: 'use_on_block', |
| 462 | description: 'Aim at a block (x,y,z) and right-click it (open chest/door/button/sign, place against it with the held item). action "attack" = start breaking.', |
| 463 | shape: { client, x: z.number(), y: z.number(), z: z.number(), action: z.enum(['use', 'attack']).optional(), screenshot: shot }, |
| 464 | run: (ctx, p) => act(ctx, p, 'use_on_block', { x: p.x, y: p.y, z: p.z, action: p.action ?? 'use' }, 'use-block'), |
| 465 | }, |
| 466 | { |
| 467 | name: 'use', |
| 468 | description: 'Right-click once with whatever the crosshair targets / the held item (eat, throw, use custom item like a cheque).', |
| 469 | shape: { client, screenshot: shot }, |
| 470 | run: (ctx, p) => act(ctx, p, 'use', {}, 'use'), |
| 471 | }, |
| 472 | { |
| 473 | name: 'attack', |
| 474 | description: 'Left-click once at the crosshair target.', |
| 475 | shape: { client, screenshot: shot }, |
| 476 | run: (ctx, p) => act(ctx, p, 'attack', {}, 'attack'), |
| 477 | }, |
| 478 | { |
| 479 | name: 'hold_keys', |
| 480 | description: 'Hold movement/action keys for ms milliseconds: forward, back, left, right, jump, sneak, sprint, use, attack.', |
| 481 | shape: { client, keys: z.array(z.string()), ms: z.number().optional() }, |
| 482 | run: (ctx, p) => act(ctx, p, 'hold', { keys: p.keys, ms: p.ms ?? 500 }, 'hold'), |
| 483 | }, |
| 484 | { |
| 485 | name: 'hotbar', |
| 486 | description: 'Select hotbar slot 0-8 (the held item).', |
| 487 | shape: { client, slot: z.number() }, |
| 488 | run: (ctx, p) => ctx.clients.call(p.client, 'hotbar', { slot: p.slot }), |
| 489 | }, |
| 490 | |
| 491 | // ---------------------------------------------------------------- scenarios |
| 492 | { |
| 493 | name: 'run_scenario', |
| 494 | description: |
| 495 | 'Run a YAML scenario file (see scenarios/README.md): ordered steps calling these same tools plus expect_* assertions. Returns pass/fail per step, failure screenshots and a JSON report path.', |
| 496 | shape: { file: z.string().describe('Path relative to the repo root, e.g. scenarios/demo-shop.yaml'), stop_on_fail: z.boolean().optional() }, |
| 497 | run: (ctx, p) => ctx.runScenario(p.file, { stopOnFail: p.stop_on_fail ?? true }), |
| 498 | }, |
| 499 | ]; |
| 500 | |
| 501 | async function connectedClients(ctx: Ctx): Promise<string[]> { |
| 502 | const out: string[] = []; |
| 503 | for (const name of ctx.clients.running()) { |
| 504 | try { |
| 505 | const st = await ctx.clients.call(name, 'state'); |
| 506 | if (st.inWorld) out.push(name); |
| 507 | } catch { |
| 508 | /* ignore */ |
| 509 | } |
| 510 | } |
| 511 | return out; |
| 512 | } |
| 513 | |
| 514 | async function waitInWorld(ctx: Ctx, name: string | undefined, timeout: number): Promise<any> { |
| 515 | const t0 = Date.now(); |
| 516 | for (;;) { |
| 517 | const st = await ctx.clients.call(name, 'state'); |
| 518 | if (st.inWorld && (!st.screen.open || !/Loading|Receiving|Connect/i.test(st.screen.class))) return st; |
| 519 | if (st.screen?.class === 'DisconnectedScreen') { |
| 520 | const scr = await ctx.clients.call(name, 'screen'); |
| 521 | throw new Error(`disconnected: ${scr.widgets.map((w: any) => w.label).join(' | ')}`); |
| 522 | } |
| 523 | if (Date.now() - t0 > timeout) throw new Error(`not in world after ${timeout}ms (screen ${st.screen?.class})`); |
| 524 | await sleep(300); |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | async function reconnect(ctx: Ctx, names: string[]): Promise<object> { |
| 529 | const out: Record<string, string> = {}; |
| 530 | for (const n of names) { |
| 531 | try { |
| 532 | // The client notices the server going away on its own; give it a moment, then rejoin. |
| 533 | await sleep(500); |
| 534 | await ctx.clients.call(n, 'connect', { address: ctx.server.status().address }); |
| 535 | await waitInWorld(ctx, n, 60_000); |
| 536 | out[n] = 'ok'; |
| 537 | } catch (e) { |
| 538 | out[n] = `failed: ${(e as Error).message}`; |
| 539 | } |
| 540 | } |
| 541 | return out; |
| 542 | } |
| 543 | |
| 544 | export const TOOL_MAP = new Map(TOOLS.map((t) => [t.name, t])); |