@milaboratories/pl-mcp-server 53.0.0 → 54.0.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 (103) hide show
  1. package/README.md +36 -2
  2. package/dist/instructions.cjs +3 -2
  3. package/dist/instructions.cjs.map +1 -1
  4. package/dist/instructions.js +3 -2
  5. package/dist/instructions.js.map +1 -1
  6. package/dist/package.cjs +1 -1
  7. package/dist/package.js +1 -1
  8. package/dist/project-holds.cjs +72 -0
  9. package/dist/project-holds.cjs.map +1 -0
  10. package/dist/project-holds.js +72 -0
  11. package/dist/project-holds.js.map +1 -0
  12. package/dist/server-log.cjs +373 -0
  13. package/dist/server-log.cjs.map +1 -0
  14. package/dist/server-log.js +371 -0
  15. package/dist/server-log.js.map +1 -0
  16. package/dist/server.cjs +77 -22
  17. package/dist/server.cjs.map +1 -1
  18. package/dist/server.d.ts +31 -7
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/server.js +77 -23
  21. package/dist/server.js.map +1 -1
  22. package/dist/tools/await.cjs +59 -60
  23. package/dist/tools/await.cjs.map +1 -1
  24. package/dist/tools/await.js +60 -61
  25. package/dist/tools/await.js.map +1 -1
  26. package/dist/tools/block-action-context.cjs +11 -9
  27. package/dist/tools/block-action-context.cjs.map +1 -1
  28. package/dist/tools/block-action-context.js +11 -9
  29. package/dist/tools/block-action-context.js.map +1 -1
  30. package/dist/tools/block-params.cjs +4 -3
  31. package/dist/tools/block-params.cjs.map +1 -1
  32. package/dist/tools/block-params.js +4 -3
  33. package/dist/tools/block-params.js.map +1 -1
  34. package/dist/tools/block-state.cjs +46 -41
  35. package/dist/tools/block-state.cjs.map +1 -1
  36. package/dist/tools/block-state.js +47 -42
  37. package/dist/tools/block-state.js.map +1 -1
  38. package/dist/tools/blocks.cjs +30 -20
  39. package/dist/tools/blocks.cjs.map +1 -1
  40. package/dist/tools/blocks.js +30 -20
  41. package/dist/tools/blocks.js.map +1 -1
  42. package/dist/tools/connection.cjs.map +1 -1
  43. package/dist/tools/connection.js.map +1 -1
  44. package/dist/tools/data-query.cjs +111 -80
  45. package/dist/tools/data-query.cjs.map +1 -1
  46. package/dist/tools/data-query.js +114 -83
  47. package/dist/tools/data-query.js.map +1 -1
  48. package/dist/tools/ids.cjs +16 -0
  49. package/dist/tools/ids.cjs.map +1 -1
  50. package/dist/tools/ids.js +13 -1
  51. package/dist/tools/ids.js.map +1 -1
  52. package/dist/tools/logs.cjs +28 -26
  53. package/dist/tools/logs.cjs.map +1 -1
  54. package/dist/tools/logs.js +28 -26
  55. package/dist/tools/logs.js.map +1 -1
  56. package/dist/tools/ping.cjs.map +1 -1
  57. package/dist/tools/ping.js.map +1 -1
  58. package/dist/tools/projects.cjs +10 -27
  59. package/dist/tools/projects.cjs.map +1 -1
  60. package/dist/tools/projects.js +11 -28
  61. package/dist/tools/projects.js.map +1 -1
  62. package/dist/tools/sandbox.cjs +110 -8
  63. package/dist/tools/sandbox.cjs.map +1 -1
  64. package/dist/tools/sandbox.js +107 -9
  65. package/dist/tools/sandbox.js.map +1 -1
  66. package/dist/tools/screenshot.cjs +9 -1
  67. package/dist/tools/screenshot.cjs.map +1 -1
  68. package/dist/tools/screenshot.js +9 -1
  69. package/dist/tools/screenshot.js.map +1 -1
  70. package/dist/tools/types.cjs +29 -0
  71. package/dist/tools/types.cjs.map +1 -1
  72. package/dist/tools/types.js +27 -1
  73. package/dist/tools/types.js.map +1 -1
  74. package/dist/tools/ui-interaction.cjs.map +1 -1
  75. package/dist/tools/ui-interaction.js.map +1 -1
  76. package/package.json +6 -5
  77. package/src/instructions.ts +3 -2
  78. package/src/project-holds.test.ts +183 -0
  79. package/src/project-holds.ts +105 -0
  80. package/src/server-log.test.ts +871 -0
  81. package/src/server-log.ts +504 -0
  82. package/src/server.logging.test.ts +383 -0
  83. package/src/server.request-failure.test.ts +49 -0
  84. package/src/server.test.ts +15 -5
  85. package/src/server.ts +111 -26
  86. package/src/test/recording-logger.ts +33 -0
  87. package/src/tools/await.ts +96 -98
  88. package/src/tools/block-action-context.ts +16 -16
  89. package/src/tools/block-params.ts +6 -6
  90. package/src/tools/block-state.ts +61 -60
  91. package/src/tools/blocks.ts +49 -40
  92. package/src/tools/connection.ts +2 -3
  93. package/src/tools/data-query.ts +151 -108
  94. package/src/tools/ids.ts +22 -1
  95. package/src/tools/logs.ts +43 -43
  96. package/src/tools/ping.ts +2 -3
  97. package/src/tools/projects.ts +22 -45
  98. package/src/tools/sandbox.test.ts +183 -0
  99. package/src/tools/sandbox.ts +126 -10
  100. package/src/tools/screenshot.ts +15 -4
  101. package/src/tools/types.test.ts +4 -3
  102. package/src/tools/types.ts +73 -3
  103. 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
