@minecraftbot-com/plugin 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/AGENTS.md +188 -0
  2. package/README.md +47 -3
  3. package/dist/api.d.ts +354 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +49 -0
  6. package/dist/cli/api.js +69 -0
  7. package/dist/cli/build.d.ts +24 -0
  8. package/dist/cli/build.js +72 -0
  9. package/dist/cli/check.d.ts +17 -0
  10. package/dist/cli/check.js +99 -0
  11. package/dist/cli/config.d.ts +11 -0
  12. package/dist/cli/config.js +38 -0
  13. package/dist/cli/create.d.ts +2 -0
  14. package/dist/cli/create.js +39 -0
  15. package/dist/cli/deploy.d.ts +13 -0
  16. package/dist/cli/deploy.js +51 -0
  17. package/dist/cli/dev-mcp.d.ts +36 -0
  18. package/dist/cli/dev-mcp.js +101 -0
  19. package/dist/cli/dev.d.ts +15 -0
  20. package/dist/cli/dev.js +261 -0
  21. package/dist/cli/fetch-guard.d.ts +7 -0
  22. package/dist/cli/fetch-guard.js +66 -0
  23. package/dist/cli/main.d.ts +2 -0
  24. package/dist/cli/main.js +119 -0
  25. package/dist/cli/mcp.d.ts +24 -0
  26. package/dist/cli/mcp.js +136 -0
  27. package/dist/cli/output.d.ts +11 -0
  28. package/dist/cli/output.js +25 -0
  29. package/dist/cli/test.d.ts +2 -0
  30. package/dist/cli/test.js +39 -0
  31. package/dist/errors.d.ts +22 -0
  32. package/dist/errors.js +35 -0
  33. package/dist/generated/block-states.d.ts +4087 -0
  34. package/dist/generated/block-states.js +2 -0
  35. package/dist/generated/blocks.d.ts +1289 -0
  36. package/dist/generated/blocks.js +1291 -0
  37. package/dist/generated/contracts.d.ts +304 -0
  38. package/dist/generated/contracts.js +327 -0
  39. package/dist/generated/effects.d.ts +43 -0
  40. package/dist/generated/effects.js +45 -0
  41. package/dist/generated/entities.d.ts +164 -0
  42. package/dist/generated/entities.js +166 -0
  43. package/dist/generated/items.d.ts +1661 -0
  44. package/dist/generated/items.js +1663 -0
  45. package/dist/generated/operations.d.ts +7 -0
  46. package/dist/generated/operations.js +65 -0
  47. package/dist/generated/permission-labels.d.ts +3 -0
  48. package/dist/generated/permission-labels.js +17 -0
  49. package/dist/generated/version.d.ts +2 -0
  50. package/dist/generated/version.js +3 -0
  51. package/dist/host/index.d.ts +7 -0
  52. package/dist/host/index.js +5 -0
  53. package/dist/hosted/fetch.d.ts +53 -0
  54. package/dist/hosted/fetch.js +216 -0
  55. package/dist/hosted/index.d.ts +3 -0
  56. package/dist/hosted/index.js +81 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +13 -0
  59. package/dist/permissions.d.ts +11 -0
  60. package/dist/permissions.js +18 -0
  61. package/dist/plugin.d.ts +86 -0
  62. package/dist/plugin.js +26 -0
  63. package/dist/protocol.d.ts +167 -0
  64. package/dist/protocol.js +4 -0
  65. package/dist/runtime/connection.d.ts +52 -0
  66. package/dist/runtime/connection.js +132 -0
  67. package/dist/runtime/handles.d.ts +95 -0
  68. package/dist/runtime/handles.js +289 -0
  69. package/dist/runtime/memory-transport.d.ts +6 -0
  70. package/dist/runtime/memory-transport.js +39 -0
  71. package/dist/runtime/runtime.d.ts +57 -0
  72. package/dist/runtime/runtime.js +265 -0
  73. package/dist/runtime/scope.d.ts +25 -0
  74. package/dist/runtime/scope.js +94 -0
  75. package/dist/runtime/storage-runtime.d.ts +10 -0
  76. package/dist/runtime/storage-runtime.js +131 -0
  77. package/dist/settings.d.ts +111 -0
  78. package/dist/settings.js +78 -0
  79. package/dist/storage.d.ts +78 -0
  80. package/dist/storage.js +24 -0
  81. package/dist/testing/fake-container.d.ts +175 -0
  82. package/dist/testing/fake-container.js +483 -0
  83. package/dist/testing/index.d.ts +37 -0
  84. package/dist/testing/index.js +54 -0
  85. package/dist/types.d.ts +65 -0
  86. package/dist/types.js +54 -0
  87. package/llms.txt +11 -0
  88. package/package.json +60 -4
  89. package/src/api.ts +337 -0
  90. package/src/cli/api.ts +105 -0
  91. package/src/cli/build.ts +83 -0
  92. package/src/cli/check.ts +104 -0
  93. package/src/cli/config.ts +48 -0
  94. package/src/cli/create.ts +38 -0
  95. package/src/cli/deploy.ts +60 -0
  96. package/src/cli/dev-mcp.ts +131 -0
  97. package/src/cli/dev.ts +272 -0
  98. package/src/cli/fetch-guard.ts +61 -0
  99. package/src/cli/main.ts +120 -0
  100. package/src/cli/mcp.ts +168 -0
  101. package/src/cli/output.ts +30 -0
  102. package/src/cli/test.ts +38 -0
  103. package/src/errors.ts +34 -0
  104. package/src/generated/block-states.ts +892 -0
  105. package/src/generated/blocks.ts +1291 -0
  106. package/src/generated/contracts.ts +329 -0
  107. package/src/generated/effects.ts +45 -0
  108. package/src/generated/entities.ts +166 -0
  109. package/src/generated/items.ts +1663 -0
  110. package/src/generated/operations.ts +69 -0
  111. package/src/generated/permission-labels.ts +19 -0
  112. package/src/generated/version.ts +3 -0
  113. package/src/host/index.ts +9 -0
  114. package/src/hosted/fetch.ts +224 -0
  115. package/src/hosted/index.ts +121 -0
  116. package/src/index.ts +34 -0
  117. package/src/permissions.ts +23 -0
  118. package/src/plugin.ts +105 -0
  119. package/src/protocol.ts +107 -0
  120. package/src/runtime/connection.ts +167 -0
  121. package/src/runtime/handles.ts +337 -0
  122. package/src/runtime/memory-transport.ts +41 -0
  123. package/src/runtime/runtime.ts +281 -0
  124. package/src/runtime/scope.ts +101 -0
  125. package/src/runtime/storage-runtime.ts +138 -0
  126. package/src/settings.ts +118 -0
  127. package/src/storage.ts +82 -0
  128. package/src/testing/fake-container.ts +571 -0
  129. package/src/testing/index.ts +70 -0
  130. package/src/types.ts +88 -0
  131. package/templates/basic/AGENTS.md +32 -0
  132. package/templates/basic/README.md +14 -0
  133. package/templates/basic/gitignore +3 -0
  134. package/templates/basic/package.json +19 -0
  135. package/templates/basic/src/index.ts +20 -0
  136. package/templates/basic/test/plugin.test.ts +14 -0
  137. package/templates/basic/tsconfig.json +14 -0
