slatebox-mcp 0.1.0 → 0.3.2

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.
@@ -0,0 +1,90 @@
1
+ // The exec input checks and the exec result shape (exec-plan 6.1), shared by the local runner,
2
+ // the MCP tools and the CLI.
3
+
4
+ export class ExecInputError extends Error {
5
+ constructor(message, field) {
6
+ super(message);
7
+ this.code = "invalid_request";
8
+ this.status = 400;
9
+ if (field) this.details = { field };
10
+ }
11
+ }
12
+
13
+ const KEY = /^[!-~]{1,128}$/;
14
+ const CONFIRM = /^cf_[A-Za-z0-9]{24}$/;
15
+ export const EXEC_FIELDS = ["intent", "code", "mode", "confirm", "idempotencyKey"];
16
+
17
+ export function validateExecInput({ code, intent, mode = "save", confirm, idempotencyKey }) {
18
+ if (typeof intent !== "string" || intent.trim().length < 1 || intent.length > 200)
19
+ throw new ExecInputError("intent is one sentence of 1–200 characters a person can approve.", "intent");
20
+ if (!intent.isWellFormed()) throw new ExecInputError("intent must be well-formed text (it has a lone surrogate).", "intent");
21
+ if (typeof code !== "string" || code.length < 1 || code.length > 65536)
22
+ throw new ExecInputError("code is 1–65,536 characters of JavaScript or TypeScript.", "code");
23
+ if (!["save", "preview"].includes(mode)) throw new ExecInputError('mode is "save" or "preview".', "mode");
24
+ if (confirm !== undefined && (typeof confirm !== "string" || !CONFIRM.test(confirm)))
25
+ throw new ExecInputError("confirm is the cf_… id from a confirmation_required result.", "confirm");
26
+ if (idempotencyKey !== undefined && (typeof idempotencyKey !== "string" || !KEY.test(idempotencyKey)))
27
+ throw new ExecInputError("idempotencyKey is 1–128 printable characters without spaces.", "idempotencyKey");
28
+ }
29
+
30
+ function capLogs(lines, limit) {
31
+ const kept = [];
32
+ let size = 0;
33
+ for (const line of lines) {
34
+ const cost = Buffer.byteLength(line) + 1;
35
+ if (size + cost > limit) {
36
+ kept.push(`[logs cut at ${Math.round(limit / 1024)} KiB]`);
37
+ return kept;
38
+ }
39
+ kept.push(line);
40
+ size += cost;
41
+ }
42
+ return kept;
43
+ }
44
+
45
+ function countWrites(responses) {
46
+ let operations = 0;
47
+ let notesCreated = 0;
48
+ for (const { method, body } of responses) {
49
+ if (method.kind !== "write" || !Array.isArray(body?.operations)) continue;
50
+ operations += body.operations.length;
51
+ for (const op of body.operations)
52
+ if (op?.kind === "add_nodes") notesCreated += Array.isArray(op.nodes) ? op.nodes.length : Number.isInteger(op.count) ? op.count : 1;
53
+ }
54
+ return { operations, notesCreated };
55
+ }
56
+
57
+ export function assembleResult({ execId, mode, execKey, outcome, calls, responses, logs, held, limits, wallMs }) {
58
+ const result = { execId, status: "completed", mode, idempotencyKey: execKey };
59
+ if (held) {
60
+ result.status = "confirmation_required";
61
+ } else if (outcome.ok) {
62
+ if (outcome.json.length > limits.resultChars) {
63
+ result.result = outcome.json.slice(0, limits.resultChars);
64
+ result.truncated = { chars: outcome.json.length };
65
+ } else {
66
+ result.result = JSON.parse(outcome.json);
67
+ }
68
+ } else {
69
+ result.status = "failed";
70
+ const { code, message, line, column, status, details } = outcome.error;
71
+ result.error = { code, message, ...(Number.isInteger(line) ? { line } : {}), ...(Number.isInteger(column) ? { column } : {}),
72
+ ...(Number.isInteger(status) ? { status } : {}), ...(details !== undefined ? { details } : {}) };
73
+ }
74
+ result.logs = capLogs(logs, limits.logBytes);
75
+ result.calls = [...calls].sort((a, b) => a.n - b.n);
76
+ if (held) result.confirmation = held;
77
+ // cpuMs is measured by the sealed runner only; a local script shares this process's CPU.
78
+ result.usage = { calls: calls.length, maxCalls: limits.maxCalls, ...countWrites(responses), wallMs };
79
+ return result;
80
+ }
81
+
82
+ /** One line a person can read: "completed · 2 calls: slates.get 200, slates.applyOperations 201 save". */
83
+ export function summaryLine(result) {
84
+ const calls = result.calls ?? [];
85
+ const list = calls.map((c) => [c.method, c.status, c.mode].filter((x) => x !== null && x !== undefined).join(" ")).join(", ");
86
+ let line = `${result.status} · ${calls.length} call${calls.length === 1 ? "" : "s"}${list ? ": " + list : ""}`;
87
+ if (result.error) line += ` · ${result.error.code}: ${result.error.message}${result.error.line ? ` (line ${result.error.line})` : ""}`;
88
+ if (result.confirmation) line += ` · confirm ${result.confirmation.id}: ${result.confirmation.reasons.map((r) => r.rule).join(", ")}`;
89
+ return line;
90
+ }
@@ -0,0 +1,57 @@
1
+ // Runs one exec script in a child process of the MCP server or CLI, on the person's own
2
+ // machine. This is not a sandbox: the script has the person's rights, and can do anything the
3
+ // person's account can. The process exists so the parent can kill a stuck script, so the
4
+ // script's stdout and stderr are pipes the parent reads as logs (never the MCP stdio stream),
5
+ // and so a crash ends only this process.
6
+ //
7
+ // The generated prelude defines `slatebox`, `SlateboxError` and a buffering `console`, runs
8
+ // the caller's code and resolves to {ok:true, json, logs} or {ok:false, error, logs}. It needs
9
+ // one global, __slatebox.call(name, input), resolving to {ok:true,value} | {ok:false,error}.
10
+ import vm from "node:vm";
11
+
12
+ const pending = new Map();
13
+ let seq = 0;
14
+
15
+ const send = (message) => {
16
+ if (process.connected) process.send(message);
17
+ };
18
+
19
+ process.on("message", (message) => {
20
+ if (message?.t === "run") return void main(message.source);
21
+ if (message?.t !== "reply") return;
22
+ const resolve = pending.get(message.seq);
23
+ if (!resolve) return;
24
+ pending.delete(message.seq);
25
+ resolve(message.envelope);
26
+ });
27
+
28
+ Object.defineProperty(globalThis, "__slatebox", { enumerable: false, value: Object.freeze({
29
+ call(method, input) {
30
+ let plain;
31
+ try {
32
+ plain = JSON.parse(JSON.stringify(input ?? {}));
33
+ } catch (failure) {
34
+ return Promise.resolve({ ok: false, error: { code: "invalid_request", status: 400, message: `${method} input is not JSON: ${failure.message}` } });
35
+ }
36
+ seq += 1;
37
+ const n = seq;
38
+ return new Promise((resolve) => {
39
+ pending.set(n, resolve);
40
+ send({ t: "call", seq: n, method: String(method), input: plain });
41
+ });
42
+ },
43
+ }) });
44
+
45
+ async function main(source) {
46
+ let outcome;
47
+ try {
48
+ const script = new vm.Script(source, { filename: "run.js" });
49
+ outcome = await script.runInThisContext();
50
+ } catch (error) {
51
+ // A syntax error, or a failure the prelude does not catch. Line 1 is the prelude.
52
+ const at = /run\.js:(\d+)(?::(\d+))?/.exec(String(error?.stack ?? ""));
53
+ const line = at && Number(at[1]) > 1 ? { line: Number(at[1]) - 1, ...(at[2] ? { column: Number(at[2]) } : {}) } : {};
54
+ outcome = { ok: false, error: { code: "script_error", message: `${error?.name ?? "Error"}: ${error?.message ?? String(error)}`, ...line }, logs: [] };
55
+ }
56
+ send({ t: "done", outcome, inFlight: pending.size });
57
+ }
@@ -0,0 +1,29 @@
1
+ // Reads the files generated from the Slatebox action registry (exec-plan 3.3). The package
2
+ // never lists actions by hand: every client method, the exec and describe tool definitions,
3
+ // the rules, limits, recipes and the guest prelude come from here, so an action the app adds
4
+ // appears without a package edit.
5
+ import { readFileSync } from "node:fs";
6
+
7
+ const DEFAULT_DIR = new URL("../generated/", import.meta.url);
8
+
9
+ // guest-client.js declares `export const PRELUDE = "<json string>"` and TRAILER likewise.
10
+ function readConstant(text, name) {
11
+ const match = new RegExp(`export const ${name} = ("(?:[^"\\\\]|\\\\.)*")`).exec(text);
12
+ if (!match) throw new Error(`guest-client.js does not export ${name}.`);
13
+ return JSON.parse(match[1]);
14
+ }
15
+
16
+ export function loadGenerated(dir = DEFAULT_DIR) {
17
+ const read = (name) => readFileSync(new URL(name, dir), "utf8");
18
+ const manifest = JSON.parse(read("client.json"));
19
+ const tools = JSON.parse(read("exec-tool.json"));
20
+ const guest = read("guest-client.js");
21
+ const methods = new Map(manifest.methods.map((method) => [method.name, method]));
22
+ return { manifest, methods, tools, prelude: readConstant(guest, "PRELUDE"), trailer: readConstant(guest, "TRAILER") };
23
+ }
24
+
25
+ let cached;
26
+ export function defaultGenerated() {
27
+ cached ??= loadGenerated();
28
+ return cached;
29
+ }
@@ -0,0 +1,89 @@
1
+ // slatebox-mcp --http: the same two tools over Streamable HTTP, for agent hosts that connect by
2
+ // URL. A script runs in this process with no sandbox, so this listener answers only:
3
+ // - on loopback (127.0.0.1), never another interface;
4
+ // - requests whose Host and any Origin are loopback (no DNS rebinding from a web page);
5
+ // - requests that carry, as a bearer token, the Slatebox token this process was started with.
6
+ import { createHash, timingSafeEqual } from "node:crypto";
7
+ import { createServer } from "node:http";
8
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
9
+ import { UsageError } from "./client/index.js";
10
+
11
+ export const LOOPBACK_HOST = "127.0.0.1";
12
+ const BODY_LIMIT = 128 * 1024;
13
+ const LOOPBACK_NAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
14
+
15
+ const digest = (text) => createHash("sha256").update(String(text)).digest();
16
+ export function sameToken(given, expected) {
17
+ return typeof given === "string" && given.length > 0 && timingSafeEqual(digest(given), digest(expected));
18
+ }
19
+
20
+ function loopbackHost(value, port) {
21
+ if (!value) return false;
22
+ const match = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(value.toLowerCase());
23
+ return Boolean(match) && LOOPBACK_NAMES.has(match[1]) && (match[2] === undefined || Number(match[2]) === port);
24
+ }
25
+ function loopbackOrigin(value, port) {
26
+ try {
27
+ const url = new URL(value);
28
+ return url.protocol === "http:" && loopbackHost(url.host, port);
29
+ } catch { return false; }
30
+ }
31
+
32
+ const answer = (res, status, code, message, headers = {}) => {
33
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", ...headers });
34
+ res.end(JSON.stringify({ error: { code, message } }));
35
+ };
36
+
37
+ async function readJson(req) {
38
+ let size = 0;
39
+ const chunks = [];
40
+ for await (const chunk of req) {
41
+ size += chunk.length;
42
+ if (size > BODY_LIMIT) throw Object.assign(new Error("The request body is too large."), { status: 413, code: "payload_too_large" });
43
+ chunks.push(chunk);
44
+ }
45
+ try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); }
46
+ catch { throw Object.assign(new Error("The request body is not valid JSON."), { status: 400, code: "invalid_json" }); }
47
+ }
48
+
49
+ /**
50
+ * Start the loopback MCP listener. createServerForRequest() returns a fresh MCP server per
51
+ * request (stateless). Resolves with {server, port, url, close}.
52
+ */
53
+ export async function startHttp({ host = LOOPBACK_HOST, port = 0, token, createServerForRequest }) {
54
+ if (host !== LOOPBACK_HOST) throw new UsageError(`--http listens on ${LOOPBACK_HOST} only: a script runs on this machine with your rights.`);
55
+ if (!token) throw new UsageError("SLATEBOX_API_TOKEN is required.");
56
+ let bound = port;
57
+ const listener = createServer(async (req, res) => {
58
+ try {
59
+ if (!loopbackHost(req.headers.host, bound)) return answer(res, 403, "forbidden_host", "This listener answers loopback hosts only.");
60
+ if (req.headers.origin !== undefined && !loopbackOrigin(req.headers.origin, bound))
61
+ return answer(res, 403, "forbidden_origin", "This listener refuses requests from web pages.");
62
+ const auth = /^Bearer (.+)$/.exec(req.headers.authorization ?? "");
63
+ if (!auth || !sameToken(auth[1], token))
64
+ return answer(res, 401, "unauthorized", "Send the Slatebox token this listener was started with as a bearer token.", { "www-authenticate": "Bearer" });
65
+ const path = new URL(req.url, "http://" + LOOPBACK_HOST).pathname;
66
+ if (path !== "/mcp") return answer(res, 404, "unknown_route", "The MCP endpoint is /mcp.");
67
+ if (req.method !== "POST") return answer(res, 405, "method_not_allowed", "Use POST.", { allow: "POST" });
68
+ const body = await readJson(req);
69
+ const server = createServerForRequest();
70
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
71
+ res.on("close", () => { transport.close(); server.close(); });
72
+ await server.connect(transport);
73
+ await transport.handleRequest(req, res, body);
74
+ } catch (error) {
75
+ if (!res.headersSent) answer(res, error.status ?? 500, error.code ?? "internal_error", error.status ? error.message : "The request could not be completed.");
76
+ }
77
+ });
78
+ await new Promise((resolve, reject) => {
79
+ listener.once("error", reject);
80
+ listener.listen(port, host, resolve);
81
+ });
82
+ bound = listener.address().port;
83
+ return {
84
+ server: listener,
85
+ port: bound,
86
+ url: `http://${LOOPBACK_HOST}:${bound}/mcp`,
87
+ close: () => new Promise((resolve) => listener.close(resolve)),
88
+ };
89
+ }