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