package/src/cli/dev.ts ADDED
@@ -0,0 +1,272 @@
1
+ import { mkdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import * as esbuild from "esbuild";
4
+ import { PluginError } from "../errors.js";
5
+ import type { BotInfo, DevOptions } from "../protocol.js";
6
+ import type { Transport } from "../runtime/connection.js";
7
+ import { buildManifest, PluginRuntime, SDK_VERSION, type LogLevel } from "../runtime/runtime.js";
8
+ import { Scope } from "../runtime/scope.js";
9
+ import { devToken, listProfiles, type DevToken } from "./api.js";
10
+ import { devBuildOptions, findProject, formatErrors, loadPlugin } from "./build.js";
11
+ import { DEV_MCP_INSTRUCTIONS, DevLog, devTools, type DevSession } from "./dev-mcp.js";
12
+ import { guardFetch } from "./fetch-guard.js";
13
+ import { startMcpServer, type McpServer } from "./mcp.js";
14
+ import { bold, cyan, dim, fail, green, info, red, timestamp, warn, yellow } from "./output.js";
15
+
16
+ export interface DevArgs {
17
+ profile?: string;
18
+ bots: string[];
19
+ settingsFile?: string;
20
+ watch: boolean;
21
+ /** Port for the MCP endpoint (the next free one up to +9 is used), or null for none. */
22
+ mcpPort: number | null;
23
+ }
24
+
25
+ /** Rejections a reconnect can't fix: stop and tell the user what to do. */
26
+ const FINAL_REJECTIONS = new Set(["UnsupportedProtocol", "BadManifest", "WrongProfile", "PermissionsChanged", "FeatureDisabled"]);
27
+
28
+ /** Closes a reconnect would undo (`StopReason`): wait for the next rebuild instead. */
29
+ const NO_RECONNECT: Record<string, string> = {
30
+ Replaced: "Another copy of this plugin connected to the profile (minebot dev running somewhere else?)",
31
+ EndedByUser: "The session was ended from the dashboard",
32
+ };
33
+
34
+ class WebSocketTransport implements Transport {
35
+ onmessage: ((text: string) => void) | null = null;
36
+ onclose: ((code: number, reason: string) => void) | null = null;
37
+
38
+ constructor(private readonly socket: WebSocket) {
39
+ socket.onmessage = event => this.onmessage?.(typeof event.data === "string" ? event.data : String(event.data));
40
+ socket.onclose = event => this.onclose?.(event.code, event.reason);
41
+ }
42
+
43
+ send(text: string): void {
44
+ if (this.socket.readyState === WebSocket.OPEN) this.socket.send(text);
45
+ }
46
+
47
+ close(code = 1000, reason = ""): void {
48
+ this.socket.close(code, reason);
49
+ }
50
+
51
+ static open(url: string): Promise<WebSocketTransport> {
52
+ return new Promise((resolve, reject) => {
53
+ const socket = new WebSocket(url);
54
+ socket.onopen = () => resolve(new WebSocketTransport(socket));
55
+ socket.onerror = () => reject(new Error(`Couldn't connect to ${url}`));
56
+ });
57
+ }
58
+ }
59
+
60
+ async function pickProfile(requested: string | undefined): Promise<string> {
61
+ const profiles = await listProfiles();
62
+ if (profiles.length === 0) fail("You have no profiles.", "Create one on the dashboard first.");
63
+ if (requested) {
64
+ const match = profiles.find(p => p.id === requested || p.name.toLowerCase() === requested.toLowerCase());
65
+ if (!match) fail(`No profile "${requested}".`, `Yours: ${profiles.map(p => `"${p.name}"`).join(", ")}`);
66
+ return match.id;
67
+ }
68
+ const running = profiles.filter(p => p.running);
69
+ if (running.length === 1) return running[0].id;
70
+ const list = profiles.map(p => ` ${p.running ? green("running") : dim("stopped")} ${p.name} ${dim(p.id)}`).join("\n");
71
+ fail(running.length === 0 ? "None of your profiles is running." : "Several profiles are running; pick one with --profile.", `\n${list}\n minebot dev --profile "<name>"`);
72
+ }
73
+
74
+ function logLine(level: LogLevel, message: string, bot: BotInfo | null): void {
75
+ const who = bot ? cyan(bot.name || bot.id) : dim("profile");
76
+ const tag = level === "error" ? red("error") : level === "warn" ? yellow("warn ") : level === "debug" ? dim("debug") : "info ";
77
+ console.log(`${timestamp()} ${tag} ${who} ${message}`);
78
+ }
79
+
80
+ /**
81
+ * `minebot dev`: builds the plugin, runs it on your machine connected to one of your running profiles, and
82
+ * rebuilds and reconnects when a file changes. Your code, your profile: the manifest's permissions are granted
83
+ * without a prompt, and storage lives in a dev namespace apart from installed copies. An MCP endpoint lets an AI
84
+ * agent read the plugin's state and logs, look at its bots and reload it.
85
+ */
86
+ export async function dev(args: DevArgs): Promise<void> {
87
+ const project = findProject();
88
+ const outDir = join(project.root, ".minebot", "dev");
89
+ mkdirSync(outDir, { recursive: true });
90
+ const outfile = join(outDir, "plugin.mjs");
91
+ const settings = args.settingsFile ? (JSON.parse(readFileSync(args.settingsFile, "utf8")) as Record<string, unknown>) : {};
92
+ const devOptions: DevOptions = { bots: args.bots.length ? args.bots : null, settings };
93
+
94
+ const profileId = await pickProfile(args.profile);
95
+ let token: DevToken = await devToken(profileId);
96
+ info(`${bold(project.name)} → profile ${bold(token.profileName)} ${dim(`(${token.address})`)}`);
97
+
98
+ const log = new DevLog();
99
+ let runtime: PluginRuntime | null = null;
100
+ let generation = 0;
101
+ let unguard: (() => void) | null = null;
102
+ let stopping = false;
103
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
104
+ let state = "building";
105
+ let buildErrors: string | null = null;
106
+
107
+ // The reload tool waits for the next outcome: connected, refused, or a failed build or load.
108
+ let outcomeWaiters: ((outcome: string) => void)[] = [];
109
+ const settle = (outcome: string) => {
110
+ state = outcome;
111
+ log.add("system", outcome);
112
+ const waiters = outcomeWaiters;
113
+ outcomeWaiters = [];
114
+ for (const resolve of waiters) resolve(outcome);
115
+ };
116
+
117
+ const connect = async (attempt = 0): Promise<void> => {
118
+ const mine = ++generation;
119
+ if (retryTimer) clearTimeout(retryTimer);
120
+ if (new Date(token.expiresAt).getTime() - Date.now() < 10 * 60_000) token = await devToken(profileId);
121
+
122
+ let plugin;
123
+ try {
124
+ plugin = await loadPlugin(outfile, mine);
125
+ } catch (e) {
126
+ console.error(red(`The plugin failed to load: ${(e as Error).stack ?? e}`));
127
+ settle(`The plugin failed to load: ${(e as Error).stack ?? e}`);
128
+ return;
129
+ }
130
+
131
+ unguard?.();
132
+ unguard = guardFetch(buildManifest(plugin, project.version), () => runtime?.welcome.settings ?? settings);
133
+
134
+ const url = `${token.address.replace(/^http/, "ws").replace(/\/+$/, "")}/plugins/${profileId}`;
135
+ state = "connecting";
136
+ try {
137
+ const transport = await WebSocketTransport.open(url);
138
+ if (mine !== generation) return transport.close();
139
+ runtime = await PluginRuntime.connect(plugin, transport, token.token, project.version, {
140
+ onLog: (level, message, bot) => {
141
+ logLine(level, message, bot);
142
+ log.add(level, message, bot ? bot.name || bot.id : null);
143
+ },
144
+ onClosed: (code, reason) => {
145
+ if (stopping || mine !== generation) return;
146
+ if (NO_RECONNECT[reason]) {
147
+ warn(`${NO_RECONNECT[reason]}. ${args.watch ? "Save a file to connect again." : "Stopped."}`);
148
+ settle(`Disconnected: ${NO_RECONNECT[reason]}. Not reconnecting until the next rebuild.`);
149
+ if (!args.watch) void shutdown();
150
+ return;
151
+ }
152
+ warn(`Disconnected (${code}${reason ? `: ${reason}` : ""}); reconnecting…`);
153
+ settle(`Disconnected (${code}${reason ? `: ${reason}` : ""}); reconnecting`);
154
+ retryTimer = setTimeout(() => void connect(attempt + 1), Math.min(30_000, 1000 * 2 ** Math.min(attempt, 5)));
155
+ },
156
+ }, devOptions);
157
+ const enabled = runtime.welcome.bots.filter(b => b.enabled);
158
+ info(`${green("connected")} running on ${enabled.length ? enabled.map(b => cyan(b.name || b.id) + (b.connected ? "" : dim(" (offline)"))).join(", ") : yellow("no bots")}`);
159
+ settle(`Connected, running on ${enabled.length ? enabled.map(b => b.name || b.id).join(", ") : "no bots"}`);
160
+ attempt = 0;
161
+ } catch (e) {
162
+ if (e instanceof PluginError && FINAL_REJECTIONS.has(e.code)) {
163
+ settle(`Refused by the bot: ${e.message}`);
164
+ fail(`The bot refused the plugin: ${e.message}`);
165
+ }
166
+ if (e instanceof PluginError && e.code === "InvalidToken") token = await devToken(profileId);
167
+ if (stopping || mine !== generation) return;
168
+ warn(`${(e as Error).message}; retrying…`);
169
+ settle(`Not connected: ${(e as Error).message}; retrying`);
170
+ retryTimer = setTimeout(() => void connect(attempt + 1), Math.min(30_000, 1000 * 2 ** Math.min(attempt, 5)));
171
+ }
172
+ };
173
+
174
+ const reload = async () => {
175
+ const previous = runtime;
176
+ runtime = null;
177
+ previous?.close();
178
+ await connect();
179
+ };
180
+
181
+ const context = await esbuild.context({
182
+ ...devBuildOptions(project, outfile),
183
+ plugins: [{
184
+ name: "minebot-dev",
185
+ setup(build) {
186
+ let first = true;
187
+ build.onEnd(result => {
188
+ if (result.errors.length) {
189
+ buildErrors = formatErrors(result.errors);
190
+ console.error(red(`Build failed:\n${buildErrors}`));
191
+ settle(`Build failed:\n${buildErrors}`);
192
+ return;
193
+ }
194
+ buildErrors = null;
195
+ if (!first) info(dim("Rebuilt; restarting the plugin…"));
196
+ log.add("system", first ? "Built" : "Rebuilt; restarting the plugin");
197
+ first = false;
198
+ void reload();
199
+ });
200
+ },
201
+ }],
202
+ });
203
+
204
+ const session: DevSession = {
205
+ log,
206
+ status: () => ({
207
+ plugin: { name: project.name, version: project.version, folder: project.root },
208
+ profile: { id: profileId, name: token.profileName },
209
+ state,
210
+ build: buildErrors ? { ok: false, errors: buildErrors } : { ok: true },
211
+ bots: runtime ? runtime.currentBots.map(b => ({ ...b, running: runtime!.runningBots.includes(b.id) })) : [],
212
+ granted: runtime?.welcome.granted ?? [],
213
+ settings: runtime?.welcome.settings ?? settings,
214
+ limits: runtime?.welcome.limits,
215
+ }),
216
+ reload: async () => {
217
+ const outcome = new Promise<string>(resolve => outcomeWaiters.push(resolve));
218
+ await context.rebuild();
219
+ const timeout = new Promise<string>(resolve => setTimeout(() => resolve(`Still ${state} after 30 seconds`), 30_000).unref());
220
+ return { outcome: await Promise.race([outcome, timeout]), status: session.status() };
221
+ },
222
+ query: async (botName, op, opArgs) => {
223
+ const current = runtime;
224
+ if (!current) throw new Error(`The plugin is not connected (${state}).`);
225
+ let bot: string | null = null;
226
+ if (!op.startsWith("storage.")) {
227
+ const bots = current.currentBots;
228
+ const running = current.runningBots;
229
+ const match = botName
230
+ ? bots.find(b => b.id === botName || b.name.toLowerCase() === botName.toLowerCase())
231
+ : bots.find(b => running.includes(b.id));
232
+ if (!match) throw new Error(botName ? `No bot "${botName}". The profile's bots: ${bots.map(b => b.name || b.id).join(", ")}` : "The plugin is not running on any bot yet.");
233
+ bot = match.id;
234
+ }
235
+ const scope = new Scope();
236
+ try {
237
+ return await current.call(scope, bot, op, opArgs);
238
+ } finally {
239
+ scope.stop("Done");
240
+ }
241
+ },
242
+ };
243
+
244
+ let mcp: McpServer | null = null;
245
+ if (args.mcpPort !== null) {
246
+ try {
247
+ mcp = await startMcpServer(devTools(session), { port: args.mcpPort, name: "minebot-dev", version: SDK_VERSION, instructions: DEV_MCP_INSTRUCTIONS });
248
+ info(dim(`MCP for AI agents: ${mcp.url} (claude mcp add --transport http minebot-dev ${mcp.url})`));
249
+ } catch (e) {
250
+ warn(`No MCP endpoint: ${(e as Error).message}`);
251
+ }
252
+ }
253
+
254
+ const shutdown = async () => {
255
+ stopping = true;
256
+ if (retryTimer) clearTimeout(retryTimer);
257
+ runtime?.close();
258
+ await context.dispose();
259
+ await mcp?.close();
260
+ unguard?.();
261
+ process.exit(0);
262
+ };
263
+ process.on("SIGINT", () => void shutdown());
264
+ process.on("SIGTERM", () => void shutdown());
265
+
266
+ if (args.watch) {
267
+ await context.watch();
268
+ info(dim("Watching for changes. Ctrl+C stops."));
269
+ } else {
270
+ await context.rebuild();
271
+ }
272
+ }
@@ -0,0 +1,61 @@
1
+ import type { Manifest } from "../protocol.js";
2
+ import { networkHost } from "../permissions.js";
3
+ import { PluginError } from "../errors.js";
4
+
5
+ /**
6
+ * Applies the hosted runner's fetch rules under `minebot dev`, so a missing network permission fails on your
7
+ * machine exactly as it would hosted: HTTPS only, and only to declared hosts or the origin of a URL setting.
8
+ * (The hosted runner also blocks private addresses and limits sizes and rates; this guard doesn't need to.)
9
+ */
10
+ export function guardFetch(manifest: Manifest, settings: () => Record<string, unknown>): () => void {
11
+ const original = globalThis.fetch;
12
+ const hosts = manifest.permissions.map(networkHost).filter((h): h is string => h !== null);
13
+
14
+ const allowed = (url: URL): boolean => {
15
+ if (url.protocol !== "https:") return false;
16
+ const port = url.port || "443";
17
+ for (const entry of hosts) {
18
+ const [host, declaredPort = "443"] = entry.split(":");
19
+ if (declaredPort !== port) continue;
20
+ if (host.startsWith("*.") ? url.hostname.endsWith(host.slice(1)) && url.hostname !== host.slice(2) : url.hostname === host) return true;
21
+ }
22
+ for (const [key, schema] of Object.entries(manifest.settings)) {
23
+ if (schema.type !== "url") continue;
24
+ const value = settings()[key];
25
+ if (typeof value !== "string") continue;
26
+ try {
27
+ if (new URL(value).origin === url.origin) return true;
28
+ } catch {
29
+ // not a URL
30
+ }
31
+ }
32
+ return false;
33
+ };
34
+
35
+ const check = (url: URL) => {
36
+ if (url.protocol !== "https:") throw new PluginError("NetworkDenied", `fetch(${url.href}): only https:// is allowed`);
37
+ if (!allowed(url)) {
38
+ throw new PluginError("NetworkDenied", `fetch(${url.origin}): add Permission.network("${url.hostname}${url.port ? `:${url.port}` : ""}") to permissions in definePlugin`);
39
+ }
40
+ };
41
+
42
+ // Redirects are followed by hand so every hop is checked, as the runner does.
43
+ globalThis.fetch = async (input: string | URL | Request, init?: RequestInit) => {
44
+ let url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
45
+ let request: string | URL | Request = input;
46
+ let options: RequestInit | undefined = init;
47
+ for (let hop = 0; hop <= 5; hop++) {
48
+ check(url);
49
+ const response = await original(request, { ...options, redirect: "manual" });
50
+ const location = response.headers.get("location");
51
+ if (response.status < 300 || response.status >= 400 || !location) return response;
52
+ url = new URL(location, url);
53
+ request = url.href;
54
+ if (response.status === 303) options = { ...options, method: "GET", body: undefined };
55
+ }
56
+ throw new PluginError("NetworkDenied", `fetch: more than 5 redirects`);
57
+ };
58
+ return () => {
59
+ globalThis.fetch = original;
60
+ };
61
+ }
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ import { pollDevice, startDevice } from "./api.js";
3
+ import { build, check } from "./check.js";
4
+ import { apiUrl, deleteCredentials, readCredentials, saveCredentials } from "./config.js";
5
+ import { create } from "./create.js";
6
+ import { deploy } from "./deploy.js";
7
+ import { dev } from "./dev.js";
8
+ import { bold, cyan, dim, fail, green, info } from "./output.js";
9
+ import { test } from "./test.js";
10
+ import { SDK_VERSION } from "../runtime/runtime.js";
11
+
12
+ const HELP = `minebot ${SDK_VERSION}: write and run MineBot plugins
13
+
14
+ minebot create <folder> new plugin project
15
+ minebot login sign in (approve on the dashboard)
16
+ minebot logout forget the sign-in on this machine
17
+ minebot dev [options] run the plugin on your running profile, restarting on changes
18
+ --profile <name|id> which profile (default: your only running one)
19
+ --bot <name> run on this bot only (repeat for more; default: every bot)
20
+ --settings <file.json> setting values to use
21
+ --once don't watch for changes
22
+ --mcp-port <port> port of the MCP endpoint for AI agents (default 7788)
23
+ --no-mcp no MCP endpoint
24
+ minebot test run test/*.test.ts against a fake bot
25
+ minebot check what users will be asked to allow, bundle size, problems
26
+ minebot build write dist/plugin.js and dist/manifest.json
27
+ minebot deploy [options] upload the plugin so it runs on MineBot's servers, not your machine
28
+ --profile <name|id> run it on this profile from now on (it already runs where it did)
29
+ --bot <name> on this bot only (repeat for more; default: every bot)
30
+ --settings <file.json> setting values for that profile
31
+
32
+ Environment: MINEBOT_API_URL overrides the API (default ${apiUrl()}).`;
33
+
34
+ function option(args: string[], name: string): string | undefined {
35
+ const i = args.indexOf(name);
36
+ if (i < 0) return undefined;
37
+ const value = args[i + 1];
38
+ if (value === undefined || value.startsWith("--")) fail(`${name} needs a value.`);
39
+ return value;
40
+ }
41
+
42
+ function options(args: string[], name: string): string[] {
43
+ const values: string[] = [];
44
+ args.forEach((a, i) => {
45
+ if (a === name && args[i + 1] && !args[i + 1].startsWith("--")) values.push(args[i + 1]);
46
+ });
47
+ return values;
48
+ }
49
+
50
+ function port(value: string): number {
51
+ const n = Number(value);
52
+ if (!Number.isInteger(n) || n < 1 || n > 65535) fail(`${value} isn't a port.`);
53
+ return n;
54
+ }
55
+
56
+ async function login(): Promise<void> {
57
+ const device = await startDevice();
58
+ info(`Open ${cyan(device.verificationUrl)}`);
59
+ info(`and approve the code ${bold(device.userCode)}\n`);
60
+ const deadline = Date.now() + device.expiresIn * 1000;
61
+ while (Date.now() < deadline) {
62
+ await new Promise(r => setTimeout(r, device.interval * 1000));
63
+ const result = await pollDevice(device.deviceCode);
64
+ if (result.status === "approved" && result.token) {
65
+ const file = saveCredentials({ apiUrl: apiUrl(), token: result.token });
66
+ info(`${green("Signed in.")} ${dim(`(saved to ${file})`)}`);
67
+ return;
68
+ }
69
+ if (result.status === "denied") fail("The sign-in was denied on the dashboard.");
70
+ if (result.status === "expired") break;
71
+ }
72
+ fail("The code expired.", "Run `minebot login` again.");
73
+ }
74
+
75
+ async function main(argv: string[]): Promise<void> {
76
+ const [command, ...args] = argv;
77
+ switch (command) {
78
+ case "create":
79
+ return create(args[0], option(args, "--template"));
80
+ case "login":
81
+ return login();
82
+ case "logout":
83
+ deleteCredentials();
84
+ info("Signed out on this machine. Revoke the sign-in on the dashboard to end it everywhere.");
85
+ return;
86
+ case "whoami":
87
+ info(readCredentials() ? `Signed in to ${apiUrl()}` : "Not signed in.");
88
+ return;
89
+ case "dev":
90
+ return dev({
91
+ profile: option(args, "--profile"),
92
+ bots: options(args, "--bot"),
93
+ settingsFile: option(args, "--settings"),
94
+ watch: !args.includes("--once"),
95
+ mcpPort: args.includes("--no-mcp") ? null : port(option(args, "--mcp-port") ?? "7788"),
96
+ });
97
+ case "test":
98
+ return test(args);
99
+ case "check":
100
+ return check();
101
+ case "build":
102
+ return build();
103
+ case "deploy":
104
+ return deploy({ profile: option(args, "--profile"), bots: options(args, "--bot"), settingsFile: option(args, "--settings") });
105
+ case undefined:
106
+ case "help":
107
+ case "--help":
108
+ case "-h":
109
+ info(HELP);
110
+ return;
111
+ case "--version":
112
+ case "-v":
113
+ info(SDK_VERSION);
114
+ return;
115
+ default:
116
+ fail(`Unknown command ${command}.`, "Run `minebot help`.");
117
+ }
118
+ }
119
+
120
+ main(process.argv.slice(2)).catch(e => fail((e as Error).stack ?? String(e)));
package/src/cli/mcp.ts ADDED
@@ -0,0 +1,168 @@
1
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+ import type { AddressInfo } from "node:net";
3
+
4
+ /** A tool the MCP server offers. `run` returns JSON-able data; a thrown error becomes a tool error the agent sees. */
5
+ export interface McpTool {
6
+ name: string;
7
+ description: string;
8
+ inputSchema: Record<string, unknown>;
9
+ run(args: Record<string, unknown>): unknown;
10
+ }
11
+
12
+ export interface McpServerOptions {
13
+ /** First port to try; the next nine are tried if it is taken. 0 picks a free one. */
14
+ port: number;
15
+ name: string;
16
+ version: string;
17
+ instructions: string;
18
+ }
19
+
20
+ export interface McpServer {
21
+ readonly url: string;
22
+ close(): Promise<void>;
23
+ }
24
+
25
+ /** Newest first; an agent asking for one of these gets it, anything else gets the newest. */
26
+ const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
27
+ const MAX_BODY_BYTES = 1024 * 1024;
28
+
29
+ interface RpcMessage {
30
+ jsonrpc?: unknown;
31
+ id?: string | number | null;
32
+ method?: unknown;
33
+ params?: Record<string, unknown>;
34
+ }
35
+
36
+ const rpcError = (id: RpcMessage["id"], code: number, message: string) => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
37
+
38
+ /**
39
+ * A tools-only MCP server over streamable HTTP with JSON replies (no server-sent events): what `minebot dev`
40
+ * offers AI agents. It listens on 127.0.0.1 only and refuses a request whose Host or Origin names anything
41
+ * else, so a web page can't reach it through the browser (DNS rebinding, cross-site requests).
42
+ */
43
+ export async function startMcpServer(tools: McpTool[], options: McpServerOptions): Promise<McpServer> {
44
+ const byName = new Map(tools.map(t => [t.name, t]));
45
+ let port = 0;
46
+
47
+ const dispatch = async (message: RpcMessage): Promise<unknown> => {
48
+ if (!message || typeof message !== "object" || message.jsonrpc !== "2.0" || typeof message.method !== "string")
49
+ return rpcError(message?.id, -32600, "Invalid request");
50
+ const notification = message.id === undefined;
51
+ let result: unknown;
52
+ switch (message.method) {
53
+ case "initialize": {
54
+ const requested = message.params?.protocolVersion;
55
+ result = {
56
+ protocolVersion: PROTOCOL_VERSIONS.includes(requested as string) ? requested : PROTOCOL_VERSIONS[0],
57
+ capabilities: { tools: {} },
58
+ serverInfo: { name: options.name, version: options.version },
59
+ instructions: options.instructions,
60
+ };
61
+ break;
62
+ }
63
+ case "ping":
64
+ result = {};
65
+ break;
66
+ case "tools/list":
67
+ result = { tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) };
68
+ break;
69
+ case "tools/call": {
70
+ const tool = byName.get(String(message.params?.name));
71
+ if (!tool) return rpcError(message.id, -32602, `Unknown tool ${String(message.params?.name)}`);
72
+ const args = message.params?.arguments;
73
+ try {
74
+ const value = await tool.run(args && typeof args === "object" ? (args as Record<string, unknown>) : {});
75
+ result = { content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }] };
76
+ } catch (error) {
77
+ result = { content: [{ type: "text", text: (error as Error)?.message ?? String(error) }], isError: true };
78
+ }
79
+ break;
80
+ }
81
+ default:
82
+ if (notification) return null;
83
+ return rpcError(message.id, -32601, `Unknown method ${message.method}`);
84
+ }
85
+ return notification ? null : { jsonrpc: "2.0", id: message.id, result };
86
+ };
87
+
88
+ const reply = (res: ServerResponse, status: number, body?: unknown) => {
89
+ if (body === undefined) {
90
+ res.writeHead(status).end();
91
+ return;
92
+ }
93
+ res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body));
94
+ };
95
+
96
+ const readBody = (req: IncomingMessage) =>
97
+ new Promise<string>((resolve, reject) => {
98
+ const chunks: Buffer[] = [];
99
+ let size = 0;
100
+ req.on("data", (chunk: Buffer) => {
101
+ size += chunk.length;
102
+ if (size > MAX_BODY_BYTES) {
103
+ reject(new Error("Body too large"));
104
+ req.destroy();
105
+ } else chunks.push(chunk);
106
+ });
107
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
108
+ req.on("error", reject);
109
+ });
110
+
111
+ const handle = async (req: IncomingMessage, res: ServerResponse) => {
112
+ const allowed = [`127.0.0.1:${port}`, `localhost:${port}`];
113
+ const origin = req.headers.origin;
114
+ if (!allowed.includes(req.headers.host ?? "") || (origin !== undefined && !allowed.some(a => origin === `http://${a}`)))
115
+ return reply(res, 403, { error: "Only local MCP clients may connect" });
116
+ if ((req.url ?? "").split("?")[0] !== "/mcp") return reply(res, 404, { error: "The MCP endpoint is /mcp" });
117
+ if (req.method !== "POST") {
118
+ res.writeHead(405, { Allow: "POST" }).end();
119
+ return;
120
+ }
121
+
122
+ let body: unknown;
123
+ try {
124
+ body = JSON.parse(await readBody(req));
125
+ } catch {
126
+ return reply(res, 400, rpcError(null, -32700, "Parse error"));
127
+ }
128
+ const messages = (Array.isArray(body) ? body : [body]) as RpcMessage[];
129
+ const replies = (await Promise.all(messages.map(dispatch))).filter(r => r !== null);
130
+ if (replies.length === 0) return reply(res, 202);
131
+ reply(res, 200, Array.isArray(body) ? replies : replies[0]);
132
+ };
133
+
134
+ const server: Server = createServer((req, res) => {
135
+ handle(req, res).catch(error => {
136
+ if (!res.headersSent) reply(res, 500, rpcError(null, -32603, (error as Error).message));
137
+ });
138
+ });
139
+
140
+ const listen = (p: number) =>
141
+ new Promise<number>((resolve, reject) => {
142
+ const onError = (error: Error) => {
143
+ server.off("listening", onListening);
144
+ reject(error);
145
+ };
146
+ const onListening = () => {
147
+ server.off("error", onError);
148
+ resolve((server.address() as AddressInfo).port);
149
+ };
150
+ server.once("error", onError);
151
+ server.once("listening", onListening);
152
+ server.listen(p, "127.0.0.1");
153
+ });
154
+
155
+ for (let attempt = 0; ; attempt++) {
156
+ try {
157
+ port = await listen(options.port === 0 ? 0 : options.port + attempt);
158
+ break;
159
+ } catch (error) {
160
+ if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE" || options.port === 0 || attempt >= 9) throw error;
161
+ }
162
+ }
163
+
164
+ return {
165
+ url: `http://127.0.0.1:${port}/mcp`,
166
+ close: () => new Promise<void>(resolve => server.close(() => resolve())),
167
+ };
168
+ }
@@ -0,0 +1,30 @@
1
+ // Terminal output: colours when the terminal supports them, plain text otherwise (and for AI agents reading logs).
2
+
3
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
4
+ const wrap = (code: number) => (text: string) => (useColor ? `\x1b[${code}m${text}\x1b[0m` : text);
5
+
6
+ export const dim = wrap(2);
7
+ export const bold = wrap(1);
8
+ export const red = wrap(31);
9
+ export const green = wrap(32);
10
+ export const yellow = wrap(33);
11
+ export const cyan = wrap(36);
12
+
13
+ export function info(message: string): void {
14
+ console.log(message);
15
+ }
16
+
17
+ export function warn(message: string): void {
18
+ console.warn(yellow(`warning: ${message}`));
19
+ }
20
+
21
+ /** Prints an error with what to do next and exits with code 1. */
22
+ export function fail(message: string, fix?: string): never {
23
+ console.error(red(`error: ${message}`));
24
+ if (fix) console.error(` ${fix}`);
25
+ process.exit(1);
26
+ }
27
+
28
+ export function timestamp(): string {
29
+ return dim(new Date().toLocaleTimeString());
30
+ }