+ });
@@ -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 });
@@ -2,10 +2,19 @@ import type {
2
2
  AuthorMarker,
3
3
  MiddleLayer,
4
4
  Project,
5
+ ProjectHolder,
5
6
  ProjectId,
6
7
  ProjectListEntry,
7
8
  } from "@milaboratories/pl-middle-layer";
8
- import type { PlMcpServerCallbacks } from "../server";
9
+ import type {
10
+ Icon,
11
+ RegisteredTool,
12
+ ScopeChallengeHandler,
13
+ StandardSchemaWithJSON,
14
+ ToolAnnotations,
15
+ ToolCallback,
16
+ } from "@modelcontextprotocol/server";
17
+ import type { McpInstanceId, PlMcpServerCallbacks } from "../server";
9
18
 
10
19
  export type { AuthorMarker };
11
20
 
@@ -13,7 +22,13 @@ export interface ToolContext {
13
22
  getMl: () => MiddleLayer | null;
14
23
  requireMl: () => MiddleLayer;
15
24
  resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;
16
- getOpenedProject: (projectId: ProjectId) => Promise<Project>;
25
+ /**
26
+ * Runs `fn` on the project, loading it when it is not loaded. The server holds the project
27
+ * while `fn` runs, so neither the application nor anyone else can unload it under the call.
28
+ */
29
+ withProject: <T>(projectId: ProjectId, fn: (project: Project) => Promise<T>) => Promise<T>;
30
+ /** The holder of this server's holds, as the middle layer's `projectHolders` lists them. */
31
+ projectHolder: ProjectHolder;
17
32
  callbacks: PlMcpServerCallbacks;
18
33
  /**
19
34
  * Returns the marker for the next write made through MCP. All writes of one server instance carry
@@ -23,11 +38,36 @@ export interface ToolContext {
23
38
  getAuthorMarker: () => AuthorMarker;
24
39
  }
25
40
 
41
+ /**
42
+ * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes
43
+ * schemas. The `register*Tools` functions get this and not the server, so that every tool they
44
+ * register goes through whatever the server put around the registration (the call log).
45
+ */
46
+ export interface ToolRegistrar {
47
+ registerTool<
48
+ OutputArgs extends StandardSchemaWithJSON,
49
+ InputArgs extends StandardSchemaWithJSON | undefined = undefined,
50
+ >(
51
+ name: string,
52
+ config: {
53
+ title?: string;
54
+ description?: string;
55
+ inputSchema?: InputArgs;
56
+ outputSchema?: OutputArgs;
57
+ annotations?: ToolAnnotations;
58
+ icons?: Icon[];
59
+ scopeChallenge?: ScopeChallengeHandler;
60
+ _meta?: Record<string, unknown>;
61
+ },
62
+ cb: ToolCallback<InputArgs>,
63
+ ): RegisteredTool;
64
+ }
65
+
26
66
  /**
27
67
  * Makes the author markers of one writer: every call returns a marker with `authorId` and the next
28
68
  * `localVersion`, counted from 1.
29
69
  */
30
- export function authorMarkerSource(authorId: string): () => AuthorMarker {
70
+ export function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {
31
71
  let localVersion = 0;
32
72
  return () => ({ authorId, localVersion: ++localVersion });
33
73
  }
@@ -100,3 +140,33 @@ export function errorResult(message: string, hint?: string) {
100
140
  isError: true,
101
141
  };
102
142
  }
143
+
144
+ /** The results made by {@link timedOutResult}. */
145
+ const timedOutResults = new WeakSet<object>();
146
+
147
+ /**
148
+ * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`
149
+ * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.
150
+ * The server's log recognises such a result with {@link isTimedOutResult}.
151
+ */
152
+ export function timedOutResult(data: Record<string, unknown>) {
153
+ const result = textResult({ timedOut: true, ...data });
154
+ timedOutResults.add(result);
155
+ return result;
156
+ }
157
+
158
+ /** Whether `result` was made by {@link timedOutResult}. */
159
+ export function isTimedOutResult(result: unknown): boolean {
160
+ return typeof result === "object" && result !== null && timedOutResults.has(result);
161
+ }
162
+
163
+ /**
164
+ * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole
165
+ * error, then `hint`. The agent needs the whole error to fix its expression.
166
+ */
167
+ export function transformFailedResult(error: unknown, hint: string) {
168
+ return errorResult(
169
+ `Transform failed: ${error instanceof Error ? error.message : String(error)}`,
170
+ hint,
171
+ );
172
+ }
@@ -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: McpServer, ctx: ToolContext): void {
6
+ export function registerUIInteractionTools(server: ToolRegistrar, ctx: ToolContext): void {
8
7
  server.registerTool(
9
8
  "click",
10
9
  {