@milaboratories/pl-mcp-server 53.0.0 → 53.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +31 -0
  2. package/dist/package.cjs +1 -1
  3. package/dist/package.js +1 -1
  4. package/dist/server-log.cjs +365 -0
  5. package/dist/server-log.cjs.map +1 -0
  6. package/dist/server-log.js +363 -0
  7. package/dist/server-log.js.map +1 -0
  8. package/dist/server.cjs +48 -16
  9. package/dist/server.cjs.map +1 -1
  10. package/dist/server.d.ts +12 -0
  11. package/dist/server.d.ts.map +1 -1
  12. package/dist/server.js +48 -16
  13. package/dist/server.js.map +1 -1
  14. package/dist/tools/await.cjs +3 -5
  15. package/dist/tools/await.cjs.map +1 -1
  16. package/dist/tools/await.js +4 -6
  17. package/dist/tools/await.js.map +1 -1
  18. package/dist/tools/block-action-context.cjs.map +1 -1
  19. package/dist/tools/block-action-context.js.map +1 -1
  20. package/dist/tools/block-params.cjs.map +1 -1
  21. package/dist/tools/block-params.js.map +1 -1
  22. package/dist/tools/block-state.cjs +1 -1
  23. package/dist/tools/block-state.cjs.map +1 -1
  24. package/dist/tools/block-state.js +2 -2
  25. package/dist/tools/block-state.js.map +1 -1
  26. package/dist/tools/blocks.cjs.map +1 -1
  27. package/dist/tools/blocks.js.map +1 -1
  28. package/dist/tools/connection.cjs.map +1 -1
  29. package/dist/tools/connection.js.map +1 -1
  30. package/dist/tools/data-query.cjs +1 -1
  31. package/dist/tools/data-query.cjs.map +1 -1
  32. package/dist/tools/data-query.js +2 -2
  33. package/dist/tools/data-query.js.map +1 -1
  34. package/dist/tools/logs.cjs.map +1 -1
  35. package/dist/tools/logs.js.map +1 -1
  36. package/dist/tools/ping.cjs.map +1 -1
  37. package/dist/tools/ping.js.map +1 -1
  38. package/dist/tools/projects.cjs.map +1 -1
  39. package/dist/tools/projects.js.map +1 -1
  40. package/dist/tools/sandbox.cjs +110 -8
  41. package/dist/tools/sandbox.cjs.map +1 -1
  42. package/dist/tools/sandbox.js +107 -9
  43. package/dist/tools/sandbox.js.map +1 -1
  44. package/dist/tools/screenshot.cjs +9 -1
  45. package/dist/tools/screenshot.cjs.map +1 -1
  46. package/dist/tools/screenshot.js +9 -1
  47. package/dist/tools/screenshot.js.map +1 -1
  48. package/dist/tools/types.cjs +29 -0
  49. package/dist/tools/types.cjs.map +1 -1
  50. package/dist/tools/types.js +27 -1
  51. package/dist/tools/types.js.map +1 -1
  52. package/dist/tools/ui-interaction.cjs.map +1 -1
  53. package/dist/tools/ui-interaction.js.map +1 -1
  54. package/package.json +2 -1
  55. package/src/server-log.test.ts +859 -0
  56. package/src/server-log.ts +495 -0
  57. package/src/server.logging.test.ts +380 -0
  58. package/src/server.request-failure.test.ts +49 -0
  59. package/src/server.ts +69 -16
  60. package/src/test/recording-logger.ts +33 -0
  61. package/src/tools/await.ts +7 -10
  62. package/src/tools/block-action-context.ts +2 -3
  63. package/src/tools/block-params.ts +2 -3
  64. package/src/tools/block-state.ts +5 -6
  65. package/src/tools/blocks.ts +2 -3
  66. package/src/tools/connection.ts +2 -3
  67. package/src/tools/data-query.ts +5 -6
  68. package/src/tools/logs.ts +2 -3
  69. package/src/tools/ping.ts +2 -3
  70. package/src/tools/projects.ts +2 -3
  71. package/src/tools/sandbox.test.ts +183 -0
  72. package/src/tools/sandbox.ts +126 -10
  73. package/src/tools/screenshot.ts +15 -4
  74. package/src/tools/types.test.ts +4 -3
  75. package/src/tools/types.ts +65 -2
  76. package/src/tools/ui-interaction.ts +2 -3
