sandkiln-mcp 0.1.0 → 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.
- package/README.md +7 -4
- package/dist/{chunk-6R5XGU7V.js → chunk-MPHLDLLV.js} +10 -3
- package/dist/chunk-MPHLDLLV.js.map +1 -0
- package/dist/chunk-YLVS6KTT.js +63 -0
- package/dist/chunk-YLVS6KTT.js.map +1 -0
- package/dist/errors.js +1 -1
- package/dist/exec-timeout.js +28 -0
- package/dist/exec-timeout.js.map +1 -0
- package/dist/index.js +39 -20
- package/dist/index.js.map +1 -1
- package/dist/session.js +1 -1
- package/dist/truncate.js +4 -57
- package/dist/truncate.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-6R5XGU7V.js.map +0 -1
- package/dist/timeout.js +0 -13
- package/dist/timeout.js.map +0 -1
package/README.md
CHANGED
|
@@ -63,7 +63,7 @@ Resources: `sandkiln://sandboxes` (live sandboxes) and `sandkiln://status`
|
|
|
63
63
|
(daemon health).
|
|
64
64
|
|
|
65
65
|
Failures come back as `isError` results with `{"error": {"kind", "message",
|
|
66
|
-
"status", "hint"}}`; `kind` is one of `invalid_request`, `unauthorized`,
|
|
66
|
+
"status", "hint", "details"}}`; `kind` is one of `invalid_request`, `unauthorized`,
|
|
67
67
|
`not_found`, `conflict`, `rate_limited`, `daemon_error`, `daemon_unreachable`,
|
|
68
68
|
`timeout`, `limit_reached`, `internal`. A command that exits nonzero is a normal
|
|
69
69
|
result, not an error.
|
|
@@ -77,9 +77,12 @@ result, not an error.
|
|
|
77
77
|
server cannot be intercepted, so those sandboxes remain until the daemon's
|
|
78
78
|
idle reaper or an operator removes them.
|
|
79
79
|
- Snapshots are durable by design and outlive the session.
|
|
80
|
-
- `sandbox_exec` has a
|
|
81
|
-
|
|
82
|
-
|
|
80
|
+
- `sandbox_exec` has a timeout enforced inside the sandbox (default 60 s, max
|
|
81
|
+
600 s, and never above the daemon's `exec_timeout_secs`). On expiry the
|
|
82
|
+
command and its child processes are killed and the call returns a `timeout`
|
|
83
|
+
error whose `details` hold the output captured so far, so nothing keeps
|
|
84
|
+
running. Against a daemon or guest agent that predates this, the limit is
|
|
85
|
+
not enforced in the guest.
|
|
83
86
|
- Any tool can act on any sandbox id on the daemon, not only the session's own.
|
|
84
87
|
Point the server at a daemon whose contents you are willing to expose to the
|
|
85
88
|
agent, and set `SANDKILN_AUTH_TOKEN` when the daemon is reachable by others.
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
// src/errors.ts
|
|
2
2
|
import { SandkilnApiError } from "sandkiln";
|
|
3
3
|
var ToolFailure = class extends Error {
|
|
4
|
-
constructor(kind, message, hint) {
|
|
4
|
+
constructor(kind, message, hint, details) {
|
|
5
5
|
super(message);
|
|
6
6
|
this.kind = kind;
|
|
7
7
|
this.hint = hint;
|
|
8
|
+
this.details = details;
|
|
8
9
|
}
|
|
9
10
|
kind;
|
|
10
11
|
hint;
|
|
12
|
+
details;
|
|
11
13
|
};
|
|
12
14
|
function fromStatus(status) {
|
|
13
15
|
if (status === 400 || status === 422) return { kind: "invalid_request", hint: "Check the arguments against the tool schema." };
|
|
@@ -19,7 +21,12 @@ function fromStatus(status) {
|
|
|
19
21
|
}
|
|
20
22
|
function toToolError(err, baseUrl) {
|
|
21
23
|
if (err instanceof ToolFailure) {
|
|
22
|
-
return {
|
|
24
|
+
return {
|
|
25
|
+
kind: err.kind,
|
|
26
|
+
message: err.message,
|
|
27
|
+
...err.hint ? { hint: err.hint } : {},
|
|
28
|
+
...err.details ? { details: err.details } : {}
|
|
29
|
+
};
|
|
23
30
|
}
|
|
24
31
|
if (err instanceof SandkilnApiError) {
|
|
25
32
|
const { kind, hint } = fromStatus(err.status);
|
|
@@ -39,4 +46,4 @@ export {
|
|
|
39
46
|
ToolFailure,
|
|
40
47
|
toToolError
|
|
41
48
|
};
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-MPHLDLLV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["import { SandkilnApiError } from \"sandkiln\";\n\n/** What a tool reports when it fails. Models act on `kind` and `hint`, so\n * these stay stable and short; `message` carries the daemon's own text. */\nexport interface ToolError {\n kind:\n | \"invalid_request\"\n | \"unauthorized\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limited\"\n | \"daemon_error\"\n | \"daemon_unreachable\"\n | \"timeout\"\n | \"limit_reached\"\n | \"internal\";\n message: string;\n status?: number;\n hint?: string;\n /** Extra structured fields for kinds that carry data, such as the partial output of a timed-out command. */\n details?: Record<string, unknown>;\n}\n\n/** Raised by this package's own guards (timeouts, session limits). */\nexport class ToolFailure extends Error {\n constructor(\n readonly kind: ToolError[\"kind\"],\n message: string,\n readonly hint?: string,\n readonly details?: Record<string, unknown>,\n ) {\n super(message);\n }\n}\n\nfunction fromStatus(status: number): { kind: ToolError[\"kind\"]; hint?: string } {\n if (status === 400 || status === 422) return { kind: \"invalid_request\", hint: \"Check the arguments against the tool schema.\" };\n if (status === 401 || status === 403) return { kind: \"unauthorized\", hint: \"The daemon rejected the credentials: check SANDKILN_AUTH_TOKEN.\" };\n if (status === 404) return { kind: \"not_found\", hint: \"The id does not exist. It may have been stopped or snapshotted; call sandbox_list or snapshot_list.\" };\n if (status === 409) return { kind: \"conflict\", hint: \"The resource is in a conflicting state, for example a snapshot that already has a live fork, or a name already taken.\" };\n if (status === 429) return { kind: \"rate_limited\", hint: \"The daemon is at capacity. Wait and retry, or stop sandboxes you no longer need.\" };\n return { kind: \"daemon_error\" };\n}\n\nexport function toToolError(err: unknown, baseUrl: string | undefined): ToolError {\n if (err instanceof ToolFailure) {\n return {\n kind: err.kind,\n message: err.message,\n ...(err.hint ? { hint: err.hint } : {}),\n ...(err.details ? { details: err.details } : {}),\n };\n }\n if (err instanceof SandkilnApiError) {\n const { kind, hint } = fromStatus(err.status);\n return { kind, message: err.message, status: err.status, ...(hint ? { hint } : {}) };\n }\n // fetch() rejects with a TypeError when the daemon cannot be reached at all.\n if (err instanceof TypeError && /fetch failed|network|ECONNREFUSED/i.test(`${err.message} ${String(err.cause ?? \"\")}`)) {\n return {\n kind: \"daemon_unreachable\",\n message: `could not reach the sandkiln daemon at ${baseUrl ?? \"the default address\"}`,\n hint: \"Check that sandkilnd is running and SANDKILN_DAEMON_URL points at it.\",\n };\n }\n return { kind: \"internal\", message: err instanceof Error ? err.message : String(err) };\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AAwB1B,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACW,MACT,SACS,MACA,SACT;AACA,UAAM,OAAO;AALJ;AAEA;AACA;AAAA,EAGX;AAAA,EANW;AAAA,EAEA;AAAA,EACA;AAIb;AAEA,SAAS,WAAW,QAA4D;AAC9E,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,EAAE,MAAM,mBAAmB,MAAM,+CAA+C;AAC7H,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,EAAE,MAAM,gBAAgB,MAAM,kEAAkE;AAC7I,MAAI,WAAW,IAAK,QAAO,EAAE,MAAM,aAAa,MAAM,sGAAsG;AAC5J,MAAI,WAAW,IAAK,QAAO,EAAE,MAAM,YAAY,MAAM,wHAAwH;AAC7K,MAAI,WAAW,IAAK,QAAO,EAAE,MAAM,gBAAgB,MAAM,mFAAmF;AAC5I,SAAO,EAAE,MAAM,eAAe;AAChC;AAEO,SAAS,YAAY,KAAc,SAAwC;AAChF,MAAI,eAAe,aAAa;AAC9B,WAAO;AAAA,MACL,MAAM,IAAI;AAAA,MACV,SAAS,IAAI;AAAA,MACb,GAAI,IAAI,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;AAAA,MACrC,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;AAAA,IAChD;AAAA,EACF;AACA,MAAI,eAAe,kBAAkB;AACnC,UAAM,EAAE,MAAM,KAAK,IAAI,WAAW,IAAI,MAAM;AAC5C,WAAO,EAAE,MAAM,SAAS,IAAI,SAAS,QAAQ,IAAI,QAAQ,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG;AAAA,EACrF;AAEA,MAAI,eAAe,aAAa,qCAAqC,KAAK,GAAG,IAAI,OAAO,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC,EAAE,GAAG;AACtH,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,0CAA0C,WAAW,qBAAqB;AAAA,MACnF,MAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO,EAAE,MAAM,YAAY,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE;AACvF;","names":[]}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// src/truncate.ts
|
|
2
|
+
var enc = new TextEncoder();
|
|
3
|
+
var dec = new TextDecoder("utf-8");
|
|
4
|
+
function safeEnd(bytes, end) {
|
|
5
|
+
let i = Math.min(end, bytes.length);
|
|
6
|
+
while (i > 0 && i < bytes.length && (bytes[i] & 192) === 128) i--;
|
|
7
|
+
return i;
|
|
8
|
+
}
|
|
9
|
+
function safeStart(bytes, start) {
|
|
10
|
+
let i = Math.max(start, 0);
|
|
11
|
+
while (i < bytes.length && (bytes[i] & 192) === 128) i++;
|
|
12
|
+
return i;
|
|
13
|
+
}
|
|
14
|
+
function truncateText(text, maxBytes) {
|
|
15
|
+
const bytes = enc.encode(text);
|
|
16
|
+
if (bytes.length <= maxBytes) {
|
|
17
|
+
return { text, truncated: false, totalBytes: bytes.length, omittedBytes: 0 };
|
|
18
|
+
}
|
|
19
|
+
const headBudget = Math.ceil(maxBytes / 2);
|
|
20
|
+
const tailBudget = maxBytes - headBudget;
|
|
21
|
+
const headEnd = safeEnd(bytes, headBudget);
|
|
22
|
+
const tailStart = safeStart(bytes, bytes.length - tailBudget);
|
|
23
|
+
const omitted = tailStart - headEnd;
|
|
24
|
+
const marker = `
|
|
25
|
+
[... ${omitted} bytes omitted of ${bytes.length} total ...]
|
|
26
|
+
`;
|
|
27
|
+
return {
|
|
28
|
+
text: dec.decode(bytes.subarray(0, headEnd)) + marker + dec.decode(bytes.subarray(tailStart)),
|
|
29
|
+
truncated: true,
|
|
30
|
+
totalBytes: bytes.length,
|
|
31
|
+
omittedBytes: omitted
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function decodeFile(bytes, maxBytes) {
|
|
35
|
+
const total = bytes.length;
|
|
36
|
+
const truncated = total > maxBytes;
|
|
37
|
+
let slice = truncated ? bytes.subarray(0, safeEnd(bytes, maxBytes)) : bytes;
|
|
38
|
+
let isText = !slice.includes(0);
|
|
39
|
+
if (isText) {
|
|
40
|
+
try {
|
|
41
|
+
new TextDecoder("utf-8", { fatal: true }).decode(slice);
|
|
42
|
+
} catch {
|
|
43
|
+
isText = false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (isText) {
|
|
47
|
+
return { encoding: "utf8", content: dec.decode(slice), totalBytes: total, returnedBytes: slice.length, truncated };
|
|
48
|
+
}
|
|
49
|
+
slice = truncated ? bytes.subarray(0, maxBytes) : bytes;
|
|
50
|
+
return {
|
|
51
|
+
encoding: "base64",
|
|
52
|
+
content: Buffer.from(slice).toString("base64"),
|
|
53
|
+
totalBytes: total,
|
|
54
|
+
returnedBytes: slice.length,
|
|
55
|
+
truncated
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export {
|
|
60
|
+
truncateText,
|
|
61
|
+
decodeFile
|
|
62
|
+
};
|
|
63
|
+
//# sourceMappingURL=chunk-YLVS6KTT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/truncate.ts"],"sourcesContent":["/** Output bounding. Everything returned to the model passes through here so\n * one noisy command or large file cannot flood its context window. */\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder(\"utf-8\");\n\nexport interface Truncated {\n text: string;\n truncated: boolean;\n /** Size of the original text in UTF-8 bytes. */\n totalBytes: number;\n omittedBytes: number;\n}\n\n/** Largest index <= `end` that does not split a UTF-8 sequence in `bytes`. */\nfunction safeEnd(bytes: Uint8Array, end: number): number {\n let i = Math.min(end, bytes.length);\n // A continuation byte (10xxxxxx) at `i` means the cut lands mid-character.\n while (i > 0 && i < bytes.length && (bytes[i]! & 0xc0) === 0x80) i--;\n return i;\n}\n\n/** Smallest index >= `start` that begins a UTF-8 sequence. */\nfunction safeStart(bytes: Uint8Array, start: number): number {\n let i = Math.max(start, 0);\n while (i < bytes.length && (bytes[i]! & 0xc0) === 0x80) i++;\n return i;\n}\n\n/** Keeps the head and tail of `text` within `maxBytes` and marks the gap.\n * Both ends matter for command output: the start shows what ran, the end\n * usually holds the error. */\nexport function truncateText(text: string, maxBytes: number): Truncated {\n const bytes = enc.encode(text);\n if (bytes.length <= maxBytes) {\n return { text, truncated: false, totalBytes: bytes.length, omittedBytes: 0 };\n }\n const headBudget = Math.ceil(maxBytes / 2);\n const tailBudget = maxBytes - headBudget;\n const headEnd = safeEnd(bytes, headBudget);\n const tailStart = safeStart(bytes, bytes.length - tailBudget);\n const omitted = tailStart - headEnd;\n const marker = `\\n[... ${omitted} bytes omitted of ${bytes.length} total ...]\\n`;\n return {\n text: dec.decode(bytes.subarray(0, headEnd)) + marker + dec.decode(bytes.subarray(tailStart)),\n truncated: true,\n totalBytes: bytes.length,\n omittedBytes: omitted,\n };\n}\n\nexport interface DecodedFile {\n encoding: \"utf8\" | \"base64\";\n content: string;\n totalBytes: number;\n returnedBytes: number;\n truncated: boolean;\n}\n\n/** Turns file bytes into a model-safe payload: UTF-8 text when the bytes\n * are valid text, base64 otherwise, cut to `maxBytes` of source data. */\nexport function decodeFile(bytes: Uint8Array, maxBytes: number): DecodedFile {\n const total = bytes.length;\n const truncated = total > maxBytes;\n let slice = truncated ? bytes.subarray(0, safeEnd(bytes, maxBytes)) : bytes;\n let isText = !slice.includes(0);\n if (isText) {\n try {\n new TextDecoder(\"utf-8\", { fatal: true }).decode(slice);\n } catch {\n isText = false;\n }\n }\n if (isText) {\n return { encoding: \"utf8\", content: dec.decode(slice), totalBytes: total, returnedBytes: slice.length, truncated };\n }\n // Binary content has no character boundaries, so cut at exactly maxBytes.\n slice = truncated ? bytes.subarray(0, maxBytes) : bytes;\n return {\n encoding: \"base64\",\n content: Buffer.from(slice).toString(\"base64\"),\n totalBytes: total,\n returnedBytes: slice.length,\n truncated,\n };\n}\n"],"mappings":";AAGA,IAAM,MAAM,IAAI,YAAY;AAC5B,IAAM,MAAM,IAAI,YAAY,OAAO;AAWnC,SAAS,QAAQ,OAAmB,KAAqB;AACvD,MAAI,IAAI,KAAK,IAAI,KAAK,MAAM,MAAM;AAElC,SAAO,IAAI,KAAK,IAAI,MAAM,WAAW,MAAM,CAAC,IAAK,SAAU,IAAM;AACjE,SAAO;AACT;AAGA,SAAS,UAAU,OAAmB,OAAuB;AAC3D,MAAI,IAAI,KAAK,IAAI,OAAO,CAAC;AACzB,SAAO,IAAI,MAAM,WAAW,MAAM,CAAC,IAAK,SAAU,IAAM;AACxD,SAAO;AACT;AAKO,SAAS,aAAa,MAAc,UAA6B;AACtE,QAAM,QAAQ,IAAI,OAAO,IAAI;AAC7B,MAAI,MAAM,UAAU,UAAU;AAC5B,WAAO,EAAE,MAAM,WAAW,OAAO,YAAY,MAAM,QAAQ,cAAc,EAAE;AAAA,EAC7E;AACA,QAAM,aAAa,KAAK,KAAK,WAAW,CAAC;AACzC,QAAM,aAAa,WAAW;AAC9B,QAAM,UAAU,QAAQ,OAAO,UAAU;AACzC,QAAM,YAAY,UAAU,OAAO,MAAM,SAAS,UAAU;AAC5D,QAAM,UAAU,YAAY;AAC5B,QAAM,SAAS;AAAA,OAAU,OAAO,qBAAqB,MAAM,MAAM;AAAA;AACjE,SAAO;AAAA,IACL,MAAM,IAAI,OAAO,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,SAAS,IAAI,OAAO,MAAM,SAAS,SAAS,CAAC;AAAA,IAC5F,WAAW;AAAA,IACX,YAAY,MAAM;AAAA,IAClB,cAAc;AAAA,EAChB;AACF;AAYO,SAAS,WAAW,OAAmB,UAA+B;AAC3E,QAAM,QAAQ,MAAM;AACpB,QAAM,YAAY,QAAQ;AAC1B,MAAI,QAAQ,YAAY,MAAM,SAAS,GAAG,QAAQ,OAAO,QAAQ,CAAC,IAAI;AACtE,MAAI,SAAS,CAAC,MAAM,SAAS,CAAC;AAC9B,MAAI,QAAQ;AACV,QAAI;AACF,UAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,OAAO,KAAK;AAAA,IACxD,QAAQ;AACN,eAAS;AAAA,IACX;AAAA,EACF;AACA,MAAI,QAAQ;AACV,WAAO,EAAE,UAAU,QAAQ,SAAS,IAAI,OAAO,KAAK,GAAG,YAAY,OAAO,eAAe,MAAM,QAAQ,UAAU;AAAA,EACnH;AAEA,UAAQ,YAAY,MAAM,SAAS,GAAG,QAAQ,IAAI;AAClD,SAAO;AAAA,IACL,UAAU;AAAA,IACV,SAAS,OAAO,KAAK,KAAK,EAAE,SAAS,QAAQ;AAAA,IAC7C,YAAY;AAAA,IACZ,eAAe,MAAM;AAAA,IACrB;AAAA,EACF;AACF;","names":[]}
|
package/dist/errors.js
CHANGED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import {
|
|
2
|
+
truncateText
|
|
3
|
+
} from "./chunk-YLVS6KTT.js";
|
|
4
|
+
import {
|
|
5
|
+
ToolFailure
|
|
6
|
+
} from "./chunk-MPHLDLLV.js";
|
|
7
|
+
|
|
8
|
+
// src/exec-timeout.ts
|
|
9
|
+
function execTimeoutFailure(err, outputBudgetBytes) {
|
|
10
|
+
const budget = Math.floor(outputBudgetBytes / 2);
|
|
11
|
+
const stdout = truncateText(err.stdout, budget);
|
|
12
|
+
const stderr = truncateText(err.stderr, budget);
|
|
13
|
+
return new ToolFailure(
|
|
14
|
+
"timeout",
|
|
15
|
+
`command did not finish within ${err.timeoutSeconds}s and was killed`,
|
|
16
|
+
"The command and its child processes were killed inside the sandbox, so nothing is left running. Raise timeout_seconds, or run it in the background (for example with nohup and output to a file) and poll.",
|
|
17
|
+
{
|
|
18
|
+
stdout: stdout.text,
|
|
19
|
+
stderr: stderr.text,
|
|
20
|
+
stdout_truncated: stdout.truncated,
|
|
21
|
+
stderr_truncated: stderr.truncated
|
|
22
|
+
}
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
execTimeoutFailure
|
|
27
|
+
};
|
|
28
|
+
//# sourceMappingURL=exec-timeout.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/exec-timeout.ts"],"sourcesContent":["import { SandkilnExecTimeoutError } from \"sandkiln\";\nimport { ToolFailure } from \"./errors.js\";\nimport { truncateText } from \"./truncate.js\";\n\n/** The tool error for a command the sandbox killed at `timeout_seconds`.\n * The partial output rides along (bounded like a normal result) because what\n * a command printed before it hung is usually the clue to why. */\nexport function execTimeoutFailure(err: SandkilnExecTimeoutError, outputBudgetBytes: number): ToolFailure {\n const budget = Math.floor(outputBudgetBytes / 2);\n const stdout = truncateText(err.stdout, budget);\n const stderr = truncateText(err.stderr, budget);\n return new ToolFailure(\n \"timeout\",\n `command did not finish within ${err.timeoutSeconds}s and was killed`,\n \"The command and its child processes were killed inside the sandbox, so nothing is left running. \" +\n \"Raise timeout_seconds, or run it in the background (for example with nohup and output to a file) and poll.\",\n {\n stdout: stdout.text,\n stderr: stderr.text,\n stdout_truncated: stdout.truncated,\n stderr_truncated: stderr.truncated,\n },\n );\n}\n"],"mappings":";;;;;;;;AAOO,SAAS,mBAAmB,KAA+B,mBAAwC;AACxG,QAAM,SAAS,KAAK,MAAM,oBAAoB,CAAC;AAC/C,QAAM,SAAS,aAAa,IAAI,QAAQ,MAAM;AAC9C,QAAM,SAAS,aAAa,IAAI,QAAQ,MAAM;AAC9C,SAAO,IAAI;AAAA,IACT;AAAA,IACA,iCAAiC,IAAI,cAAc;AAAA,IACnD;AAAA,IAEA;AAAA,MACE,QAAQ,OAAO;AAAA,MACf,QAAQ,OAAO;AAAA,MACf,kBAAkB,OAAO;AAAA,MACzB,kBAAkB,OAAO;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.js
CHANGED
|
@@ -72,13 +72,15 @@ function registerResources(server, ctx) {
|
|
|
72
72
|
// src/errors.ts
|
|
73
73
|
import { SandkilnApiError } from "sandkiln";
|
|
74
74
|
var ToolFailure = class extends Error {
|
|
75
|
-
constructor(kind, message, hint) {
|
|
75
|
+
constructor(kind, message, hint, details) {
|
|
76
76
|
super(message);
|
|
77
77
|
this.kind = kind;
|
|
78
78
|
this.hint = hint;
|
|
79
|
+
this.details = details;
|
|
79
80
|
}
|
|
80
81
|
kind;
|
|
81
82
|
hint;
|
|
83
|
+
details;
|
|
82
84
|
};
|
|
83
85
|
function fromStatus(status) {
|
|
84
86
|
if (status === 400 || status === 422) return { kind: "invalid_request", hint: "Check the arguments against the tool schema." };
|
|
@@ -90,7 +92,12 @@ function fromStatus(status) {
|
|
|
90
92
|
}
|
|
91
93
|
function toToolError(err, baseUrl) {
|
|
92
94
|
if (err instanceof ToolFailure) {
|
|
93
|
-
return {
|
|
95
|
+
return {
|
|
96
|
+
kind: err.kind,
|
|
97
|
+
message: err.message,
|
|
98
|
+
...err.hint ? { hint: err.hint } : {},
|
|
99
|
+
...err.details ? { details: err.details } : {}
|
|
100
|
+
};
|
|
94
101
|
}
|
|
95
102
|
if (err instanceof SandkilnApiError) {
|
|
96
103
|
const { kind, hint } = fromStatus(err.status);
|
|
@@ -157,6 +164,7 @@ var SandboxSession = class {
|
|
|
157
164
|
};
|
|
158
165
|
|
|
159
166
|
// src/tools/exec.ts
|
|
167
|
+
import { SandkilnExecTimeoutError } from "sandkiln";
|
|
160
168
|
import { z } from "zod";
|
|
161
169
|
|
|
162
170
|
// src/truncate.ts
|
|
@@ -217,14 +225,22 @@ function decodeFile(bytes, maxBytes) {
|
|
|
217
225
|
};
|
|
218
226
|
}
|
|
219
227
|
|
|
220
|
-
// src/timeout.ts
|
|
221
|
-
function
|
|
222
|
-
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
+
// src/exec-timeout.ts
|
|
229
|
+
function execTimeoutFailure(err, outputBudgetBytes) {
|
|
230
|
+
const budget = Math.floor(outputBudgetBytes / 2);
|
|
231
|
+
const stdout = truncateText(err.stdout, budget);
|
|
232
|
+
const stderr = truncateText(err.stderr, budget);
|
|
233
|
+
return new ToolFailure(
|
|
234
|
+
"timeout",
|
|
235
|
+
`command did not finish within ${err.timeoutSeconds}s and was killed`,
|
|
236
|
+
"The command and its child processes were killed inside the sandbox, so nothing is left running. Raise timeout_seconds, or run it in the background (for example with nohup and output to a file) and poll.",
|
|
237
|
+
{
|
|
238
|
+
stdout: stdout.text,
|
|
239
|
+
stderr: stderr.text,
|
|
240
|
+
stdout_truncated: stdout.truncated,
|
|
241
|
+
stderr_truncated: stderr.truncated
|
|
242
|
+
}
|
|
243
|
+
);
|
|
228
244
|
}
|
|
229
245
|
|
|
230
246
|
// src/tools/register.ts
|
|
@@ -268,21 +284,24 @@ function registerExecTools(server, ctx) {
|
|
|
268
284
|
command: z.string().min(1).describe("Executable to run, for example python3 or sh."),
|
|
269
285
|
args: z.array(z.string()).default([]).describe("Arguments, one array element each."),
|
|
270
286
|
env: z.record(z.string(), z.string()).optional().describe("Extra environment variables for this command only."),
|
|
271
|
-
timeout_seconds: z.number().int().min(1).max(MAX_EXEC_TIMEOUT_S).default(DEFAULT_EXEC_TIMEOUT_S).describe(
|
|
287
|
+
timeout_seconds: z.number().int().min(1).max(MAX_EXEC_TIMEOUT_S).default(DEFAULT_EXEC_TIMEOUT_S).describe(
|
|
288
|
+
"Wall-clock limit enforced inside the sandbox. On expiry the command and its child processes are killed and the call returns a timeout error carrying the output captured so far."
|
|
289
|
+
)
|
|
272
290
|
},
|
|
273
291
|
annotations: { title: "Run command in sandbox", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }
|
|
274
292
|
},
|
|
275
293
|
async (a) => {
|
|
276
294
|
const sandbox = attach(ctx, a.sandbox_id);
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
a.
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
)
|
|
285
|
-
|
|
295
|
+
let result;
|
|
296
|
+
try {
|
|
297
|
+
result = await sandbox.runCommand(a.command, a.args, {
|
|
298
|
+
...a.env ? { env: a.env } : {},
|
|
299
|
+
timeoutSeconds: a.timeout_seconds
|
|
300
|
+
});
|
|
301
|
+
} catch (err) {
|
|
302
|
+
if (err instanceof SandkilnExecTimeoutError) throw execTimeoutFailure(err, ctx.config.maxOutputBytes);
|
|
303
|
+
throw err;
|
|
304
|
+
}
|
|
286
305
|
const budget = Math.floor(ctx.config.maxOutputBytes / 2);
|
|
287
306
|
const stdout = truncateText(result.stdout, budget);
|
|
288
307
|
const stderr = truncateText(result.stderr, budget);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/server.ts","../src/resources.ts","../src/errors.ts","../src/session.ts","../src/tools/exec.ts","../src/truncate.ts","../src/timeout.ts","../src/tools/register.ts","../src/tools/files.ts","../src/tools/sandboxes.ts","../src/tools/snapshots.ts","../src/tools/status.ts"],"sourcesContent":["/** Entry point: stdio transport plus guaranteed cleanup.\n *\n * stdout carries the protocol, so every diagnostic goes to stderr. */\n\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { ConfigError, parseConfig } from \"./config.js\";\nimport { createServer } from \"./server.js\";\n\nconst CLEANUP_DEADLINE_MS = 15_000;\n\nasync function main(): Promise<void> {\n const config = parseConfig(process.env);\n const { server, session } = createServer(config);\n\n let shuttingDown = false;\n const shutdown = async (reason: string, code: number): Promise<void> => {\n if (shuttingDown) return;\n shuttingDown = true;\n const forced = setTimeout(() => process.exit(1), CLEANUP_DEADLINE_MS);\n forced.unref();\n const ids = session.ids();\n if (ids.length > 0) {\n const failed = await session.cleanup(config.keepOnExit);\n const verb = config.keepOnExit ? \"snapshotted\" : \"destroyed\";\n console.error(`sandkiln-mcp: ${reason}; ${ids.length - failed.length}/${ids.length} sandboxes ${verb}`);\n if (failed.length > 0) console.error(`sandkiln-mcp: could not stop: ${failed.join(\", \")}`);\n }\n await server.close().catch(() => undefined);\n process.exit(code);\n };\n\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\", 0));\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\", 0));\n process.stdin.on(\"end\", () => void shutdown(\"stdin closed\", 0));\n process.stdin.on(\"close\", () => void shutdown(\"stdin closed\", 0));\n\n await server.connect(new StdioServerTransport());\n console.error(`sandkiln-mcp ready (daemon ${config.baseUrl ?? \"default\"}, max ${config.maxSandboxes} sandboxes)`);\n}\n\nmain().catch((err: unknown) => {\n console.error(`sandkiln-mcp: ${err instanceof ConfigError ? err.message : err instanceof Error ? err.stack : String(err)}`);\n process.exit(1);\n});\n","/** Server settings, parsed from the environment. Pure so it is unit-testable. */\n\nexport interface McpConfig {\n /** Daemon URL; undefined lets the SDK fall back to its own default. */\n baseUrl: string | undefined;\n /** Bearer token; never logged or echoed in any tool result. */\n authToken: string | undefined;\n /** Cap on text returned to the model by any single tool call. */\n maxOutputBytes: number;\n /** Most sandboxes this session may have live at once. */\n maxSandboxes: number;\n /** When true, sandboxes still live at exit are stopped with `keep=true` (snapshotted) instead of destroyed. */\n keepOnExit: boolean;\n}\n\nexport const DEFAULT_MAX_OUTPUT_BYTES = 32 * 1024;\nexport const DEFAULT_MAX_SANDBOXES = 8;\n\nexport class ConfigError extends Error {}\n\nfunction positiveInt(env: NodeJS.ProcessEnv, key: string, fallback: number): number {\n const raw = env[key];\n if (raw === undefined || raw === \"\") return fallback;\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 1) {\n throw new ConfigError(`${key} must be a positive integer, got \"${raw}\"`);\n }\n return value;\n}\n\nfunction flag(env: NodeJS.ProcessEnv, key: string): boolean {\n const raw = env[key]?.toLowerCase();\n if (raw === undefined || raw === \"\" || raw === \"0\" || raw === \"false\") return false;\n if (raw === \"1\" || raw === \"true\") return true;\n throw new ConfigError(`${key} must be 1/true or 0/false, got \"${env[key]}\"`);\n}\n\nexport function parseConfig(env: NodeJS.ProcessEnv): McpConfig {\n return {\n baseUrl: env.SANDKILN_DAEMON_URL || undefined,\n authToken: env.SANDKILN_AUTH_TOKEN || undefined,\n maxOutputBytes: positiveInt(env, \"SANDKILN_MCP_MAX_OUTPUT_BYTES\", DEFAULT_MAX_OUTPUT_BYTES),\n maxSandboxes: positiveInt(env, \"SANDKILN_MCP_MAX_SANDBOXES\", DEFAULT_MAX_SANDBOXES),\n keepOnExit: flag(env, \"SANDKILN_MCP_KEEP_ON_EXIT\"),\n };\n}\n","/** Wires configuration, the session, tools and resources into one MCP server. */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox, SandkilnApiError } from \"sandkiln\";\nimport type { McpConfig } from \"./config.js\";\nimport { registerResources } from \"./resources.js\";\nimport { SandboxSession } from \"./session.js\";\nimport { registerExecTools } from \"./tools/exec.js\";\nimport { registerFileTools } from \"./tools/files.js\";\nimport type { ToolContext } from \"./tools/register.js\";\nimport { registerSandboxTools } from \"./tools/sandboxes.js\";\nimport { registerSnapshotTools } from \"./tools/snapshots.js\";\nimport { registerStatusTools } from \"./tools/status.js\";\n\nexport const SERVER_NAME = \"sandkiln-mcp\";\nexport const SERVER_VERSION = \"0.1.0\";\n\nconst INSTRUCTIONS =\n \"Tools for running untrusted or generated code in hardware-isolated sandkiln microVMs. \" +\n \"Typical flow: sandbox_create, then sandbox_exec / sandbox_write_file / sandbox_read_file, then sandbox_stop. \" +\n \"Stop sandboxes you no longer need; any still running when the session ends are stopped automatically.\";\n\nexport interface SandkilnMcp {\n server: McpServer;\n session: SandboxSession;\n}\n\nexport function createServer(config: McpConfig): SandkilnMcp {\n const client = {\n ...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl } : {}),\n ...(config.authToken !== undefined ? { authToken: config.authToken } : {}),\n };\n\n const session = new SandboxSession(config.maxSandboxes, async (id, keep) => {\n try {\n await Sandbox.attach(id, client).stop({ keep });\n } catch (err) {\n // Already gone (stopped by the model or reaped by the daemon) counts as cleaned up.\n if (!(err instanceof SandkilnApiError && err.status === 404)) throw err;\n }\n });\n\n const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: INSTRUCTIONS });\n const ctx: ToolContext = { config, session, client };\n registerSandboxTools(server, ctx);\n registerExecTools(server, ctx);\n registerFileTools(server, ctx);\n registerSnapshotTools(server, ctx);\n registerStatusTools(server, ctx);\n registerResources(server, ctx);\n return { server, session };\n}\n","/** Read-only resources: a client can attach these to context without a tool call. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox, getStatus } from \"sandkiln\";\nimport type { ToolContext } from \"./tools/register.js\";\n\nfunction json(uri: string, data: unknown) {\n return { contents: [{ uri, mimeType: \"application/json\", text: JSON.stringify(data, null, 2) }] };\n}\n\nexport function registerResources(server: McpServer, ctx: ToolContext): void {\n server.registerResource(\n \"sandboxes\",\n \"sandkiln://sandboxes\",\n { title: \"Live sandboxes\", description: \"Every live sandbox on the daemon, with tags and which ones this session created.\", mimeType: \"application/json\" },\n async (uri) => {\n const list = await Sandbox.list(ctx.client);\n return json(\n uri.href,\n list.map((s) => ({\n id: s.id,\n name: s.name ?? null,\n tags: s.tags,\n created_at: s.createdAt.toISOString(),\n created_by_this_session: ctx.session.owns(s.id),\n })),\n );\n },\n );\n\n server.registerResource(\n \"status\",\n \"sandkiln://status\",\n { title: \"Daemon status\", description: \"Daemon health, capacity and warnings.\", mimeType: \"application/json\" },\n async (uri) => json(uri.href, await getStatus(ctx.client)),\n );\n}\n","import { SandkilnApiError } from \"sandkiln\";\n\n/** What a tool reports when it fails. Models act on `kind` and `hint`, so\n * these stay stable and short; `message` carries the daemon's own text. */\nexport interface ToolError {\n kind:\n | \"invalid_request\"\n | \"unauthorized\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limited\"\n | \"daemon_error\"\n | \"daemon_unreachable\"\n | \"timeout\"\n | \"limit_reached\"\n | \"internal\";\n message: string;\n status?: number;\n hint?: string;\n}\n\n/** Raised by this package's own guards (timeouts, session limits). */\nexport class ToolFailure extends Error {\n constructor(\n readonly kind: ToolError[\"kind\"],\n message: string,\n readonly hint?: string,\n ) {\n super(message);\n }\n}\n\nfunction fromStatus(status: number): { kind: ToolError[\"kind\"]; hint?: string } {\n if (status === 400 || status === 422) return { kind: \"invalid_request\", hint: \"Check the arguments against the tool schema.\" };\n if (status === 401 || status === 403) return { kind: \"unauthorized\", hint: \"The daemon rejected the credentials: check SANDKILN_AUTH_TOKEN.\" };\n if (status === 404) return { kind: \"not_found\", hint: \"The id does not exist. It may have been stopped or snapshotted; call sandbox_list or snapshot_list.\" };\n if (status === 409) return { kind: \"conflict\", hint: \"The resource is in a conflicting state, for example a snapshot that already has a live fork, or a name already taken.\" };\n if (status === 429) return { kind: \"rate_limited\", hint: \"The daemon is at capacity. Wait and retry, or stop sandboxes you no longer need.\" };\n return { kind: \"daemon_error\" };\n}\n\nexport function toToolError(err: unknown, baseUrl: string | undefined): ToolError {\n if (err instanceof ToolFailure) {\n return { kind: err.kind, message: err.message, ...(err.hint ? { hint: err.hint } : {}) };\n }\n if (err instanceof SandkilnApiError) {\n const { kind, hint } = fromStatus(err.status);\n return { kind, message: err.message, status: err.status, ...(hint ? { hint } : {}) };\n }\n // fetch() rejects with a TypeError when the daemon cannot be reached at all.\n if (err instanceof TypeError && /fetch failed|network|ECONNREFUSED/i.test(`${err.message} ${String(err.cause ?? \"\")}`)) {\n return {\n kind: \"daemon_unreachable\",\n message: `could not reach the sandkiln daemon at ${baseUrl ?? \"the default address\"}`,\n hint: \"Check that sandkilnd is running and SANDKILN_DAEMON_URL points at it.\",\n };\n }\n return { kind: \"internal\", message: err instanceof Error ? err.message : String(err) };\n}\n","/** Ownership of the sandboxes this server instance created.\n *\n * The MCP client is an AI agent that may crash, loop, or simply forget to\n * clean up, so the server (not the model) is responsible for stopping what\n * it started when the connection ends. */\n\nimport { ToolFailure } from \"./errors.js\";\n\nexport interface Stopper {\n (id: string, keep: boolean): Promise<unknown>;\n}\n\nexport class SandboxSession {\n private readonly live = new Set<string>();\n\n constructor(\n private readonly maxSandboxes: number,\n private readonly stop: Stopper,\n ) {}\n\n /** Throws before the daemon is asked to boot anything over the cap. */\n assertCanCreate(): void {\n if (this.live.size >= this.maxSandboxes) {\n throw new ToolFailure(\n \"limit_reached\",\n `this session already has ${this.live.size} live sandboxes (limit ${this.maxSandboxes})`,\n \"Stop a sandbox with sandbox_stop first, or raise SANDKILN_MCP_MAX_SANDBOXES.\",\n );\n }\n }\n\n track(id: string): void {\n this.live.add(id);\n }\n\n /** Called when a sandbox stops or is retired by a snapshot. */\n forget(id: string): void {\n this.live.delete(id);\n }\n\n owns(id: string): boolean {\n return this.live.has(id);\n }\n\n ids(): string[] {\n return [...this.live];\n }\n\n /** Stops everything still tracked. One failure never blocks the rest;\n * returns the ids that could not be stopped. */\n async cleanup(keep: boolean): Promise<string[]> {\n const failed: string[] = [];\n await Promise.all(\n this.ids().map(async (id) => {\n try {\n await this.stop(id, keep);\n this.live.delete(id);\n } catch {\n failed.push(id);\n }\n }),\n );\n return failed;\n }\n}\n","/** Command execution tool. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { ToolFailure } from \"../errors.js\";\nimport { truncateText } from \"../truncate.js\";\nimport { withTimeout } from \"../timeout.js\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\nexport const DEFAULT_EXEC_TIMEOUT_S = 60;\nexport const MAX_EXEC_TIMEOUT_S = 600;\n\nexport function registerExecTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_exec\",\n {\n title: \"Run command in sandbox\",\n description:\n \"Run one command inside a sandbox and wait for it to finish. The command is executed directly, not through a shell: \" +\n \"to use pipes, redirects or globbing, call command=\\\"sh\\\" with args=[\\\"-c\\\", \\\"...\\\"]. \" +\n \"Returns stdout, stderr and the exit code; a nonzero exit code is a normal result, not a tool error. \" +\n \"Output beyond the size cap keeps its head and tail with a note in between.\",\n inputSchema: {\n sandbox_id: z.string().min(1).describe(\"Sandbox id from sandbox_create.\"),\n command: z.string().min(1).describe(\"Executable to run, for example python3 or sh.\"),\n args: z.array(z.string()).default([]).describe(\"Arguments, one array element each.\"),\n env: z.record(z.string(), z.string()).optional().describe(\"Extra environment variables for this command only.\"),\n timeout_seconds: z\n .number()\n .int()\n .min(1)\n .max(MAX_EXEC_TIMEOUT_S)\n .default(DEFAULT_EXEC_TIMEOUT_S)\n .describe(\"How long to wait. On expiry the call returns a timeout error but the process may keep running inside the sandbox.\"),\n },\n annotations: { title: \"Run command in sandbox\", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },\n },\n async (a) => {\n const sandbox = attach(ctx, a.sandbox_id);\n const result = await withTimeout(\n sandbox.runCommand(a.command, a.args, a.env ? { env: a.env } : {}),\n a.timeout_seconds * 1000,\n () =>\n new ToolFailure(\n \"timeout\",\n `command did not finish within ${a.timeout_seconds}s`,\n \"The process may still be running in the sandbox. Run it in the background (for example with nohup and output to a file) and poll, or raise timeout_seconds.\",\n ),\n );\n // The budget is split so that stdout and stderr together stay within the cap.\n const budget = Math.floor(ctx.config.maxOutputBytes / 2);\n const stdout = truncateText(result.stdout, budget);\n const stderr = truncateText(result.stderr, budget);\n return {\n exit_code: result.exitCode,\n stdout: stdout.text,\n stderr: stderr.text,\n stdout_truncated: stdout.truncated,\n stderr_truncated: stderr.truncated,\n stdout_total_bytes: stdout.totalBytes,\n stderr_total_bytes: stderr.totalBytes,\n };\n },\n );\n}\n","/** Output bounding. Everything returned to the model passes through here so\n * one noisy command or large file cannot flood its context window. */\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder(\"utf-8\");\n\nexport interface Truncated {\n text: string;\n truncated: boolean;\n /** Size of the original text in UTF-8 bytes. */\n totalBytes: number;\n omittedBytes: number;\n}\n\n/** Largest index <= `end` that does not split a UTF-8 sequence in `bytes`. */\nfunction safeEnd(bytes: Uint8Array, end: number): number {\n let i = Math.min(end, bytes.length);\n // A continuation byte (10xxxxxx) at `i` means the cut lands mid-character.\n while (i > 0 && i < bytes.length && (bytes[i]! & 0xc0) === 0x80) i--;\n return i;\n}\n\n/** Smallest index >= `start` that begins a UTF-8 sequence. */\nfunction safeStart(bytes: Uint8Array, start: number): number {\n let i = Math.max(start, 0);\n while (i < bytes.length && (bytes[i]! & 0xc0) === 0x80) i++;\n return i;\n}\n\n/** Keeps the head and tail of `text` within `maxBytes` and marks the gap.\n * Both ends matter for command output: the start shows what ran, the end\n * usually holds the error. */\nexport function truncateText(text: string, maxBytes: number): Truncated {\n const bytes = enc.encode(text);\n if (bytes.length <= maxBytes) {\n return { text, truncated: false, totalBytes: bytes.length, omittedBytes: 0 };\n }\n const headBudget = Math.ceil(maxBytes / 2);\n const tailBudget = maxBytes - headBudget;\n const headEnd = safeEnd(bytes, headBudget);\n const tailStart = safeStart(bytes, bytes.length - tailBudget);\n const omitted = tailStart - headEnd;\n const marker = `\\n[... ${omitted} bytes omitted of ${bytes.length} total ...]\\n`;\n return {\n text: dec.decode(bytes.subarray(0, headEnd)) + marker + dec.decode(bytes.subarray(tailStart)),\n truncated: true,\n totalBytes: bytes.length,\n omittedBytes: omitted,\n };\n}\n\nexport interface DecodedFile {\n encoding: \"utf8\" | \"base64\";\n content: string;\n totalBytes: number;\n returnedBytes: number;\n truncated: boolean;\n}\n\n/** Turns file bytes into a model-safe payload: UTF-8 text when the bytes\n * are valid text, base64 otherwise, cut to `maxBytes` of source data. */\nexport function decodeFile(bytes: Uint8Array, maxBytes: number): DecodedFile {\n const total = bytes.length;\n const truncated = total > maxBytes;\n let slice = truncated ? bytes.subarray(0, safeEnd(bytes, maxBytes)) : bytes;\n let isText = !slice.includes(0);\n if (isText) {\n try {\n new TextDecoder(\"utf-8\", { fatal: true }).decode(slice);\n } catch {\n isText = false;\n }\n }\n if (isText) {\n return { encoding: \"utf8\", content: dec.decode(slice), totalBytes: total, returnedBytes: slice.length, truncated };\n }\n // Binary content has no character boundaries, so cut at exactly maxBytes.\n slice = truncated ? bytes.subarray(0, maxBytes) : bytes;\n return {\n encoding: \"base64\",\n content: Buffer.from(slice).toString(\"base64\"),\n totalBytes: total,\n returnedBytes: slice.length,\n truncated,\n };\n}\n","/** Rejects with `onTimeout()` if `work` has not settled in `ms`. The work\n * itself is not cancelled (the SDK exposes no abort), only abandoned. */\nexport function withTimeout<T>(work: Promise<T>, ms: number, onTimeout: () => Error): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(onTimeout()), ms);\n });\n // Swallow a late rejection from the abandoned work so it cannot crash the process.\n work.catch(() => undefined);\n return Promise.race([work, timeout]).finally(() => clearTimeout(timer));\n}\n","/** The one place a tool handler becomes an MCP tool: validation comes from\n * the zod shape, and every thrown error is converted to a structured,\n * `isError` result so a failure never surfaces as a protocol error. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { CallToolResult, ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Sandbox, type SandboxOptions } from \"sandkiln\";\nimport type { z } from \"zod\";\nimport type { McpConfig } from \"../config.js\";\nimport { toToolError } from \"../errors.js\";\nimport type { SandboxSession } from \"../session.js\";\n\nexport interface ToolContext {\n config: McpConfig;\n session: SandboxSession;\n /** Connection options passed to every SDK call. */\n client: SandboxOptions;\n}\n\nexport function attach(ctx: ToolContext, id: string): Sandbox {\n return Sandbox.attach(id, ctx.client);\n}\n\nexport interface ToolSpec<S extends z.ZodRawShape> {\n title: string;\n description: string;\n inputSchema: S;\n annotations: ToolAnnotations;\n}\n\nexport function success(data: Record<string, unknown>): CallToolResult {\n return {\n content: [{ type: \"text\", text: JSON.stringify(data, null, 2) }],\n structuredContent: data,\n };\n}\n\nexport function failure(err: unknown, ctx: ToolContext): CallToolResult {\n const error = toToolError(err, ctx.config.baseUrl);\n return { isError: true, content: [{ type: \"text\", text: JSON.stringify({ error }, null, 2) }] };\n}\n\nexport function defineTool<S extends z.ZodRawShape>(\n server: McpServer,\n ctx: ToolContext,\n name: string,\n spec: ToolSpec<S>,\n handler: (args: z.infer<z.ZodObject<S>>) => Promise<Record<string, unknown>>,\n): void {\n server.registerTool(name, spec, (async (args: z.infer<z.ZodObject<S>>) => {\n try {\n return success(await handler(args));\n } catch (err) {\n return failure(err, ctx);\n }\n }) as never);\n}\n","/** Filesystem tools: write, read, list. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { ToolFailure } from \"../errors.js\";\nimport { decodeFile } from \"../truncate.js\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\n/** Writes above this are refused: they would travel through the model's context twice. */\nexport const MAX_WRITE_BYTES = 4 * 1024 * 1024;\nexport const MAX_LIST_ENTRIES = 500;\n\nconst sandboxId = z.string().min(1).describe(\"Sandbox id from sandbox_create.\");\nconst path = z.string().min(1).describe(\"Absolute path inside the sandbox.\");\n\nexport function registerFileTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_write_file\",\n {\n title: \"Write file in sandbox\",\n description: `Create or overwrite a file inside a sandbox. Content is UTF-8 text by default; use encoding=base64 for binary data. Limit ${MAX_WRITE_BYTES} bytes.`,\n inputSchema: {\n sandbox_id: sandboxId,\n path,\n content: z.string().describe(\"File content, interpreted per `encoding`.\"),\n encoding: z.enum([\"utf8\", \"base64\"]).default(\"utf8\").describe(\"How `content` is encoded.\"),\n },\n annotations: { title: \"Write file in sandbox\", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },\n },\n async (a) => {\n const bytes = a.encoding === \"base64\" ? Buffer.from(a.content, \"base64\") : Buffer.from(a.content, \"utf8\");\n if (bytes.length > MAX_WRITE_BYTES) {\n throw new ToolFailure(\"invalid_request\", `content is ${bytes.length} bytes, over the ${MAX_WRITE_BYTES} byte limit`);\n }\n await attach(ctx, a.sandbox_id).writeFile(a.path, bytes);\n return { path: a.path, bytes_written: bytes.length };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_read_file\",\n {\n title: \"Read file from sandbox\",\n description:\n \"Read a file from a sandbox. Text comes back as UTF-8; binary files come back base64 with encoding=base64. \" +\n \"Large files are cut to max_bytes and flagged as truncated.\",\n inputSchema: {\n sandbox_id: sandboxId,\n path,\n max_bytes: z.number().int().min(1).max(1024 * 1024).optional().describe(\"Most bytes of the file to return. Defaults to the server output cap.\"),\n },\n annotations: { title: \"Read file from sandbox\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const bytes = await attach(ctx, a.sandbox_id).readFile(a.path);\n const limit = Math.min(a.max_bytes ?? ctx.config.maxOutputBytes, 1024 * 1024);\n const file = decodeFile(bytes, limit);\n return {\n path: a.path,\n encoding: file.encoding,\n content: file.content,\n total_bytes: file.totalBytes,\n returned_bytes: file.returnedBytes,\n truncated: file.truncated,\n };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_list_dir\",\n {\n title: \"List directory in sandbox\",\n description: `List the entries of a directory inside a sandbox: name, type, size, mode and modification time. At most ${MAX_LIST_ENTRIES} entries are returned.`,\n inputSchema: { sandbox_id: sandboxId, path },\n annotations: { title: \"List directory in sandbox\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const entries = await attach(ctx, a.sandbox_id).listDir(a.path);\n return {\n path: a.path,\n total_entries: entries.length,\n truncated: entries.length > MAX_LIST_ENTRIES,\n entries: entries.slice(0, MAX_LIST_ENTRIES).map((e) => ({\n name: e.name,\n type: e.isSymlink ? \"symlink\" : e.isDir ? \"dir\" : \"file\",\n size: e.size,\n mode: e.mode.toString(8),\n modified_at: e.mtime.toISOString(),\n })),\n };\n },\n );\n}\n","/** Sandbox lifecycle tools: create, list, stop. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox } from \"sandkiln\";\nimport { z } from \"zod\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\nconst sandboxId = z.string().min(1).describe(\"Sandbox id returned by sandbox_create.\");\n\nexport function registerSandboxTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_create\",\n {\n title: \"Create sandbox\",\n description:\n \"Boot a new hardware-isolated microVM sandbox and return its id. Use it to run untrusted or generated code safely. \" +\n \"The sandbox is stopped automatically when this MCP session ends unless the server was configured to keep it. \" +\n \"Egress is unrestricted by default; use egress=deny_all for code that must not reach the network.\",\n inputSchema: {\n image: z.string().min(1).optional().describe(\"Registered image id to boot from. Omit for the default image.\"),\n vcpu: z.number().int().min(1).optional().describe(\"vCPU count. Omit for the daemon default; the daemon rejects values past its ceiling.\"),\n mem_mib: z.number().int().min(1).optional().describe(\"Memory in MiB. Omit for the daemon default.\"),\n name: z.string().min(1).optional().describe(\"Optional unique name for the sandbox.\"),\n tags: z.record(z.string(), z.string()).optional().describe(\"Key/value labels, usable to filter sandbox_list.\"),\n env: z.record(z.string(), z.string()).optional().describe(\"Environment variables set for every command in this sandbox.\"),\n egress: z\n .enum([\"allow_all\", \"deny_all\"])\n .optional()\n .describe(\"Outbound network mode. deny_all blocks all outbound traffic except what allow_cidrs permits.\"),\n allow_cidrs: z.array(z.string()).optional().describe(\"With egress=deny_all: CIDR ranges still reachable, for example 10.0.0.0/8.\"),\n },\n annotations: { title: \"Create sandbox\", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n ctx.session.assertCanCreate();\n const sandbox = await Sandbox.create({\n ...ctx.client,\n ...(a.image !== undefined ? { imageId: a.image } : {}),\n ...(a.vcpu !== undefined ? { vcpuCount: a.vcpu } : {}),\n ...(a.mem_mib !== undefined ? { memSizeMib: a.mem_mib } : {}),\n ...(a.name !== undefined ? { name: a.name } : {}),\n ...(a.tags !== undefined ? { tags: a.tags } : {}),\n ...(a.env !== undefined ? { env: a.env } : {}),\n ...(a.egress !== undefined ? { egress: { mode: a.egress, ...(a.allow_cidrs ? { allowCidrs: a.allow_cidrs } : {}) } } : {}),\n });\n ctx.session.track(sandbox.id);\n return { sandbox_id: sandbox.id, stopped_on_exit: !ctx.config.keepOnExit };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_list\",\n {\n title: \"List sandboxes\",\n description: \"List live sandboxes on the daemon, optionally filtered by tags. Marks the ones created by this session.\",\n inputSchema: { tags: z.record(z.string(), z.string()).optional().describe(\"Only sandboxes carrying every given tag.\") },\n annotations: { title: \"List sandboxes\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const list = await Sandbox.list({ ...ctx.client, ...(a.tags ? { tags: a.tags } : {}) });\n return {\n count: list.length,\n sandboxes: list.map((s) => ({\n id: s.id,\n name: s.name ?? null,\n tags: s.tags,\n created_at: s.createdAt.toISOString(),\n created_by_this_session: ctx.session.owns(s.id),\n })),\n };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_stop\",\n {\n title: \"Stop sandbox\",\n description:\n \"Stop a sandbox. By default (keep=false) it is destroyed and its disk is discarded, which avoids leaking resources. \" +\n \"Pass keep=true to snapshot it first so it can be brought back with sandbox_resume.\",\n inputSchema: {\n sandbox_id: sandboxId,\n keep: z.boolean().default(false).describe(\"true: preserve state as a snapshot and return its id. false: destroy.\"),\n },\n annotations: { title: \"Stop sandbox\", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n const result = await attach(ctx, a.sandbox_id).stop({ keep: a.keep });\n ctx.session.forget(a.sandbox_id);\n return { sandbox_id: a.sandbox_id, kept: result.kept, snapshot_id: result.snapshotId };\n },\n );\n}\n","/** Snapshot tools: snapshot, list, resume, fork. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox } from \"sandkiln\";\nimport { z } from \"zod\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\nconst snapshotId = z.string().min(1).describe(\"Snapshot id from sandbox_snapshot or snapshot_list.\");\n\nexport function registerSnapshotTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_snapshot\",\n {\n title: \"Snapshot sandbox\",\n description:\n \"Freeze a sandbox's memory and disk into a snapshot and return its id. The sandbox itself is retired by this call \" +\n \"(its id stops working); bring the state back with sandbox_resume or sandbox_fork. Snapshots persist on the daemon after this session ends.\",\n inputSchema: { sandbox_id: z.string().min(1).describe(\"Sandbox id from sandbox_create.\") },\n annotations: { title: \"Snapshot sandbox\", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n const id = await attach(ctx, a.sandbox_id).snapshot();\n ctx.session.forget(a.sandbox_id);\n return { snapshot_id: id, retired_sandbox_id: a.sandbox_id };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"snapshot_list\",\n {\n title: \"List snapshots\",\n description: \"List held snapshots, with the live sandbox currently forked from each, if any.\",\n inputSchema: { source_sandbox_id: z.string().min(1).optional().describe(\"Only the snapshot taken from this sandbox id.\") },\n annotations: { title: \"List snapshots\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const list = await Sandbox.listSnapshots({ ...ctx.client, ...(a.source_sandbox_id ? { sourceSandboxId: a.source_sandbox_id } : {}) });\n return {\n count: list.length,\n snapshots: list.map((s) => ({\n id: s.id,\n source_sandbox_id: s.sourceSandboxId,\n name: s.name ?? null,\n tags: s.tags,\n created_at: s.createdAt.toISOString(),\n forked_into: s.forkedInto,\n })),\n };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_resume\",\n {\n title: \"Resume sandbox from snapshot\",\n description:\n \"Boot a sandbox from a snapshot, consuming the snapshot: it is gone afterwards. The resumed sandbox gets a new id \" +\n \"and is stopped when this session ends. Use sandbox_fork instead to keep the snapshot.\",\n inputSchema: { snapshot_id: snapshotId },\n annotations: { title: \"Resume sandbox from snapshot\", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n ctx.session.assertCanCreate();\n const sandbox = await Sandbox.resume(a.snapshot_id, ctx.client);\n ctx.session.track(sandbox.id);\n return { sandbox_id: sandbox.id, snapshot_consumed: true };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_fork\",\n {\n title: \"Fork sandbox from snapshot\",\n description:\n \"Boot a new sandbox from a snapshot without consuming it, so the same starting state can be explored again. \" +\n \"At most one live fork per snapshot exists at a time: a second fork fails with a conflict until the first is stopped.\",\n inputSchema: { snapshot_id: snapshotId },\n annotations: { title: \"Fork sandbox from snapshot\", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n ctx.session.assertCanCreate();\n const sandbox = await Sandbox.fork(a.snapshot_id, ctx.client);\n ctx.session.track(sandbox.id);\n return { sandbox_id: sandbox.id, snapshot_consumed: false };\n },\n );\n}\n","/** Daemon health tool. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { getStatus } from \"sandkiln\";\nimport { defineTool, type ToolContext } from \"./register.js\";\n\nexport function registerStatusTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"daemon_status\",\n {\n title: \"Daemon status\",\n description:\n \"Report sandkiln daemon health and capacity: version, uptime, live sandboxes, held snapshots, free network devices, disk headroom, and warnings to act on. \" +\n \"Call it first when a create fails to see whether the host is out of capacity.\",\n inputSchema: {},\n annotations: { title: \"Daemon status\", readOnlyHint: true, openWorldHint: false },\n },\n async () => ({ ...(await getStatus(ctx.client)) }),\n );\n}\n"],"mappings":";;;AAIA,SAAS,4BAA4B;;;ACW9B,IAAM,2BAA2B,KAAK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E,MAAM,CAAC,QAAiB;AAC7B,UAAQ,MAAM,iBAAiB,eAAe,cAAc,IAAI,UAAU,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,CAAC,EAAE;AAC1H,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Sandbox","SandkilnApiError","Sandbox","Sandbox","z","z","Sandbox","z","sandboxId","z","Sandbox","Sandbox","z","z","Sandbox","getStatus","getStatus","Sandbox","SandkilnApiError"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/server.ts","../src/resources.ts","../src/errors.ts","../src/session.ts","../src/tools/exec.ts","../src/truncate.ts","../src/exec-timeout.ts","../src/tools/register.ts","../src/tools/files.ts","../src/tools/sandboxes.ts","../src/tools/snapshots.ts","../src/tools/status.ts"],"sourcesContent":["/** Entry point: stdio transport plus guaranteed cleanup.\n *\n * stdout carries the protocol, so every diagnostic goes to stderr. */\n\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { ConfigError, parseConfig } from \"./config.js\";\nimport { createServer } from \"./server.js\";\n\nconst CLEANUP_DEADLINE_MS = 15_000;\n\nasync function main(): Promise<void> {\n const config = parseConfig(process.env);\n const { server, session } = createServer(config);\n\n let shuttingDown = false;\n const shutdown = async (reason: string, code: number): Promise<void> => {\n if (shuttingDown) return;\n shuttingDown = true;\n const forced = setTimeout(() => process.exit(1), CLEANUP_DEADLINE_MS);\n forced.unref();\n const ids = session.ids();\n if (ids.length > 0) {\n const failed = await session.cleanup(config.keepOnExit);\n const verb = config.keepOnExit ? \"snapshotted\" : \"destroyed\";\n console.error(`sandkiln-mcp: ${reason}; ${ids.length - failed.length}/${ids.length} sandboxes ${verb}`);\n if (failed.length > 0) console.error(`sandkiln-mcp: could not stop: ${failed.join(\", \")}`);\n }\n await server.close().catch(() => undefined);\n process.exit(code);\n };\n\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\", 0));\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\", 0));\n process.stdin.on(\"end\", () => void shutdown(\"stdin closed\", 0));\n process.stdin.on(\"close\", () => void shutdown(\"stdin closed\", 0));\n\n await server.connect(new StdioServerTransport());\n console.error(`sandkiln-mcp ready (daemon ${config.baseUrl ?? \"default\"}, max ${config.maxSandboxes} sandboxes)`);\n}\n\nmain().catch((err: unknown) => {\n console.error(`sandkiln-mcp: ${err instanceof ConfigError ? err.message : err instanceof Error ? err.stack : String(err)}`);\n process.exit(1);\n});\n","/** Server settings, parsed from the environment. Pure so it is unit-testable. */\n\nexport interface McpConfig {\n /** Daemon URL; undefined lets the SDK fall back to its own default. */\n baseUrl: string | undefined;\n /** Bearer token; never logged or echoed in any tool result. */\n authToken: string | undefined;\n /** Cap on text returned to the model by any single tool call. */\n maxOutputBytes: number;\n /** Most sandboxes this session may have live at once. */\n maxSandboxes: number;\n /** When true, sandboxes still live at exit are stopped with `keep=true` (snapshotted) instead of destroyed. */\n keepOnExit: boolean;\n}\n\nexport const DEFAULT_MAX_OUTPUT_BYTES = 32 * 1024;\nexport const DEFAULT_MAX_SANDBOXES = 8;\n\nexport class ConfigError extends Error {}\n\nfunction positiveInt(env: NodeJS.ProcessEnv, key: string, fallback: number): number {\n const raw = env[key];\n if (raw === undefined || raw === \"\") return fallback;\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 1) {\n throw new ConfigError(`${key} must be a positive integer, got \"${raw}\"`);\n }\n return value;\n}\n\nfunction flag(env: NodeJS.ProcessEnv, key: string): boolean {\n const raw = env[key]?.toLowerCase();\n if (raw === undefined || raw === \"\" || raw === \"0\" || raw === \"false\") return false;\n if (raw === \"1\" || raw === \"true\") return true;\n throw new ConfigError(`${key} must be 1/true or 0/false, got \"${env[key]}\"`);\n}\n\nexport function parseConfig(env: NodeJS.ProcessEnv): McpConfig {\n return {\n baseUrl: env.SANDKILN_DAEMON_URL || undefined,\n authToken: env.SANDKILN_AUTH_TOKEN || undefined,\n maxOutputBytes: positiveInt(env, \"SANDKILN_MCP_MAX_OUTPUT_BYTES\", DEFAULT_MAX_OUTPUT_BYTES),\n maxSandboxes: positiveInt(env, \"SANDKILN_MCP_MAX_SANDBOXES\", DEFAULT_MAX_SANDBOXES),\n keepOnExit: flag(env, \"SANDKILN_MCP_KEEP_ON_EXIT\"),\n };\n}\n","/** Wires configuration, the session, tools and resources into one MCP server. */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox, SandkilnApiError } from \"sandkiln\";\nimport type { McpConfig } from \"./config.js\";\nimport { registerResources } from \"./resources.js\";\nimport { SandboxSession } from \"./session.js\";\nimport { registerExecTools } from \"./tools/exec.js\";\nimport { registerFileTools } from \"./tools/files.js\";\nimport type { ToolContext } from \"./tools/register.js\";\nimport { registerSandboxTools } from \"./tools/sandboxes.js\";\nimport { registerSnapshotTools } from \"./tools/snapshots.js\";\nimport { registerStatusTools } from \"./tools/status.js\";\n\nexport const SERVER_NAME = \"sandkiln-mcp\";\nexport const SERVER_VERSION = \"0.1.0\";\n\nconst INSTRUCTIONS =\n \"Tools for running untrusted or generated code in hardware-isolated sandkiln microVMs. \" +\n \"Typical flow: sandbox_create, then sandbox_exec / sandbox_write_file / sandbox_read_file, then sandbox_stop. \" +\n \"Stop sandboxes you no longer need; any still running when the session ends are stopped automatically.\";\n\nexport interface SandkilnMcp {\n server: McpServer;\n session: SandboxSession;\n}\n\nexport function createServer(config: McpConfig): SandkilnMcp {\n const client = {\n ...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl } : {}),\n ...(config.authToken !== undefined ? { authToken: config.authToken } : {}),\n };\n\n const session = new SandboxSession(config.maxSandboxes, async (id, keep) => {\n try {\n await Sandbox.attach(id, client).stop({ keep });\n } catch (err) {\n // Already gone (stopped by the model or reaped by the daemon) counts as cleaned up.\n if (!(err instanceof SandkilnApiError && err.status === 404)) throw err;\n }\n });\n\n const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: INSTRUCTIONS });\n const ctx: ToolContext = { config, session, client };\n registerSandboxTools(server, ctx);\n registerExecTools(server, ctx);\n registerFileTools(server, ctx);\n registerSnapshotTools(server, ctx);\n registerStatusTools(server, ctx);\n registerResources(server, ctx);\n return { server, session };\n}\n","/** Read-only resources: a client can attach these to context without a tool call. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox, getStatus } from \"sandkiln\";\nimport type { ToolContext } from \"./tools/register.js\";\n\nfunction json(uri: string, data: unknown) {\n return { contents: [{ uri, mimeType: \"application/json\", text: JSON.stringify(data, null, 2) }] };\n}\n\nexport function registerResources(server: McpServer, ctx: ToolContext): void {\n server.registerResource(\n \"sandboxes\",\n \"sandkiln://sandboxes\",\n { title: \"Live sandboxes\", description: \"Every live sandbox on the daemon, with tags and which ones this session created.\", mimeType: \"application/json\" },\n async (uri) => {\n const list = await Sandbox.list(ctx.client);\n return json(\n uri.href,\n list.map((s) => ({\n id: s.id,\n name: s.name ?? null,\n tags: s.tags,\n created_at: s.createdAt.toISOString(),\n created_by_this_session: ctx.session.owns(s.id),\n })),\n );\n },\n );\n\n server.registerResource(\n \"status\",\n \"sandkiln://status\",\n { title: \"Daemon status\", description: \"Daemon health, capacity and warnings.\", mimeType: \"application/json\" },\n async (uri) => json(uri.href, await getStatus(ctx.client)),\n );\n}\n","import { SandkilnApiError } from \"sandkiln\";\n\n/** What a tool reports when it fails. Models act on `kind` and `hint`, so\n * these stay stable and short; `message` carries the daemon's own text. */\nexport interface ToolError {\n kind:\n | \"invalid_request\"\n | \"unauthorized\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limited\"\n | \"daemon_error\"\n | \"daemon_unreachable\"\n | \"timeout\"\n | \"limit_reached\"\n | \"internal\";\n message: string;\n status?: number;\n hint?: string;\n /** Extra structured fields for kinds that carry data, such as the partial output of a timed-out command. */\n details?: Record<string, unknown>;\n}\n\n/** Raised by this package's own guards (timeouts, session limits). */\nexport class ToolFailure extends Error {\n constructor(\n readonly kind: ToolError[\"kind\"],\n message: string,\n readonly hint?: string,\n readonly details?: Record<string, unknown>,\n ) {\n super(message);\n }\n}\n\nfunction fromStatus(status: number): { kind: ToolError[\"kind\"]; hint?: string } {\n if (status === 400 || status === 422) return { kind: \"invalid_request\", hint: \"Check the arguments against the tool schema.\" };\n if (status === 401 || status === 403) return { kind: \"unauthorized\", hint: \"The daemon rejected the credentials: check SANDKILN_AUTH_TOKEN.\" };\n if (status === 404) return { kind: \"not_found\", hint: \"The id does not exist. It may have been stopped or snapshotted; call sandbox_list or snapshot_list.\" };\n if (status === 409) return { kind: \"conflict\", hint: \"The resource is in a conflicting state, for example a snapshot that already has a live fork, or a name already taken.\" };\n if (status === 429) return { kind: \"rate_limited\", hint: \"The daemon is at capacity. Wait and retry, or stop sandboxes you no longer need.\" };\n return { kind: \"daemon_error\" };\n}\n\nexport function toToolError(err: unknown, baseUrl: string | undefined): ToolError {\n if (err instanceof ToolFailure) {\n return {\n kind: err.kind,\n message: err.message,\n ...(err.hint ? { hint: err.hint } : {}),\n ...(err.details ? { details: err.details } : {}),\n };\n }\n if (err instanceof SandkilnApiError) {\n const { kind, hint } = fromStatus(err.status);\n return { kind, message: err.message, status: err.status, ...(hint ? { hint } : {}) };\n }\n // fetch() rejects with a TypeError when the daemon cannot be reached at all.\n if (err instanceof TypeError && /fetch failed|network|ECONNREFUSED/i.test(`${err.message} ${String(err.cause ?? \"\")}`)) {\n return {\n kind: \"daemon_unreachable\",\n message: `could not reach the sandkiln daemon at ${baseUrl ?? \"the default address\"}`,\n hint: \"Check that sandkilnd is running and SANDKILN_DAEMON_URL points at it.\",\n };\n }\n return { kind: \"internal\", message: err instanceof Error ? err.message : String(err) };\n}\n","/** Ownership of the sandboxes this server instance created.\n *\n * The MCP client is an AI agent that may crash, loop, or simply forget to\n * clean up, so the server (not the model) is responsible for stopping what\n * it started when the connection ends. */\n\nimport { ToolFailure } from \"./errors.js\";\n\nexport interface Stopper {\n (id: string, keep: boolean): Promise<unknown>;\n}\n\nexport class SandboxSession {\n private readonly live = new Set<string>();\n\n constructor(\n private readonly maxSandboxes: number,\n private readonly stop: Stopper,\n ) {}\n\n /** Throws before the daemon is asked to boot anything over the cap. */\n assertCanCreate(): void {\n if (this.live.size >= this.maxSandboxes) {\n throw new ToolFailure(\n \"limit_reached\",\n `this session already has ${this.live.size} live sandboxes (limit ${this.maxSandboxes})`,\n \"Stop a sandbox with sandbox_stop first, or raise SANDKILN_MCP_MAX_SANDBOXES.\",\n );\n }\n }\n\n track(id: string): void {\n this.live.add(id);\n }\n\n /** Called when a sandbox stops or is retired by a snapshot. */\n forget(id: string): void {\n this.live.delete(id);\n }\n\n owns(id: string): boolean {\n return this.live.has(id);\n }\n\n ids(): string[] {\n return [...this.live];\n }\n\n /** Stops everything still tracked. One failure never blocks the rest;\n * returns the ids that could not be stopped. */\n async cleanup(keep: boolean): Promise<string[]> {\n const failed: string[] = [];\n await Promise.all(\n this.ids().map(async (id) => {\n try {\n await this.stop(id, keep);\n this.live.delete(id);\n } catch {\n failed.push(id);\n }\n }),\n );\n return failed;\n }\n}\n","/** Command execution tool. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { SandkilnExecTimeoutError } from \"sandkiln\";\nimport { z } from \"zod\";\nimport { execTimeoutFailure } from \"../exec-timeout.js\";\nimport { truncateText } from \"../truncate.js\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\nexport const DEFAULT_EXEC_TIMEOUT_S = 60;\nexport const MAX_EXEC_TIMEOUT_S = 600;\n\nexport function registerExecTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_exec\",\n {\n title: \"Run command in sandbox\",\n description:\n \"Run one command inside a sandbox and wait for it to finish. The command is executed directly, not through a shell: \" +\n \"to use pipes, redirects or globbing, call command=\\\"sh\\\" with args=[\\\"-c\\\", \\\"...\\\"]. \" +\n \"Returns stdout, stderr and the exit code; a nonzero exit code is a normal result, not a tool error. \" +\n \"Output beyond the size cap keeps its head and tail with a note in between.\",\n inputSchema: {\n sandbox_id: z.string().min(1).describe(\"Sandbox id from sandbox_create.\"),\n command: z.string().min(1).describe(\"Executable to run, for example python3 or sh.\"),\n args: z.array(z.string()).default([]).describe(\"Arguments, one array element each.\"),\n env: z.record(z.string(), z.string()).optional().describe(\"Extra environment variables for this command only.\"),\n timeout_seconds: z\n .number()\n .int()\n .min(1)\n .max(MAX_EXEC_TIMEOUT_S)\n .default(DEFAULT_EXEC_TIMEOUT_S)\n .describe(\n \"Wall-clock limit enforced inside the sandbox. On expiry the command and its child processes are killed and the call returns a timeout error carrying the output captured so far.\",\n ),\n },\n annotations: { title: \"Run command in sandbox\", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },\n },\n async (a) => {\n const sandbox = attach(ctx, a.sandbox_id);\n let result;\n try {\n result = await sandbox.runCommand(a.command, a.args, {\n ...(a.env ? { env: a.env } : {}),\n timeoutSeconds: a.timeout_seconds,\n });\n } catch (err) {\n if (err instanceof SandkilnExecTimeoutError) throw execTimeoutFailure(err, ctx.config.maxOutputBytes);\n throw err;\n }\n // The budget is split so that stdout and stderr together stay within the cap.\n const budget = Math.floor(ctx.config.maxOutputBytes / 2);\n const stdout = truncateText(result.stdout, budget);\n const stderr = truncateText(result.stderr, budget);\n return {\n exit_code: result.exitCode,\n stdout: stdout.text,\n stderr: stderr.text,\n stdout_truncated: stdout.truncated,\n stderr_truncated: stderr.truncated,\n stdout_total_bytes: stdout.totalBytes,\n stderr_total_bytes: stderr.totalBytes,\n };\n },\n );\n}\n","/** Output bounding. Everything returned to the model passes through here so\n * one noisy command or large file cannot flood its context window. */\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder(\"utf-8\");\n\nexport interface Truncated {\n text: string;\n truncated: boolean;\n /** Size of the original text in UTF-8 bytes. */\n totalBytes: number;\n omittedBytes: number;\n}\n\n/** Largest index <= `end` that does not split a UTF-8 sequence in `bytes`. */\nfunction safeEnd(bytes: Uint8Array, end: number): number {\n let i = Math.min(end, bytes.length);\n // A continuation byte (10xxxxxx) at `i` means the cut lands mid-character.\n while (i > 0 && i < bytes.length && (bytes[i]! & 0xc0) === 0x80) i--;\n return i;\n}\n\n/** Smallest index >= `start` that begins a UTF-8 sequence. */\nfunction safeStart(bytes: Uint8Array, start: number): number {\n let i = Math.max(start, 0);\n while (i < bytes.length && (bytes[i]! & 0xc0) === 0x80) i++;\n return i;\n}\n\n/** Keeps the head and tail of `text` within `maxBytes` and marks the gap.\n * Both ends matter for command output: the start shows what ran, the end\n * usually holds the error. */\nexport function truncateText(text: string, maxBytes: number): Truncated {\n const bytes = enc.encode(text);\n if (bytes.length <= maxBytes) {\n return { text, truncated: false, totalBytes: bytes.length, omittedBytes: 0 };\n }\n const headBudget = Math.ceil(maxBytes / 2);\n const tailBudget = maxBytes - headBudget;\n const headEnd = safeEnd(bytes, headBudget);\n const tailStart = safeStart(bytes, bytes.length - tailBudget);\n const omitted = tailStart - headEnd;\n const marker = `\\n[... ${omitted} bytes omitted of ${bytes.length} total ...]\\n`;\n return {\n text: dec.decode(bytes.subarray(0, headEnd)) + marker + dec.decode(bytes.subarray(tailStart)),\n truncated: true,\n totalBytes: bytes.length,\n omittedBytes: omitted,\n };\n}\n\nexport interface DecodedFile {\n encoding: \"utf8\" | \"base64\";\n content: string;\n totalBytes: number;\n returnedBytes: number;\n truncated: boolean;\n}\n\n/** Turns file bytes into a model-safe payload: UTF-8 text when the bytes\n * are valid text, base64 otherwise, cut to `maxBytes` of source data. */\nexport function decodeFile(bytes: Uint8Array, maxBytes: number): DecodedFile {\n const total = bytes.length;\n const truncated = total > maxBytes;\n let slice = truncated ? bytes.subarray(0, safeEnd(bytes, maxBytes)) : bytes;\n let isText = !slice.includes(0);\n if (isText) {\n try {\n new TextDecoder(\"utf-8\", { fatal: true }).decode(slice);\n } catch {\n isText = false;\n }\n }\n if (isText) {\n return { encoding: \"utf8\", content: dec.decode(slice), totalBytes: total, returnedBytes: slice.length, truncated };\n }\n // Binary content has no character boundaries, so cut at exactly maxBytes.\n slice = truncated ? bytes.subarray(0, maxBytes) : bytes;\n return {\n encoding: \"base64\",\n content: Buffer.from(slice).toString(\"base64\"),\n totalBytes: total,\n returnedBytes: slice.length,\n truncated,\n };\n}\n","import { SandkilnExecTimeoutError } from \"sandkiln\";\nimport { ToolFailure } from \"./errors.js\";\nimport { truncateText } from \"./truncate.js\";\n\n/** The tool error for a command the sandbox killed at `timeout_seconds`.\n * The partial output rides along (bounded like a normal result) because what\n * a command printed before it hung is usually the clue to why. */\nexport function execTimeoutFailure(err: SandkilnExecTimeoutError, outputBudgetBytes: number): ToolFailure {\n const budget = Math.floor(outputBudgetBytes / 2);\n const stdout = truncateText(err.stdout, budget);\n const stderr = truncateText(err.stderr, budget);\n return new ToolFailure(\n \"timeout\",\n `command did not finish within ${err.timeoutSeconds}s and was killed`,\n \"The command and its child processes were killed inside the sandbox, so nothing is left running. \" +\n \"Raise timeout_seconds, or run it in the background (for example with nohup and output to a file) and poll.\",\n {\n stdout: stdout.text,\n stderr: stderr.text,\n stdout_truncated: stdout.truncated,\n stderr_truncated: stderr.truncated,\n },\n );\n}\n","/** The one place a tool handler becomes an MCP tool: validation comes from\n * the zod shape, and every thrown error is converted to a structured,\n * `isError` result so a failure never surfaces as a protocol error. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { CallToolResult, ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Sandbox, type SandboxOptions } from \"sandkiln\";\nimport type { z } from \"zod\";\nimport type { McpConfig } from \"../config.js\";\nimport { toToolError } from \"../errors.js\";\nimport type { SandboxSession } from \"../session.js\";\n\nexport interface ToolContext {\n config: McpConfig;\n session: SandboxSession;\n /** Connection options passed to every SDK call. */\n client: SandboxOptions;\n}\n\nexport function attach(ctx: ToolContext, id: string): Sandbox {\n return Sandbox.attach(id, ctx.client);\n}\n\nexport interface ToolSpec<S extends z.ZodRawShape> {\n title: string;\n description: string;\n inputSchema: S;\n annotations: ToolAnnotations;\n}\n\nexport function success(data: Record<string, unknown>): CallToolResult {\n return {\n content: [{ type: \"text\", text: JSON.stringify(data, null, 2) }],\n structuredContent: data,\n };\n}\n\nexport function failure(err: unknown, ctx: ToolContext): CallToolResult {\n const error = toToolError(err, ctx.config.baseUrl);\n return { isError: true, content: [{ type: \"text\", text: JSON.stringify({ error }, null, 2) }] };\n}\n\nexport function defineTool<S extends z.ZodRawShape>(\n server: McpServer,\n ctx: ToolContext,\n name: string,\n spec: ToolSpec<S>,\n handler: (args: z.infer<z.ZodObject<S>>) => Promise<Record<string, unknown>>,\n): void {\n server.registerTool(name, spec, (async (args: z.infer<z.ZodObject<S>>) => {\n try {\n return success(await handler(args));\n } catch (err) {\n return failure(err, ctx);\n }\n }) as never);\n}\n","/** Filesystem tools: write, read, list. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { ToolFailure } from \"../errors.js\";\nimport { decodeFile } from \"../truncate.js\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\n/** Writes above this are refused: they would travel through the model's context twice. */\nexport const MAX_WRITE_BYTES = 4 * 1024 * 1024;\nexport const MAX_LIST_ENTRIES = 500;\n\nconst sandboxId = z.string().min(1).describe(\"Sandbox id from sandbox_create.\");\nconst path = z.string().min(1).describe(\"Absolute path inside the sandbox.\");\n\nexport function registerFileTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_write_file\",\n {\n title: \"Write file in sandbox\",\n description: `Create or overwrite a file inside a sandbox. Content is UTF-8 text by default; use encoding=base64 for binary data. Limit ${MAX_WRITE_BYTES} bytes.`,\n inputSchema: {\n sandbox_id: sandboxId,\n path,\n content: z.string().describe(\"File content, interpreted per `encoding`.\"),\n encoding: z.enum([\"utf8\", \"base64\"]).default(\"utf8\").describe(\"How `content` is encoded.\"),\n },\n annotations: { title: \"Write file in sandbox\", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },\n },\n async (a) => {\n const bytes = a.encoding === \"base64\" ? Buffer.from(a.content, \"base64\") : Buffer.from(a.content, \"utf8\");\n if (bytes.length > MAX_WRITE_BYTES) {\n throw new ToolFailure(\"invalid_request\", `content is ${bytes.length} bytes, over the ${MAX_WRITE_BYTES} byte limit`);\n }\n await attach(ctx, a.sandbox_id).writeFile(a.path, bytes);\n return { path: a.path, bytes_written: bytes.length };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_read_file\",\n {\n title: \"Read file from sandbox\",\n description:\n \"Read a file from a sandbox. Text comes back as UTF-8; binary files come back base64 with encoding=base64. \" +\n \"Large files are cut to max_bytes and flagged as truncated.\",\n inputSchema: {\n sandbox_id: sandboxId,\n path,\n max_bytes: z.number().int().min(1).max(1024 * 1024).optional().describe(\"Most bytes of the file to return. Defaults to the server output cap.\"),\n },\n annotations: { title: \"Read file from sandbox\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const bytes = await attach(ctx, a.sandbox_id).readFile(a.path);\n const limit = Math.min(a.max_bytes ?? ctx.config.maxOutputBytes, 1024 * 1024);\n const file = decodeFile(bytes, limit);\n return {\n path: a.path,\n encoding: file.encoding,\n content: file.content,\n total_bytes: file.totalBytes,\n returned_bytes: file.returnedBytes,\n truncated: file.truncated,\n };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_list_dir\",\n {\n title: \"List directory in sandbox\",\n description: `List the entries of a directory inside a sandbox: name, type, size, mode and modification time. At most ${MAX_LIST_ENTRIES} entries are returned.`,\n inputSchema: { sandbox_id: sandboxId, path },\n annotations: { title: \"List directory in sandbox\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const entries = await attach(ctx, a.sandbox_id).listDir(a.path);\n return {\n path: a.path,\n total_entries: entries.length,\n truncated: entries.length > MAX_LIST_ENTRIES,\n entries: entries.slice(0, MAX_LIST_ENTRIES).map((e) => ({\n name: e.name,\n type: e.isSymlink ? \"symlink\" : e.isDir ? \"dir\" : \"file\",\n size: e.size,\n mode: e.mode.toString(8),\n modified_at: e.mtime.toISOString(),\n })),\n };\n },\n );\n}\n","/** Sandbox lifecycle tools: create, list, stop. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox } from \"sandkiln\";\nimport { z } from \"zod\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\nconst sandboxId = z.string().min(1).describe(\"Sandbox id returned by sandbox_create.\");\n\nexport function registerSandboxTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_create\",\n {\n title: \"Create sandbox\",\n description:\n \"Boot a new hardware-isolated microVM sandbox and return its id. Use it to run untrusted or generated code safely. \" +\n \"The sandbox is stopped automatically when this MCP session ends unless the server was configured to keep it. \" +\n \"Egress is unrestricted by default; use egress=deny_all for code that must not reach the network.\",\n inputSchema: {\n image: z.string().min(1).optional().describe(\"Registered image id to boot from. Omit for the default image.\"),\n vcpu: z.number().int().min(1).optional().describe(\"vCPU count. Omit for the daemon default; the daemon rejects values past its ceiling.\"),\n mem_mib: z.number().int().min(1).optional().describe(\"Memory in MiB. Omit for the daemon default.\"),\n name: z.string().min(1).optional().describe(\"Optional unique name for the sandbox.\"),\n tags: z.record(z.string(), z.string()).optional().describe(\"Key/value labels, usable to filter sandbox_list.\"),\n env: z.record(z.string(), z.string()).optional().describe(\"Environment variables set for every command in this sandbox.\"),\n egress: z\n .enum([\"allow_all\", \"deny_all\"])\n .optional()\n .describe(\"Outbound network mode. deny_all blocks all outbound traffic except what allow_cidrs permits.\"),\n allow_cidrs: z.array(z.string()).optional().describe(\"With egress=deny_all: CIDR ranges still reachable, for example 10.0.0.0/8.\"),\n },\n annotations: { title: \"Create sandbox\", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n ctx.session.assertCanCreate();\n const sandbox = await Sandbox.create({\n ...ctx.client,\n ...(a.image !== undefined ? { imageId: a.image } : {}),\n ...(a.vcpu !== undefined ? { vcpuCount: a.vcpu } : {}),\n ...(a.mem_mib !== undefined ? { memSizeMib: a.mem_mib } : {}),\n ...(a.name !== undefined ? { name: a.name } : {}),\n ...(a.tags !== undefined ? { tags: a.tags } : {}),\n ...(a.env !== undefined ? { env: a.env } : {}),\n ...(a.egress !== undefined ? { egress: { mode: a.egress, ...(a.allow_cidrs ? { allowCidrs: a.allow_cidrs } : {}) } } : {}),\n });\n ctx.session.track(sandbox.id);\n return { sandbox_id: sandbox.id, stopped_on_exit: !ctx.config.keepOnExit };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_list\",\n {\n title: \"List sandboxes\",\n description: \"List live sandboxes on the daemon, optionally filtered by tags. Marks the ones created by this session.\",\n inputSchema: { tags: z.record(z.string(), z.string()).optional().describe(\"Only sandboxes carrying every given tag.\") },\n annotations: { title: \"List sandboxes\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const list = await Sandbox.list({ ...ctx.client, ...(a.tags ? { tags: a.tags } : {}) });\n return {\n count: list.length,\n sandboxes: list.map((s) => ({\n id: s.id,\n name: s.name ?? null,\n tags: s.tags,\n created_at: s.createdAt.toISOString(),\n created_by_this_session: ctx.session.owns(s.id),\n })),\n };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_stop\",\n {\n title: \"Stop sandbox\",\n description:\n \"Stop a sandbox. By default (keep=false) it is destroyed and its disk is discarded, which avoids leaking resources. \" +\n \"Pass keep=true to snapshot it first so it can be brought back with sandbox_resume.\",\n inputSchema: {\n sandbox_id: sandboxId,\n keep: z.boolean().default(false).describe(\"true: preserve state as a snapshot and return its id. false: destroy.\"),\n },\n annotations: { title: \"Stop sandbox\", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n const result = await attach(ctx, a.sandbox_id).stop({ keep: a.keep });\n ctx.session.forget(a.sandbox_id);\n return { sandbox_id: a.sandbox_id, kept: result.kept, snapshot_id: result.snapshotId };\n },\n );\n}\n","/** Snapshot tools: snapshot, list, resume, fork. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Sandbox } from \"sandkiln\";\nimport { z } from \"zod\";\nimport { attach, defineTool, type ToolContext } from \"./register.js\";\n\nconst snapshotId = z.string().min(1).describe(\"Snapshot id from sandbox_snapshot or snapshot_list.\");\n\nexport function registerSnapshotTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"sandbox_snapshot\",\n {\n title: \"Snapshot sandbox\",\n description:\n \"Freeze a sandbox's memory and disk into a snapshot and return its id. The sandbox itself is retired by this call \" +\n \"(its id stops working); bring the state back with sandbox_resume or sandbox_fork. Snapshots persist on the daemon after this session ends.\",\n inputSchema: { sandbox_id: z.string().min(1).describe(\"Sandbox id from sandbox_create.\") },\n annotations: { title: \"Snapshot sandbox\", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n const id = await attach(ctx, a.sandbox_id).snapshot();\n ctx.session.forget(a.sandbox_id);\n return { snapshot_id: id, retired_sandbox_id: a.sandbox_id };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"snapshot_list\",\n {\n title: \"List snapshots\",\n description: \"List held snapshots, with the live sandbox currently forked from each, if any.\",\n inputSchema: { source_sandbox_id: z.string().min(1).optional().describe(\"Only the snapshot taken from this sandbox id.\") },\n annotations: { title: \"List snapshots\", readOnlyHint: true, openWorldHint: false },\n },\n async (a) => {\n const list = await Sandbox.listSnapshots({ ...ctx.client, ...(a.source_sandbox_id ? { sourceSandboxId: a.source_sandbox_id } : {}) });\n return {\n count: list.length,\n snapshots: list.map((s) => ({\n id: s.id,\n source_sandbox_id: s.sourceSandboxId,\n name: s.name ?? null,\n tags: s.tags,\n created_at: s.createdAt.toISOString(),\n forked_into: s.forkedInto,\n })),\n };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_resume\",\n {\n title: \"Resume sandbox from snapshot\",\n description:\n \"Boot a sandbox from a snapshot, consuming the snapshot: it is gone afterwards. The resumed sandbox gets a new id \" +\n \"and is stopped when this session ends. Use sandbox_fork instead to keep the snapshot.\",\n inputSchema: { snapshot_id: snapshotId },\n annotations: { title: \"Resume sandbox from snapshot\", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n ctx.session.assertCanCreate();\n const sandbox = await Sandbox.resume(a.snapshot_id, ctx.client);\n ctx.session.track(sandbox.id);\n return { sandbox_id: sandbox.id, snapshot_consumed: true };\n },\n );\n\n defineTool(\n server,\n ctx,\n \"sandbox_fork\",\n {\n title: \"Fork sandbox from snapshot\",\n description:\n \"Boot a new sandbox from a snapshot without consuming it, so the same starting state can be explored again. \" +\n \"At most one live fork per snapshot exists at a time: a second fork fails with a conflict until the first is stopped.\",\n inputSchema: { snapshot_id: snapshotId },\n annotations: { title: \"Fork sandbox from snapshot\", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n },\n async (a) => {\n ctx.session.assertCanCreate();\n const sandbox = await Sandbox.fork(a.snapshot_id, ctx.client);\n ctx.session.track(sandbox.id);\n return { sandbox_id: sandbox.id, snapshot_consumed: false };\n },\n );\n}\n","/** Daemon health tool. */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { getStatus } from \"sandkiln\";\nimport { defineTool, type ToolContext } from \"./register.js\";\n\nexport function registerStatusTools(server: McpServer, ctx: ToolContext): void {\n defineTool(\n server,\n ctx,\n \"daemon_status\",\n {\n title: \"Daemon status\",\n description:\n \"Report sandkiln daemon health and capacity: version, uptime, live sandboxes, held snapshots, free network devices, disk headroom, and warnings to act on. \" +\n \"Call it first when a create fails to see whether the host is out of capacity.\",\n inputSchema: {},\n annotations: { title: \"Daemon status\", readOnlyHint: true, openWorldHint: false },\n },\n async () => ({ ...(await getStatus(ctx.client)) }),\n );\n}\n"],"mappings":";;;AAIA,SAAS,4BAA4B;;;ACW9B,IAAM,2BAA2B,KAAK;AAC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MAAM,GAAG,OAAO,MAAM,KAAK,SAAS,gBAAgB,CAAC,CAAC;AAC9D,UAAQ,MAAM,GAAG,SAAS,MAAM,KAAK,SAAS,gBAAgB,CAAC,CAAC;AAEhE,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAC/C,UAAQ,MAAM,8BAA8B,OAAO,WAAW,SAAS,SAAS,OAAO,YAAY,aAAa;AAClH;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAC7B,UAAQ,MAAM,iBAAiB,eAAe,cAAc,IAAI,UAAU,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,CAAC,EAAE;AAC1H,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Sandbox","SandkilnApiError","Sandbox","Sandbox","z","z","Sandbox","z","sandboxId","z","Sandbox","Sandbox","z","z","Sandbox","getStatus","getStatus","Sandbox","SandkilnApiError"]}
|
package/dist/session.js
CHANGED
package/dist/truncate.js
CHANGED
|
@@ -1,60 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
let i = Math.min(end, bytes.length);
|
|
6
|
-
while (i > 0 && i < bytes.length && (bytes[i] & 192) === 128) i--;
|
|
7
|
-
return i;
|
|
8
|
-
}
|
|
9
|
-
function safeStart(bytes, start) {
|
|
10
|
-
let i = Math.max(start, 0);
|
|
11
|
-
while (i < bytes.length && (bytes[i] & 192) === 128) i++;
|
|
12
|
-
return i;
|
|
13
|
-
}
|
|
14
|
-
function truncateText(text, maxBytes) {
|
|
15
|
-
const bytes = enc.encode(text);
|
|
16
|
-
if (bytes.length <= maxBytes) {
|
|
17
|
-
return { text, truncated: false, totalBytes: bytes.length, omittedBytes: 0 };
|
|
18
|
-
}
|
|
19
|
-
const headBudget = Math.ceil(maxBytes / 2);
|
|
20
|
-
const tailBudget = maxBytes - headBudget;
|
|
21
|
-
const headEnd = safeEnd(bytes, headBudget);
|
|
22
|
-
const tailStart = safeStart(bytes, bytes.length - tailBudget);
|
|
23
|
-
const omitted = tailStart - headEnd;
|
|
24
|
-
const marker = `
|
|
25
|
-
[... ${omitted} bytes omitted of ${bytes.length} total ...]
|
|
26
|
-
`;
|
|
27
|
-
return {
|
|
28
|
-
text: dec.decode(bytes.subarray(0, headEnd)) + marker + dec.decode(bytes.subarray(tailStart)),
|
|
29
|
-
truncated: true,
|
|
30
|
-
totalBytes: bytes.length,
|
|
31
|
-
omittedBytes: omitted
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
function decodeFile(bytes, maxBytes) {
|
|
35
|
-
const total = bytes.length;
|
|
36
|
-
const truncated = total > maxBytes;
|
|
37
|
-
let slice = truncated ? bytes.subarray(0, safeEnd(bytes, maxBytes)) : bytes;
|
|
38
|
-
let isText = !slice.includes(0);
|
|
39
|
-
if (isText) {
|
|
40
|
-
try {
|
|
41
|
-
new TextDecoder("utf-8", { fatal: true }).decode(slice);
|
|
42
|
-
} catch {
|
|
43
|
-
isText = false;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if (isText) {
|
|
47
|
-
return { encoding: "utf8", content: dec.decode(slice), totalBytes: total, returnedBytes: slice.length, truncated };
|
|
48
|
-
}
|
|
49
|
-
slice = truncated ? bytes.subarray(0, maxBytes) : bytes;
|
|
50
|
-
return {
|
|
51
|
-
encoding: "base64",
|
|
52
|
-
content: Buffer.from(slice).toString("base64"),
|
|
53
|
-
totalBytes: total,
|
|
54
|
-
returnedBytes: slice.length,
|
|
55
|
-
truncated
|
|
56
|
-
};
|
|
57
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
decodeFile,
|
|
3
|
+
truncateText
|
|
4
|
+
} from "./chunk-YLVS6KTT.js";
|
|
58
5
|
export {
|
|
59
6
|
decodeFile,
|
|
60
7
|
truncateText
|
package/dist/truncate.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sandkiln-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Model Context Protocol server that gives AI agents sandkiln microVM sandboxes as tools (stdio transport).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Sumit Kumar",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
30
|
-
"sandkiln": "0.
|
|
30
|
+
"sandkiln": "0.14.0",
|
|
31
31
|
"zod": "4.6.7"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["import { SandkilnApiError } from \"sandkiln\";\n\n/** What a tool reports when it fails. Models act on `kind` and `hint`, so\n * these stay stable and short; `message` carries the daemon's own text. */\nexport interface ToolError {\n kind:\n | \"invalid_request\"\n | \"unauthorized\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limited\"\n | \"daemon_error\"\n | \"daemon_unreachable\"\n | \"timeout\"\n | \"limit_reached\"\n | \"internal\";\n message: string;\n status?: number;\n hint?: string;\n}\n\n/** Raised by this package's own guards (timeouts, session limits). */\nexport class ToolFailure extends Error {\n constructor(\n readonly kind: ToolError[\"kind\"],\n message: string,\n readonly hint?: string,\n ) {\n super(message);\n }\n}\n\nfunction fromStatus(status: number): { kind: ToolError[\"kind\"]; hint?: string } {\n if (status === 400 || status === 422) return { kind: \"invalid_request\", hint: \"Check the arguments against the tool schema.\" };\n if (status === 401 || status === 403) return { kind: \"unauthorized\", hint: \"The daemon rejected the credentials: check SANDKILN_AUTH_TOKEN.\" };\n if (status === 404) return { kind: \"not_found\", hint: \"The id does not exist. It may have been stopped or snapshotted; call sandbox_list or snapshot_list.\" };\n if (status === 409) return { kind: \"conflict\", hint: \"The resource is in a conflicting state, for example a snapshot that already has a live fork, or a name already taken.\" };\n if (status === 429) return { kind: \"rate_limited\", hint: \"The daemon is at capacity. Wait and retry, or stop sandboxes you no longer need.\" };\n return { kind: \"daemon_error\" };\n}\n\nexport function toToolError(err: unknown, baseUrl: string | undefined): ToolError {\n if (err instanceof ToolFailure) {\n return { kind: err.kind, message: err.message, ...(err.hint ? { hint: err.hint } : {}) };\n }\n if (err instanceof SandkilnApiError) {\n const { kind, hint } = fromStatus(err.status);\n return { kind, message: err.message, status: err.status, ...(hint ? { hint } : {}) };\n }\n // fetch() rejects with a TypeError when the daemon cannot be reached at all.\n if (err instanceof TypeError && /fetch failed|network|ECONNREFUSED/i.test(`${err.message} ${String(err.cause ?? \"\")}`)) {\n return {\n kind: \"daemon_unreachable\",\n message: `could not reach the sandkiln daemon at ${baseUrl ?? \"the default address\"}`,\n hint: \"Check that sandkilnd is running and SANDKILN_DAEMON_URL points at it.\",\n };\n }\n return { kind: \"internal\", message: err instanceof Error ? err.message : String(err) };\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AAsB1B,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACW,MACT,SACS,MACT;AACA,UAAM,OAAO;AAJJ;AAEA;AAAA,EAGX;AAAA,EALW;AAAA,EAEA;AAIb;AAEA,SAAS,WAAW,QAA4D;AAC9E,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,EAAE,MAAM,mBAAmB,MAAM,+CAA+C;AAC7H,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,EAAE,MAAM,gBAAgB,MAAM,kEAAkE;AAC7I,MAAI,WAAW,IAAK,QAAO,EAAE,MAAM,aAAa,MAAM,sGAAsG;AAC5J,MAAI,WAAW,IAAK,QAAO,EAAE,MAAM,YAAY,MAAM,wHAAwH;AAC7K,MAAI,WAAW,IAAK,QAAO,EAAE,MAAM,gBAAgB,MAAM,mFAAmF;AAC5I,SAAO,EAAE,MAAM,eAAe;AAChC;AAEO,SAAS,YAAY,KAAc,SAAwC;AAChF,MAAI,eAAe,aAAa;AAC9B,WAAO,EAAE,MAAM,IAAI,MAAM,SAAS,IAAI,SAAS,GAAI,IAAI,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC,EAAG;AAAA,EACzF;AACA,MAAI,eAAe,kBAAkB;AACnC,UAAM,EAAE,MAAM,KAAK,IAAI,WAAW,IAAI,MAAM;AAC5C,WAAO,EAAE,MAAM,SAAS,IAAI,SAAS,QAAQ,IAAI,QAAQ,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG;AAAA,EACrF;AAEA,MAAI,eAAe,aAAa,qCAAqC,KAAK,GAAG,IAAI,OAAO,IAAI,OAAO,IAAI,SAAS,EAAE,CAAC,EAAE,GAAG;AACtH,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,0CAA0C,WAAW,qBAAqB;AAAA,MACnF,MAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO,EAAE,MAAM,YAAY,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE;AACvF;","names":[]}
|
package/dist/timeout.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
// src/timeout.ts
|
|
2
|
-
function withTimeout(work, ms, onTimeout) {
|
|
3
|
-
let timer;
|
|
4
|
-
const timeout = new Promise((_, reject) => {
|
|
5
|
-
timer = setTimeout(() => reject(onTimeout()), ms);
|
|
6
|
-
});
|
|
7
|
-
work.catch(() => void 0);
|
|
8
|
-
return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
|
|
9
|
-
}
|
|
10
|
-
export {
|
|
11
|
-
withTimeout
|
|
12
|
-
};
|
|
13
|
-
//# sourceMappingURL=timeout.js.map
|
package/dist/timeout.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/timeout.ts"],"sourcesContent":["/** Rejects with `onTimeout()` if `work` has not settled in `ms`. The work\n * itself is not cancelled (the SDK exposes no abort), only abandoned. */\nexport function withTimeout<T>(work: Promise<T>, ms: number, onTimeout: () => Error): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(onTimeout()), ms);\n });\n // Swallow a late rejection from the abandoned work so it cannot crash the process.\n work.catch(() => undefined);\n return Promise.race([work, timeout]).finally(() => clearTimeout(timer));\n}\n"],"mappings":";AAEO,SAAS,YAAe,MAAkB,IAAY,WAAoC;AAC/F,MAAI;AACJ,QAAM,UAAU,IAAI,QAAe,CAAC,GAAG,WAAW;AAChD,YAAQ,WAAW,MAAM,OAAO,UAAU,CAAC,GAAG,EAAE;AAAA,EAClD,CAAC;AAED,OAAK,MAAM,MAAM,MAAS;AAC1B,SAAO,QAAQ,KAAK,CAAC,MAAM,OAAO,CAAC,EAAE,QAAQ,MAAM,aAAa,KAAK,CAAC;AACxE;","names":[]}
|