@milaboratories/pl-mcp-server 52.1.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.
- package/README.md +31 -0
- package/dist/instructions.cjs +2 -1
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +2 -1
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/server-log.cjs +365 -0
- package/dist/server-log.cjs.map +1 -0
- package/dist/server-log.js +363 -0
- package/dist/server-log.js.map +1 -0
- package/dist/server.cjs +49 -15
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +12 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +49 -15
- package/dist/server.js.map +1 -1
- package/dist/tools/await.cjs +4 -6
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +5 -7
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-api.cjs +23 -0
- package/dist/tools/block-api.cjs.map +1 -0
- package/dist/tools/block-api.js +22 -0
- package/dist/tools/block-api.js.map +1 -0
- package/dist/tools/block-params.cjs +21 -0
- package/dist/tools/block-params.cjs.map +1 -0
- package/dist/tools/block-params.js +21 -0
- package/dist/tools/block-params.js.map +1 -0
- package/dist/tools/block-state.cjs +2 -2
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +3 -3
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/blocks.cjs +78 -20
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +78 -21
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/connection.cjs.map +1 -1
- package/dist/tools/connection.js.map +1 -1
- package/dist/tools/data-query.cjs +1 -1
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +2 -2
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/ping.cjs.map +1 -1
- package/dist/tools/ping.js.map +1 -1
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/sandbox.cjs +110 -8
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +107 -9
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/screenshot.cjs +9 -1
- package/dist/tools/screenshot.cjs.map +1 -1
- package/dist/tools/screenshot.js +9 -1
- package/dist/tools/screenshot.js.map +1 -1
- package/dist/tools/types.cjs +29 -0
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +27 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/ui-interaction.cjs.map +1 -1
- package/dist/tools/ui-interaction.js.map +1 -1
- package/package.json +5 -4
- package/src/instructions.ts +2 -1
- package/src/server-log.test.ts +859 -0
- package/src/server-log.ts +495 -0
- package/src/server.logging.test.ts +380 -0
- package/src/server.request-failure.test.ts +49 -0
- package/src/server.test.ts +4 -2
- package/src/server.ts +70 -15
- package/src/test/recording-logger.ts +33 -0
- package/src/tools/await.ts +7 -10
- package/src/tools/block-action-context.ts +2 -3
- package/src/tools/block-api.ts +24 -0
- package/src/tools/block-params.ts +29 -0
- package/src/tools/block-state.ts +5 -6
- package/src/tools/blocks.test.ts +148 -0
- package/src/tools/blocks.ts +162 -34
- package/src/tools/connection.ts +2 -3
- package/src/tools/data-query.ts +5 -6
- package/src/tools/logs.ts +2 -3
- package/src/tools/ping.ts +2 -3
- package/src/tools/projects.ts +2 -3
- package/src/tools/sandbox.test.ts +183 -0
- package/src/tools/sandbox.ts +126 -10
- package/src/tools/screenshot.ts +15 -4
- package/src/tools/types.test.ts +4 -3
- package/src/tools/types.ts +65 -2
- package/src/tools/ui-interaction.ts +2 -3
|
@@ -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
|
+
});
|
package/src/tools/sandbox.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
43
|
-
|
|
44
|
-
throw new
|
|
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}))`,
|
|
160
|
+
const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);
|
|
50
161
|
if (result.error) {
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
throw new
|
|
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();
|
package/src/tools/screenshot.ts
CHANGED
|
@@ -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:
|
|
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
|
-
|
|
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
|
+
}
|
package/src/tools/types.test.ts
CHANGED
|
@@ -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 });
|
package/src/tools/types.ts
CHANGED
|
@@ -5,7 +5,15 @@ import type {
|
|
|
5
5
|
ProjectId,
|
|
6
6
|
ProjectListEntry,
|
|
7
7
|
} from "@milaboratories/pl-middle-layer";
|
|
8
|
-
import type {
|
|
8
|
+
import type {
|
|
9
|
+
Icon,
|
|
10
|
+
RegisteredTool,
|
|
11
|
+
ScopeChallengeHandler,
|
|
12
|
+
StandardSchemaWithJSON,
|
|
13
|
+
ToolAnnotations,
|
|
14
|
+
ToolCallback,
|
|
15
|
+
} from "@modelcontextprotocol/server";
|
|
16
|
+
import type { McpInstanceId, PlMcpServerCallbacks } from "../server";
|
|
9
17
|
|
|
10
18
|
export type { AuthorMarker };
|
|
11
19
|
|
|
@@ -23,11 +31,36 @@ export interface ToolContext {
|
|
|
23
31
|
getAuthorMarker: () => AuthorMarker;
|
|
24
32
|
}
|
|
25
33
|
|
|
34
|
+
/**
|
|
35
|
+
* What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes
|
|
36
|
+
* schemas. The `register*Tools` functions get this and not the server, so that every tool they
|
|
37
|
+
* register goes through whatever the server put around the registration (the call log).
|
|
38
|
+
*/
|
|
39
|
+
export interface ToolRegistrar {
|
|
40
|
+
registerTool<
|
|
41
|
+
OutputArgs extends StandardSchemaWithJSON,
|
|
42
|
+
InputArgs extends StandardSchemaWithJSON | undefined = undefined,
|
|
43
|
+
>(
|
|
44
|
+
name: string,
|
|
45
|
+
config: {
|
|
46
|
+
title?: string;
|
|
47
|
+
description?: string;
|
|
48
|
+
inputSchema?: InputArgs;
|
|
49
|
+
outputSchema?: OutputArgs;
|
|
50
|
+
annotations?: ToolAnnotations;
|
|
51
|
+
icons?: Icon[];
|
|
52
|
+
scopeChallenge?: ScopeChallengeHandler;
|
|
53
|
+
_meta?: Record<string, unknown>;
|
|
54
|
+
},
|
|
55
|
+
cb: ToolCallback<InputArgs>,
|
|
56
|
+
): RegisteredTool;
|
|
57
|
+
}
|
|
58
|
+
|
|
26
59
|
/**
|
|
27
60
|
* Makes the author markers of one writer: every call returns a marker with `authorId` and the next
|
|
28
61
|
* `localVersion`, counted from 1.
|
|
29
62
|
*/
|
|
30
|
-
export function authorMarkerSource(authorId:
|
|
63
|
+
export function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {
|
|
31
64
|
let localVersion = 0;
|
|
32
65
|
return () => ({ authorId, localVersion: ++localVersion });
|
|
33
66
|
}
|
|
@@ -100,3 +133,33 @@ export function errorResult(message: string, hint?: string) {
|
|
|
100
133
|
isError: true,
|
|
101
134
|
};
|
|
102
135
|
}
|
|
136
|
+
|
|
137
|
+
/** The results made by {@link timedOutResult}. */
|
|
138
|
+
const timedOutResults = new WeakSet<object>();
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Returns the result of a tool that waited for something and ran out of time: the JSON of `data`
|
|
142
|
+
* with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.
|
|
143
|
+
* The server's log recognises such a result with {@link isTimedOutResult}.
|
|
144
|
+
*/
|
|
145
|
+
export function timedOutResult(data: Record<string, unknown>) {
|
|
146
|
+
const result = textResult({ timedOut: true, ...data });
|
|
147
|
+
timedOutResults.add(result);
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Whether `result` was made by {@link timedOutResult}. */
|
|
152
|
+
export function isTimedOutResult(result: unknown): boolean {
|
|
153
|
+
return typeof result === "object" && result !== null && timedOutResults.has(result);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole
|
|
158
|
+
* error, then `hint`. The agent needs the whole error to fix its expression.
|
|
159
|
+
*/
|
|
160
|
+
export function transformFailedResult(error: unknown, hint: string) {
|
|
161
|
+
return errorResult(
|
|
162
|
+
`Transform failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
163
|
+
hint,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
@@ -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 { errorResult, hints, textResult } from "./types";
|
|
6
5
|
|
|
7
|
-
export function registerUIInteractionTools(server:
|
|
6
|
+
export function registerUIInteractionTools(server: ToolRegistrar, ctx: ToolContext): void {
|
|
8
7
|
server.registerTool(
|
|
9
8
|
"click",
|
|
10
9
|
{
|