@@ -1,8 +1,7 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import type { BlockActionContextNode } from "@milaboratories/pl-middle-layer";
3
2
  import { z } from "zod";
4
3
  import { projectIdInput, blockIdInput } from "./ids";
5
- import type { ToolContext } from "./types";
4
+ import type { ToolContext, ToolRegistrar } from "./types";
6
5
  import { errorResult, hints, textResult } from "./types";
7
6
 
8
7
  /** An action context tree node as the tool returns it: cut to the requested depth and history. */
@@ -57,7 +56,7 @@ export function limitBlockActionContextTree(
57
56
  return limited;
58
57
  }
59
58
 
60
- export function registerBlockActionContextTools(server: McpServer, ctx: ToolContext): void {
59
+ export function registerBlockActionContextTools(server: ToolRegistrar, ctx: ToolContext): void {
61
60
  server.registerTool(
62
61
  "get_block_action_context",
63
62
  {
@@ -1,10 +1,9 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import { z } from "zod";
3
2
  import { projectIdInput, blockIdInput } from "./ids";
4
- import type { ToolContext } from "./types";
3
+ import type { ToolContext, ToolRegistrar } from "./types";
5
4
  import { hints, textResult } from "./types";
6
5
 
7
- export function registerBlockParamsTools(server: McpServer, ctx: ToolContext): void {
6
+ export function registerBlockParamsTools(server: ToolRegistrar, ctx: ToolContext): void {
8
7
  server.registerTool(
9
8
  "get_block_params",
10
9
  {
@@ -1,14 +1,13 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import { deriveDataFromStorage } from "@platforma-sdk/model";
3
2
  import { ModelAPIVersionMismatchError } from "@milaboratories/pl-errors";
4
3
  import { z } from "zod";
5
4
  import { projectIdInput, blockIdInput } from "./ids";
6
- import type { ToolContext } from "./types";
5
+ import type { ToolContext, ToolRegistrar } from "./types";
7
6
  import { summarizeOutputs } from "./tokens";
8
7
  import { safeEval } from "./sandbox";
9
- import { errorResult, hints, textResult } from "./types";
8
+ import { errorResult, hints, textResult, transformFailedResult } from "./types";
10
9
 
11
- export function registerBlockStateTools(server: McpServer, ctx: ToolContext): void {
10
+ export function registerBlockStateTools(server: ToolRegistrar, ctx: ToolContext): void {
12
11
  server.registerTool(
13
12
  "get_project_overview",
14
13
  {
@@ -85,8 +84,8 @@ export function registerBlockStateTools(server: McpServer, ctx: ToolContext): vo
85
84
  );
86
85
  return textResult(result);
87
86
  } catch (e: unknown) {
88
- return errorResult(
89
- `Transform failed: ${e instanceof Error ? e.message : String(e)}`,
87
+ return transformFailedResult(
88
+ e,
90
89
  "Check your JS expression syntax. Available variables: data, outputs.",
91
90
  );
92
91
  }
@@ -1,11 +1,10 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import type { BlockPackSpecAny, Project } from "@milaboratories/pl-middle-layer";
3
2
  import { BlockKindRef, CentralBlockRegistry } from "@milaboratories/pl-middle-layer";
4
3
  import { BlockInitParamsRejectedError } from "@milaboratories/pl-errors";
5
4
  import type { BlockKindReference } from "@platforma-sdk/model";
6
5
  import { z } from "zod";
7
6
  import { projectIdInput, blockIdInput } from "./ids";
8
- import type { AuthorMarker, ToolContext } from "./types";
7
+ import type { AuthorMarker, ToolContext, ToolRegistrar } from "./types";
9
8
  import { errorResult, hints, textResult } from "./types";
10
9
  import { SUPPORTED_BLOCK_API, unsupportedBlockApiResult } from "./block-api";
11
10
 
@@ -140,7 +139,7 @@ export async function addBlock(deps: AddBlockDeps, input: AddBlockInput) {
140
139
  }
141
140
  }
142
141
 
143
- export function registerBlockTools(server: McpServer, ctx: ToolContext): void {
142
+ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): void {
144
143
  server.registerTool(
145
144
  "add_block",
146
145
  {
@@ -1,9 +1,8 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import { z } from "zod";
3
- import type { ToolContext } from "./types";
2
+ import type { ToolContext, ToolRegistrar } from "./types";
4
3
  import { errorResult, hints, textResult } from "./types";
5
4
 
6
- export function registerConnectionTools(server: McpServer, ctx: ToolContext): void {
5
+ export function registerConnectionTools(server: ToolRegistrar, ctx: ToolContext): void {
7
6
  server.registerTool(
8
7
  "get_connection_status",
9
8
  {
@@ -1,4 +1,3 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import type {
3
2
  PFrameHandle,
4
3
  PTableHandle,
@@ -13,9 +12,9 @@ import {
13
12
  } from "@milaboratories/pl-model-common";
14
13
  import { z } from "zod";
15
14
  import { projectIdInput, blockIdInput } from "./ids";
16
- import type { ToolContext } from "./types";
15
+ import type { ToolContext, ToolRegistrar } from "./types";
17
16
  import { safeEval } from "./sandbox";
18
- import { errorResult, hints, textResult } from "./types";
17
+ import { errorResult, hints, textResult, transformFailedResult } from "./types";
19
18
 
20
19
  const HEX_HASH_RE = /^[a-f0-9]{64}$/;
21
20
 
@@ -119,7 +118,7 @@ function vectorToJson(vector: PTableVector, rows: number): (string | number | nu
119
118
  return result;
120
119
  }
121
120
 
122
- export function registerDataQueryTools(server: McpServer, ctx: ToolContext): void {
121
+ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext): void {
123
122
  server.registerTool(
124
123
  "get_block_outputs",
125
124
  {
@@ -297,8 +296,8 @@ export function registerDataQueryTools(server: McpServer, ctx: ToolContext): voi
297
296
  );
298
297
  return textResult(result);
299
298
  } catch (e: unknown) {
300
- return errorResult(
301
- `Transform failed: ${e instanceof Error ? e.message : String(e)}`,
299
+ return transformFailedResult(
300
+ e,
302
301
  "Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.",
303
302
  );
304
303
  }
package/src/tools/logs.ts CHANGED
@@ -1,12 +1,11 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import { isAnyLogHandle } from "@milaboratories/pl-model-common";
3
2
  import type { AnyLogHandle } from "@milaboratories/pl-model-common";
4
3
  import { z } from "zod";
5
4
  import { projectIdInput, blockIdInput } from "./ids";
6
- import type { ToolContext } from "./types";
5
+ import type { ToolContext, ToolRegistrar } from "./types";
7
6
  import { errorResult, hints, textResult } from "./types";
8
7
 
9
- export function registerLogTools(server: McpServer, ctx: ToolContext): void {
8
+ export function registerLogTools(server: ToolRegistrar, ctx: ToolContext): void {
10
9
  server.registerTool(
11
10
  "get_block_logs",
12
11
  {
package/src/tools/ping.ts CHANGED
@@ -1,8 +1,7 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
- import type { ToolContext } from "./types";
1
+ import type { ToolContext, ToolRegistrar } from "./types";
3
2
  import { hints, textResult } from "./types";
4
3
 
5
- export function registerPingTool(server: McpServer, ctx: ToolContext): void {
4
+ export function registerPingTool(server: ToolRegistrar, ctx: ToolContext): void {
6
5
  server.registerTool(
7
6
  "ping",
8
7
  {
@@ -1,10 +1,9 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import { z } from "zod";
3
2
  import { projectIdInput } from "./ids";
4
- import type { ToolContext } from "./types";
3
+ import type { ToolContext, ToolRegistrar } from "./types";
5
4
  import { hints, textResult } from "./types";
6
5
 
7
- export function registerProjectTools(server: McpServer, ctx: ToolContext): void {
6
+ export function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {
8
7
  server.registerTool(
9
8
  "list_projects",
10
9
  {
@@ -0,0 +1,183 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { safeEval, SandboxError } from "./sandbox";
3
+
4
+ const TIMEOUT = 5000;
5
+
6
+ /** The class of the failure `safeEval` throws. */
7
+ async function failureClass(
8
+ expression: string,
9
+ context: Record<string, unknown> = {},
10
+ timeout: number = TIMEOUT,
11
+ ): Promise<string> {
12
+ try {
13
+ await safeEval(expression, context, timeout);
14
+ } catch (e: unknown) {
15
+ if (e instanceof SandboxError) return e.errorClass;
16
+ throw e;
17
+ }
18
+ throw new Error(`Expected the evaluation to fail: ${expression}`);
19
+ }
20
+
21
+ /** The message of the error `safeEval` throws: the text a tool puts after `Transform failed: `. */
22
+ async function failureMessage(
23
+ expression: string,
24
+ context: Record<string, unknown> = {},
25
+ timeout: number = TIMEOUT,
26
+ ): Promise<string> {
27
+ try {
28
+ await safeEval(expression, context, timeout);
29
+ } catch (e: unknown) {
30
+ if (e instanceof Error) return e.message;
31
+ throw e;
32
+ }
33
+ throw new Error(`Expected the evaluation to fail: ${expression}`);
34
+ }
35
+
36
+ const STATEMENTS = "const a = rows.map(r => r[0]); a.slice(0, 5)";
37
+ const ENDLESS_LOOP = "(() => { while (true) {} })()";
38
+ const ROWS = {
39
+ rows: [
40
+ [1, "a"],
41
+ [2, "b"],
42
+ ],
43
+ };
44
+
45
+ describe("safeEval", () => {
46
+ it("returns the value of an expression that uses a context variable", async () => {
47
+ expect(await safeEval("rows.map(r => r[0])", ROWS, TIMEOUT)).toEqual([1, 2]);
48
+ expect(
49
+ await safeEval("({ count: rows.length, offset })", { ...ROWS, offset: 10 }, TIMEOUT),
50
+ ).toEqual({
51
+ count: 2,
52
+ offset: 10,
53
+ });
54
+ });
55
+
56
+ it("runs several statements wrapped the way the hint shows", async () => {
57
+ expect(
58
+ await safeEval(
59
+ "(() => { const a = rows.map(r => r[0]); return a.slice(0, 5); })()",
60
+ ROWS,
61
+ TIMEOUT,
62
+ ),
63
+ ).toEqual([1, 2]);
64
+ });
65
+
66
+ it("reports statements in place of an expression as a syntax error with the one-expression hint", async () => {
67
+ const message = await failureMessage(STATEMENTS, ROWS);
68
+ expect(message).toMatch(/^SyntaxError: .*const/);
69
+ expect(message).toContain("A transform is a single expression");
70
+ expect(message).toContain("(() => { ...; return value; })()");
71
+ });
72
+
73
+ it("gives the hint for any expression that does not parse", async () => {
74
+ const message = await failureMessage("rows.map(");
75
+ expect(message).toMatch(/^SyntaxError: /);
76
+ expect(message).toContain("A transform is a single expression");
77
+ });
78
+
79
+ it("names the unknown variable of a reference error", async () => {
80
+ const message = await failureMessage("missingVariable.length");
81
+ expect(message).toMatch(/^ReferenceError: .*missingVariable.* is not defined$/);
82
+ });
83
+
84
+ it("reports a thrown Error by its name and message", async () => {
85
+ expect(await failureMessage('(() => { throw new Error("boom"); })()')).toBe("Error: boom");
86
+ expect(await failureMessage("rows[5][0]", ROWS)).toMatch(/^TypeError: /);
87
+ });
88
+
89
+ it("reports a thrown non-error value as the value", async () => {
90
+ expect(await failureMessage('(() => { throw "plain text"; })()')).toBe(
91
+ "Thrown value: plain text",
92
+ );
93
+ expect(await failureMessage('(() => { throw { code: 42, why: "nope" }; })()')).toBe(
94
+ 'Thrown value: {"code":42,"why":"nope"}',
95
+ );
96
+ expect(await failureMessage("(() => { throw 42; })()")).toBe("Thrown value: 42");
97
+ expect(await failureMessage("(() => { throw null; })()")).toBe("Thrown value: null");
98
+ expect(await failureMessage("(() => { throw undefined; })()")).toBe("Thrown value: undefined");
99
+ expect(await failureMessage("(() => { throw Promise.resolve(1); })()")).toBe(
100
+ 'Thrown value: {"type":"fulfilled","value":1}',
101
+ );
102
+ });
103
+
104
+ it("gives no one-expression hint for a syntax error raised at run time", async () => {
105
+ const message = await failureMessage('JSON.parse("{bad")');
106
+ expect(message).toMatch(/^SyntaxError: /);
107
+ expect(message).not.toContain("single expression");
108
+ });
109
+
110
+ it("says that an endless loop timed out, and the shared runtime keeps working", async () => {
111
+ expect(await failureMessage(ENDLESS_LOOP, {}, 50)).toBe("Evaluation timed out after 50 ms");
112
+ expect(await safeEval("rows.length + 1", ROWS, TIMEOUT)).toBe(3);
113
+ });
114
+
115
+ it("reports a failed context setup with the real error", async () => {
116
+ const message = await failureMessage("1", { "not-an-identifier": 1 });
117
+ expect(message).toMatch(/^Context setup failed: SyntaxError: /);
118
+ expect(message).not.toContain("single expression");
119
+ });
120
+
121
+ it("says that the setup step timed out", async () => {
122
+ // QuickJS calls the interrupt handler once when an evaluation starts, so a deadline already in the past
123
+ // stops the setup step.
124
+ expect(await failureMessage("1", { a: 1 }, -1)).toBe("Evaluation timed out after -1 ms");
125
+ expect(await safeEval("a + 1", { a: 1 }, TIMEOUT)).toBe(2);
126
+ });
127
+
128
+ it("reports an error with an empty name and message as an error", async () => {
129
+ expect(
130
+ await failureMessage('(() => { const e = new Error(""); e.name = ""; throw e; })()'),
131
+ ).toBe("Error");
132
+ expect(
133
+ await failureMessage('(() => { const e = new Error("boom"); e.name = ""; throw e; })()'),
134
+ ).toBe("Error: boom");
135
+ });
136
+
137
+ it("says what class of failure it was, in words the code cannot choose", async () => {
138
+ expect(await failureClass(STATEMENTS, ROWS)).toBe("SyntaxError");
139
+ expect(await failureClass("missingVariable.length")).toBe("ReferenceError");
140
+ expect(await failureClass("rows[5][0]", ROWS)).toBe("TypeError");
141
+ expect(await failureClass('(() => { throw new Error("boom"); })()')).toBe("Error");
142
+ expect(await failureClass('(() => { throw "plain text"; })()')).toBe("Thrown value");
143
+ expect(await failureClass("(() => { throw rows; })()", ROWS)).toBe("Thrown value");
144
+ // A name the code gave its error can be anything, data included.
145
+ expect(
146
+ await failureClass(
147
+ '(() => { const e = new Error("x"); e.name = rows[0][1]; throw e; })()',
148
+ ROWS,
149
+ ),
150
+ ).toBe("Error");
151
+ expect(await failureClass('(() => { throw { name: "donor_17", message: "" }; })()')).toBe(
152
+ "Error",
153
+ );
154
+ expect(await failureClass(ENDLESS_LOOP, {}, 50)).toBe("timeout");
155
+ expect(await failureClass("1", { "not-an-identifier": 1 })).toBe("SyntaxError");
156
+ });
157
+
158
+ it.each([
159
+ ["statements", STATEMENTS, ROWS, TIMEOUT],
160
+ ["unknown variable", "missingVariable.length", {}, TIMEOUT],
161
+ ["thrown Error", '(() => { throw new Error("boom"); })()', {}, TIMEOUT],
162
+ ["thrown string", '(() => { throw "plain text"; })()', {}, TIMEOUT],
163
+ ["thrown object", '(() => { throw { code: 42, why: "nope" }; })()', {}, TIMEOUT],
164
+ ["thrown array of objects", "(() => { throw [{ a: 1 }]; })()", {}, TIMEOUT],
165
+ ["thrown function", "(() => { throw function f() {}; })()", {}, TIMEOUT],
166
+ ["value JSON cannot hold", "10n", {}, TIMEOUT],
167
+ ["endless loop", ENDLESS_LOOP, {}, 50],
168
+ ["context setup", "1", { "not-an-identifier": 1 }, TIMEOUT],
169
+ [
170
+ "error without name or message",
171
+ '(() => { const e = new Error(""); e.name = ""; throw e; })()',
172
+ {},
173
+ TIMEOUT,
174
+ ],
175
+ ])(
176
+ "keeps [object Object] out of the message: %s",
177
+ async (_name, expression, context, timeout) => {
178
+ const message = await failureMessage(expression, context, timeout);
179
+ expect(message).not.toBe("");
180
+ expect(message).not.toContain("[object Object]");
181
+ },
182
+ );
183
+ });
@@ -1,4 +1,4 @@
1
- import { getQuickJS, type QuickJSRuntime } from "quickjs-emscripten";
1
+ import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from "quickjs-emscripten";
2
2
 
3
3
  /** Lazily initialized QuickJS runtime shared across evaluations. */
4
4
  let sharedRuntime: QuickJSRuntime | undefined;
@@ -13,10 +13,106 @@ async function getRuntime(): Promise<QuickJSRuntime> {
13
13
  return sharedRuntime;
14
14
  }
15
15
 
16
+ /** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */
17
+ const EXPRESSION_FILE = "transform.js";
18
+
19
+ const SINGLE_EXPRESSION_HINT =
20
+ "A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()";
21
+
22
+ /**
23
+ * The classes of the errors built into the JavaScript of the sandbox. Only these names are used as
24
+ * the class of a failure: code can give an error any name, data included.
25
+ */
26
+ const BUILT_IN_ERRORS: ReadonlySet<string> = new Set([
27
+ "Error",
28
+ "AggregateError",
29
+ "EvalError",
30
+ "InternalError",
31
+ "RangeError",
32
+ "ReferenceError",
33
+ "SyntaxError",
34
+ "TypeError",
35
+ "URIError",
36
+ ]);
37
+
38
+ /**
39
+ * What kind of failure an error is, in words that hold nothing of the code or its data: the name of
40
+ * a built-in error class, or `Error` for any other name.
41
+ */
42
+ export function errorClassOf(name: string): string {
43
+ return BUILT_IN_ERRORS.has(name) ? name : "Error";
44
+ }
45
+
46
+ /** The class of the failure of an evaluation that threw a value that is not an error. */
47
+ export const THROWN_VALUE = "Thrown value";
48
+
49
+ /** The class of the failure of an evaluation that ran out of time. */
50
+ export const TIMEOUT = "timeout";
51
+
52
+ /**
53
+ * Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the
54
+ * agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.
55
+ */
56
+ export class SandboxError extends Error {
57
+ /** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */
58
+ readonly errorClass: string;
59
+
60
+ constructor(message: string, errorClass: string) {
61
+ super(message);
62
+ this.name = "SandboxError";
63
+ this.errorClass = errorClass;
64
+ }
65
+ }
66
+
67
+ /** A value thrown inside the sandbox. */
68
+ type Thrown = {
69
+ /** `Name: message` of an error, or the thrown value itself when it is not an error. */
70
+ text: string;
71
+ /** See {@link SandboxError.errorClass}. */
72
+ errorClass: string;
73
+ /** For a syntax error: the file whose text failed to parse, as QuickJS names it. */
74
+ syntaxErrorFile?: string;
75
+ };
76
+
77
+ /**
78
+ * Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object
79
+ * `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file
80
+ * when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes
81
+ * as itself: a primitive, or an object that went through JSON.
82
+ */
83
+ function parseThrown(dumped: unknown): Thrown {
84
+ if (typeof dumped === "object" && dumped !== null && "name" in dumped && "message" in dumped) {
85
+ const { name, message } = dumped;
86
+ if (typeof name === "string" && typeof message === "string") {
87
+ // An error with neither a name nor a message still reads as an error.
88
+ const label = name === "" ? "Error" : name;
89
+ const text = message === "" ? label : `${label}: ${message}`;
90
+ const errorClass = errorClassOf(name);
91
+ if (name === "SyntaxError" && "fileName" in dumped && typeof dumped.fileName === "string")
92
+ return { text, errorClass, syntaxErrorFile: dumped.fileName };
93
+ return { text, errorClass };
94
+ }
95
+ }
96
+ const errorClass = THROWN_VALUE;
97
+ if (typeof dumped === "string") return { text: `${THROWN_VALUE}: ${dumped}`, errorClass };
98
+ if (typeof dumped === "object" && dumped !== null) {
99
+ // A thrown promise is dumped as its state, and the settled value can be a bigint.
100
+ const json = JSON.stringify(dumped, (_key, value: unknown) =>
101
+ typeof value === "bigint" ? `${value}n` : value,
102
+ );
103
+ return { text: `${THROWN_VALUE}: ${json}`, errorClass };
104
+ }
105
+ return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };
106
+ }
107
+
16
108
  /**
17
109
  * Evaluate a JS expression in a QuickJS sandbox.
18
110
  * Variables from `context` are injected as globals.
19
111
  * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.
112
+ *
113
+ * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),
114
+ * with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than
115
+ * `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.
20
116
  */
21
117
  export async function safeEval(
22
118
  expression: string,
@@ -25,11 +121,26 @@ export async function safeEval(
25
121
  ): Promise<unknown> {
26
122
  const runtime = await getRuntime();
27
123
 
28
- // Set interrupt handler for timeout
124
+ // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,
125
+ // so the flag is what tells a timeout from an error of the code itself.
29
126
  const deadline = Date.now() + timeout;
30
- runtime.setInterruptHandler(() => Date.now() > deadline);
127
+ let timedOut = false;
128
+ runtime.setInterruptHandler(() => {
129
+ if (Date.now() > deadline) timedOut = true;
130
+ return timedOut;
131
+ });
132
+ const timeoutMessage = `Evaluation timed out after ${timeout} ms`;
31
133
 
32
134
  const vm = runtime.newContext();
135
+
136
+ /** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */
137
+ const takeThrown = (error: QuickJSHandle): Thrown | undefined => {
138
+ const dumped: unknown = vm.dump(error);
139
+ // `dump` releases the handle itself when the thrown value is a promise.
140
+ if (error.alive) error.dispose();
141
+ return timedOut ? undefined : parseThrown(dumped);
142
+ };
143
+
33
144
  try {
34
145
  // Inject context variables via JSON
35
146
  const contextJson = JSON.stringify(context);
@@ -39,18 +150,23 @@ ${Object.keys(context)
39
150
  .join("\n")}`;
40
151
  const setupResult = vm.evalCode(setup, "setup.js", { type: "global" });
41
152
  if (setupResult.error) {
42
- const err = vm.dump(setupResult.error);
43
- setupResult.error.dispose();
44
- throw new Error(`Context setup failed: ${err}`);
153
+ const thrown = takeThrown(setupResult.error);
154
+ if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
155
+ throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);
45
156
  }
46
157
  setupResult.value.dispose();
47
158
 
48
159
  // Evaluate the expression
49
- const result = vm.evalCode(`JSON.stringify((${expression}))`, "transform.js");
160
+ const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);
50
161
  if (result.error) {
51
- const err = vm.dump(result.error);
52
- result.error.dispose();
53
- throw new Error(String(err));
162
+ const thrown = takeThrown(result.error);
163
+ if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
164
+ throw new SandboxError(
165
+ thrown.syntaxErrorFile === EXPRESSION_FILE
166
+ ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`
167
+ : thrown.text,
168
+ thrown.errorClass,
169
+ );
54
170
  }
55
171
  const json = vm.getString(result.value);
56
172
  result.value.dispose();
@@ -1,11 +1,10 @@
1
1
  import { writeFile } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
- import type { McpServer } from "@modelcontextprotocol/server";
4
3
  import { z } from "zod";
5
- import type { ToolContext } from "./types";
4
+ import type { ToolContext, ToolRegistrar } from "./types";
6
5
  import { errorResult, hints } from "./types";
7
6
 
8
- export function registerScreenshotTool(server: McpServer, ctx: ToolContext): void {
7
+ export function registerScreenshotTool(server: ToolRegistrar, ctx: ToolContext): void {
9
8
  server.registerTool(
10
9
  "capture_screenshot",
11
10
  {
@@ -33,7 +32,11 @@ export function registerScreenshotTool(server: McpServer, ctx: ToolContext): voi
33
32
 
34
33
  if (savePath) {
35
34
  const absPath = resolve(savePath);
36
- await writeFile(absPath, Buffer.from(base64Png, "base64"), { flag: "wx" });
35
+ try {
36
+ await writeFile(absPath, Buffer.from(base64Png, "base64"), { flag: "wx" });
37
+ } catch (e: unknown) {
38
+ return saveFailedResult(e);
39
+ }
37
40
  return {
38
41
  content: [
39
42
  { type: "image" as const, data: base64Png, mimeType: "image/png" },
@@ -48,3 +51,11 @@ export function registerScreenshotTool(server: McpServer, ctx: ToolContext): voi
48
51
  },
49
52
  );
50
53
  }
54
+
55
+ /** The result of a screenshot that could not be saved: the error of the file system, as it is. */
56
+ function saveFailedResult(error: unknown) {
57
+ return errorResult(
58
+ `Could not save the screenshot: ${error instanceof Error ? error.message : String(error)}`,
59
+ "Check that the folder exists and is writable and that no file exists at the path; the screenshot is not overwritten.",
60
+ );
61
+ }
@@ -1,8 +1,9 @@
1
1
  import { expect, test } from "vitest";
2
+ import type { McpInstanceId } from "../server";
2
3
  import { authorMarkerSource } from "./types";
3
4
 
4
5
  test("author markers keep the id and count the version up from 1", () => {
5
- const next = authorMarkerSource("mcp-1a2b3c4d");
6
+ const next = authorMarkerSource("mcp-1a2b3c4d" as McpInstanceId);
6
7
  expect([next(), next(), next()]).toEqual([
7
8
  { authorId: "mcp-1a2b3c4d", localVersion: 1 },
8
9
  { authorId: "mcp-1a2b3c4d", localVersion: 2 },
@@ -11,8 +12,8 @@ test("author markers keep the id and count the version up from 1", () => {
11
12
  });
12
13
 
13
14
  test("two sources count separately", () => {
14
- const first = authorMarkerSource("mcp-aaaaaaaa");
15
- const second = authorMarkerSource("mcp-bbbbbbbb");
15
+ const first = authorMarkerSource("mcp-aaaaaaaa" as McpInstanceId);
16
+ const second = authorMarkerSource("mcp-bbbbbbbb" as McpInstanceId);
16
17
  first();
17
18
  expect(second()).toEqual({ authorId: "mcp-bbbbbbbb", localVersion: 1 });
18
19
  expect(first()).toEqual({ authorId: "mcp-aaaaaaaa", localVersion: 2 });