@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
@@ -1,4 +1,3 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import type {
3
2
  PFrameHandle,
4
3
  PTableHandle,
@@ -7,18 +6,37 @@ import type {
7
6
  } from "@milaboratories/pl-middle-layer";
8
7
  import {
9
8
  Annotation,
9
+ isPFrameDriverError,
10
10
  pTableValue,
11
11
  readAnnotation,
12
12
  PFrameDriver,
13
13
  } from "@milaboratories/pl-model-common";
14
14
  import { z } from "zod";
15
- import { projectIdInput, blockIdInput } from "./ids";
16
- import type { ToolContext } from "./types";
15
+ import { projectIdInput, blockIdInput, pFrameHandleInput, pTableHandleInput } from "./ids";
16
+ import type { ToolContext, ToolRegistrar } from "./types";
17
17
  import { safeEval } from "./sandbox";
18
- import { errorResult, hints, textResult } from "./types";
18
+ import { errorResult, hints, textResult, transformFailedResult } from "./types";
19
19
 
20
20
  const HEX_HASH_RE = /^[a-f0-9]{64}$/;
21
21
 
22
+ /**
23
+ * The error of a tool given a handle the driver does not know (any more). A handle lives as long as
24
+ * a project it came from stays loaded, and the server lets a project go some time after the last
25
+ * call on it.
26
+ */
27
+ function staleHandleResult(kind: "PFrame" | "PTable", handle: string, err: Error) {
28
+ return errorResult(
29
+ `${kind} handle ${handle} is not valid: ${err.message}`,
30
+ "Handles stop working some time after the last call on their project. " +
31
+ "Call get_block_outputs again for a fresh handle.",
32
+ );
33
+ }
34
+
35
+ /** Whether `err` is the driver's answer to a handle it does not know (any more). */
36
+ function isUnknownHandleError(err: unknown): err is Error {
37
+ return isPFrameDriverError(err) && /^Invalid P(Frame|Table) handle/.test(err.message);
38
+ }
39
+
22
40
  /**
23
41
  * Try to resolve a 64-char hex handle as PTable, then PFrame.
24
42
  * Returns a summary object or the original string if neither works.
@@ -119,7 +137,7 @@ function vectorToJson(vector: PTableVector, rows: number): (string | number | nu
119
137
  return result;
120
138
  }
121
139
 
122
- export function registerDataQueryTools(server: McpServer, ctx: ToolContext): void {
140
+ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext): void {
123
141
  server.registerTool(
124
142
  "get_block_outputs",
125
143
  {
@@ -140,28 +158,28 @@ export function registerDataQueryTools(server: McpServer, ctx: ToolContext): voi
140
158
  }),
141
159
  },
142
160
  async ({ projectId, blockId, maxColumns }) => {
143
- const project = await ctx.getOpenedProject(projectId);
144
- const state = await project.getBlockState(blockId).getValue();
145
- if (!state.outputs)
146
- return errorResult(
147
- "Block has no outputs yet.",
148
- "The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.",
149
- );
150
-
151
- const outputs = state.outputs as Record<string, { ok?: boolean; value?: unknown }>;
152
- const driver = ctx.requireMl().internalDriverKit.pFrameDriver;
153
- const cache = new Map<string, unknown>();
161
+ return await ctx.withProject(projectId, async (project) => {
162
+ const state = await project.getBlockState(blockId).getValue();
163
+ if (!state.outputs)
164
+ return errorResult(
165
+ "Block has no outputs yet.",
166
+ "The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.",
167
+ );
168
+ const outputs = state.outputs as Record<string, { ok?: boolean; value?: unknown }>;
169
+ const driver = ctx.requireMl().internalDriverKit.pFrameDriver;
170
+ const cache = new Map<string, unknown>();
154
171
 
155
- const result: Record<string, unknown> = {};
156
- for (const [key, output] of Object.entries(outputs)) {
157
- if (!output?.ok || output.value == null) {
158
- result[key] = { ok: output?.ok ?? false };
159
- continue;
172
+ const result: Record<string, unknown> = {};
173
+ for (const [key, output] of Object.entries(outputs)) {
174
+ if (!output?.ok || output.value == null) {
175
+ result[key] = { ok: output?.ok ?? false };
176
+ continue;
177
+ }
178
+ result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);
160
179
  }
161
- result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);
162
- }
163
180
 
164
- return textResult(result);
181
+ return textResult(result);
182
+ });
165
183
  },
166
184
  );
167
185
 
@@ -173,28 +191,38 @@ export function registerDataQueryTools(server: McpServer, ctx: ToolContext): voi
173
191
  description:
174
192
  "List all columns in a PFrame with their specs. Use get_block_outputs first to find the PFrame handle.",
175
193
  inputSchema: z.object({
176
- pFrameHandle: z
177
- .string()
178
- .describe("PFrame handle (64-char hex hash from get_block_outputs)"),
194
+ projectId: projectIdInput.describe("Project the handle came from"),
195
+ pFrameHandle: pFrameHandleInput.describe(
196
+ "PFrame handle (64-char hex hash from get_block_outputs)",
197
+ ),
179
198
  }),
180
199
  },
181
- async ({ pFrameHandle }) => {
182
- const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;
183
- const columns = await pFrameDriver.listColumns(pFrameHandle as PFrameHandle);
184
- return textResult(
185
- columns.map((c) => ({
186
- columnId: c.columnId,
187
- name: c.spec.name,
188
- valueType: c.spec.valueType,
189
- label: readAnnotation(c.spec, Annotation.Label),
190
- visibility: readAnnotation(c.spec, Annotation.Table.Visibility),
191
- axes: c.spec.axesSpec.map((a) => ({
192
- name: a.name,
193
- type: a.type,
194
- label: readAnnotation(a, Annotation.Label),
200
+ async ({ projectId, pFrameHandle }) => {
201
+ // The handle lives as long as its project stays loaded: the read holds it.
202
+ return await ctx.withProject(projectId, async () => {
203
+ const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;
204
+ let columns;
205
+ try {
206
+ columns = await pFrameDriver.listColumns(pFrameHandle);
207
+ } catch (err) {
208
+ if (isUnknownHandleError(err)) return staleHandleResult("PFrame", pFrameHandle, err);
209
+ throw err;
210
+ }
211
+ return textResult(
212
+ columns.map((c) => ({
213
+ columnId: c.columnId,
214
+ name: c.spec.name,
215
+ valueType: c.spec.valueType,
216
+ label: readAnnotation(c.spec, Annotation.Label),
217
+ visibility: readAnnotation(c.spec, Annotation.Table.Visibility),
218
+ axes: c.spec.axesSpec.map((a) => ({
219
+ name: a.name,
220
+ type: a.type,
221
+ label: readAnnotation(a, Annotation.Label),
222
+ })),
195
223
  })),
196
- })),
197
- );
224
+ );
225
+ });
198
226
  },
199
227
  );
200
228
 
@@ -207,9 +235,10 @@ export function registerDataQueryTools(server: McpServer, ctx: ToolContext): voi
207
235
  "Query data from a PTable. Returns rows as arrays of values. Use get_block_outputs first to find the PTable handle. " +
208
236
  "Use `transform` to process results server-side and return only what you need.",
209
237
  inputSchema: z.object({
210
- pTableHandle: z
211
- .string()
212
- .describe("PTable handle (64-char hex hash from get_block_outputs)"),
238
+ projectId: projectIdInput.describe("Project the handle came from"),
239
+ pTableHandle: pTableHandleInput.describe(
240
+ "PTable handle (64-char hex hash from get_block_outputs)",
241
+ ),
213
242
  columns: z
214
243
  .array(z.number())
215
244
  .optional()
@@ -238,77 +267,91 @@ export function registerDataQueryTools(server: McpServer, ctx: ToolContext): voi
238
267
  .describe("Timeout in ms for transform evaluation (default 5000)."),
239
268
  }),
240
269
  },
241
- async ({ pTableHandle, columns, offset, limit, maxLimit, transform, transformTimeout }) => {
242
- const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;
243
- const handle = pTableHandle as PTableHandle;
270
+ async ({
271
+ projectId,
272
+ pTableHandle,
273
+ columns,
274
+ offset,
275
+ limit,
276
+ maxLimit,
277
+ transform,
278
+ transformTimeout,
279
+ }) => {
280
+ // The handle lives as long as its project stays loaded: the read holds it.
281
+ return await ctx.withProject(projectId, async () => {
282
+ const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;
283
+ const handle = pTableHandle;
244
284
 
245
- let spec;
246
- try {
247
- spec = await pFrameDriver.getSpec(handle);
248
- } catch (err) {
249
- return textResult({ error: `getSpec failed: ${err}` });
250
- }
285
+ let spec;
286
+ try {
287
+ spec = await pFrameDriver.getSpec(handle);
288
+ } catch (err) {
289
+ if (isUnknownHandleError(err)) return staleHandleResult("PTable", pTableHandle, err);
290
+ throw err;
291
+ }
251
292
 
252
- const effectiveLimit = Math.min(limit, maxLimit);
253
- const range = { offset, length: effectiveLimit };
293
+ const effectiveLimit = Math.min(limit, maxLimit);
294
+ const range = { offset, length: effectiveLimit };
254
295
 
255
- // If no columns specified, get all
256
- const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);
296
+ // If no columns specified, get all
297
+ const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);
257
298
 
258
- let vectors: PTableVector[];
259
- try {
260
- vectors = await pFrameDriver.getData(handle, columnIndices, range);
261
- } catch (err) {
262
- return textResult({
263
- error: `getData failed: ${err}`,
264
- columnIndices,
265
- range,
266
- });
267
- }
299
+ let vectors: PTableVector[];
300
+ try {
301
+ vectors = await pFrameDriver.getData(handle, columnIndices, range);
302
+ } catch (err) {
303
+ if (isUnknownHandleError(err)) return staleHandleResult("PTable", pTableHandle, err);
304
+ return textResult({
305
+ error: `getData failed: ${err}`,
306
+ columnIndices,
307
+ range,
308
+ });
309
+ }
268
310
 
269
- const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;
270
- const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));
271
- const rows: unknown[][] = [];
272
- for (let r = 0; r < actualRows; r++) {
273
- rows.push(columnVectors.map((col) => col[r]));
274
- }
311
+ const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;
312
+ const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));
313
+ const rows: unknown[][] = [];
314
+ for (let r = 0; r < actualRows; r++) {
315
+ rows.push(columnVectors.map((col) => col[r]));
316
+ }
275
317
 
276
- const columnHeaders = columnIndices.map((idx: number) => {
277
- const s = spec[idx];
278
- return {
279
- index: idx,
280
- type: s.type,
281
- name: s.type === "column" ? s.spec.name : s.spec.name,
282
- label: readAnnotation(s.spec, Annotation.Label),
283
- };
284
- });
318
+ const columnHeaders = columnIndices.map((idx: number) => {
319
+ const s = spec[idx];
320
+ return {
321
+ index: idx,
322
+ type: s.type,
323
+ name: s.type === "column" ? s.spec.name : s.spec.name,
324
+ label: readAnnotation(s.spec, Annotation.Label),
325
+ };
326
+ });
285
327
 
286
- if (transform) {
287
- try {
288
- const result = await safeEval(
289
- transform,
290
- {
291
- rows,
292
- columns: columnHeaders,
293
- offset,
294
- rowCount: actualRows,
295
- },
296
- transformTimeout,
297
- );
298
- return textResult(result);
299
- } catch (e: unknown) {
300
- return errorResult(
301
- `Transform failed: ${e instanceof Error ? e.message : String(e)}`,
302
- "Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.",
303
- );
328
+ if (transform) {
329
+ try {
330
+ const result = await safeEval(
331
+ transform,
332
+ {
333
+ rows,
334
+ columns: columnHeaders,
335
+ offset,
336
+ rowCount: actualRows,
337
+ },
338
+ transformTimeout,
339
+ );
340
+ return textResult(result);
341
+ } catch (e: unknown) {
342
+ return transformFailedResult(
343
+ e,
344
+ "Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.",
345
+ );
346
+ }
304
347
  }
305
- }
306
348
 
307
- return textResult({
308
- offset,
309
- rowCount: actualRows,
310
- columns: columnHeaders,
311
- rows,
349
+ return textResult({
350
+ offset,
351
+ rowCount: actualRows,
352
+ columns: columnHeaders,
353
+ rows,
354
+ });
312
355
  });
313
356
  },
314
357
  );
package/src/tools/ids.ts CHANGED
@@ -1,6 +1,21 @@
1
- import { asBlockId, asProjectId } from "@milaboratories/pl-model-common";
1
+ import {
2
+ asBlockId,
3
+ asProjectId,
4
+ type PFrameHandle,
5
+ type PTableHandle,
6
+ } from "@milaboratories/pl-model-common";
2
7
  import { z } from "zod";
3
8
 
9
+ /** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */
10
+ export function asPFrameHandle(handle: string): PFrameHandle {
11
+ return handle as PFrameHandle;
12
+ }
13
+
14
+ /** Brands a string handed back by an agent as a PTable handle; the driver says whether it is one. */
15
+ export function asPTableHandle(handle: string): PTableHandle {
16
+ return handle as PTableHandle;
17
+ }
18
+
4
19
  /**
5
20
  * A project id argument of a tool. The agent sends a string; the tool receives a `ProjectId`.
6
21
  * Each tool adds its own description.
@@ -9,3 +24,9 @@ export const projectIdInput = z.string().transform(asProjectId);
9
24
 
10
25
  /** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */
11
26
  export const blockIdInput = z.string().transform(asBlockId);
27
+
28
+ /** A PFrame handle argument of a tool, as get_block_outputs gave it. */
29
+ export const pFrameHandleInput = z.string().transform(asPFrameHandle);
30
+
31
+ /** A PTable handle argument of a tool, as get_block_outputs gave it. */
32
+ export const pTableHandleInput = z.string().transform(asPTableHandle);
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
  {
@@ -25,55 +24,56 @@ export function registerLogTools(server: McpServer, ctx: ToolContext): void {
25
24
  }),
26
25
  },
27
26
  async ({ projectId, blockId, lines, sampleId }) => {
28
- const project = await ctx.getOpenedProject(projectId);
29
- const state = await project.getBlockState(blockId).getValue();
30
- if (!state.outputs)
31
- return errorResult(
32
- "Block has no outputs yet.",
33
- "The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.",
34
- );
27
+ return await ctx.withProject(projectId, async (project) => {
28
+ const state = await project.getBlockState(blockId).getValue();
29
+ if (!state.outputs)
30
+ return errorResult(
31
+ "Block has no outputs yet.",
32
+ "The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.",
33
+ );
35
34
 
36
- // Scan all outputs for log handles (log+ready:// or log+live://)
37
- const outputs = state.outputs as Record<
38
- string,
39
- { ok?: boolean; value?: { data?: { key: string[]; value: unknown }[] } }
40
- >;
41
- const logEntries: { outputKey: string; key: string[]; handle: AnyLogHandle }[] = [];
42
- for (const [outputKey, output] of Object.entries(outputs)) {
43
- if (!output?.ok || !output.value?.data) continue;
44
- for (const entry of output.value.data) {
45
- if (isAnyLogHandle(entry.value)) {
46
- logEntries.push({ outputKey, key: entry.key, handle: entry.value });
35
+ // Scan all outputs for log handles (log+ready:// or log+live://)
36
+ const outputs = state.outputs as Record<
37
+ string,
38
+ { ok?: boolean; value?: { data?: { key: string[]; value: unknown }[] } }
39
+ >;
40
+ const logEntries: { outputKey: string; key: string[]; handle: AnyLogHandle }[] = [];
41
+ for (const [outputKey, output] of Object.entries(outputs)) {
42
+ if (!output?.ok || !output.value?.data) continue;
43
+ for (const entry of output.value.data) {
44
+ if (isAnyLogHandle(entry.value)) {
45
+ logEntries.push({ outputKey, key: entry.key, handle: entry.value });
46
+ }
47
47
  }
48
48
  }
49
- }
50
49
 
51
- if (logEntries.length === 0) {
52
- return errorResult(
53
- "No log handles found in block outputs.",
54
- "This block may not produce logs, or it hasn't run yet. Use get_block_outputs to inspect available output types.",
55
- );
56
- }
50
+ if (logEntries.length === 0) {
51
+ return errorResult(
52
+ "No log handles found in block outputs.",
53
+ "This block may not produce logs, or it hasn't run yet. Use get_block_outputs to inspect available output types.",
54
+ );
55
+ }
57
56
 
58
- const logDriver = ctx.requireMl().driverKit.logDriver;
59
- const results: Record<string, string> = {};
57
+ const logDriver = ctx.requireMl().driverKit.logDriver;
58
+ const results: Record<string, string> = {};
60
59
 
61
- for (const entry of logEntries) {
62
- const key = entry.key.join("/");
63
- if (sampleId && !entry.key.includes(sampleId)) continue;
64
- try {
65
- const response = await logDriver.lastLines(entry.handle, lines);
66
- if (response.shouldUpdateHandle) {
67
- results[key] = "[log handle stale — block may still be running, retry later]";
68
- } else {
69
- results[key] = new TextDecoder().decode(response.data);
60
+ for (const entry of logEntries) {
61
+ const key = entry.key.join("/");
62
+ if (sampleId && !entry.key.includes(sampleId)) continue;
63
+ try {
64
+ const response = await logDriver.lastLines(entry.handle, lines);
65
+ if (response.shouldUpdateHandle) {
66
+ results[key] = "[log handle stale — block may still be running, retry later]";
67
+ } else {
68
+ results[key] = new TextDecoder().decode(response.data);
69
+ }
70
+ } catch (err) {
71
+ results[key] = `Error reading log: ${err}`;
70
72
  }
71
- } catch (err) {
72
- results[key] = `Error reading log: ${err}`;
73
73
  }
74
- }
75
74
 
76
- return textResult(results);
75
+ return textResult(results);
76
+ });
77
77
  },
78
78
  );
79
79
 
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,16 +1,16 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
1
+ import { isProjectInUseError } from "@milaboratories/pl-middle-layer";
2
2
  import { z } from "zod";
3
3
  import { projectIdInput } from "./ids";
4
- import type { ToolContext } from "./types";
5
- import { hints, textResult } from "./types";
4
+ import type { ToolContext, ToolRegistrar } from "./types";
5
+ import { errorResult, hints, textResult } from "./types";
6
6
 
7
- export function registerProjectTools(server: McpServer, ctx: ToolContext): void {
7
+ export function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {
8
8
  server.registerTool(
9
9
  "list_projects",
10
10
  {
11
11
  title: "List Projects",
12
12
  annotations: hints.read,
13
- description: "List all projects with their IDs, labels, and status",
13
+ description: "List all projects with their IDs, labels, and creation and modification times",
14
14
  },
15
15
  async () => {
16
16
  const ml = ctx.requireMl();
@@ -20,7 +20,6 @@ export function registerProjectTools(server: McpServer, ctx: ToolContext): void
20
20
  projects.map((p) => ({
21
21
  projectId: p.id,
22
22
  label: p.meta.label,
23
- opened: p.opened,
24
23
  created: p.created.toISOString(),
25
24
  lastModified: p.lastModified.toISOString(),
26
25
  })),
@@ -33,8 +32,7 @@ export function registerProjectTools(server: McpServer, ctx: ToolContext): void
33
32
  {
34
33
  title: "Create Project",
35
34
  annotations: hints.additive,
36
- description:
37
- "Create a new, empty project and return its ID. Call open_project before adding blocks to it.",
35
+ description: "Create a new, empty project and return its ID.",
38
36
  inputSchema: z.object({ label: z.string().describe("Project name") }),
39
37
  },
40
38
  async ({ label }) => {
@@ -44,52 +42,31 @@ export function registerProjectTools(server: McpServer, ctx: ToolContext): void
44
42
  },
45
43
  );
46
44
 
47
- server.registerTool(
48
- "open_project",
49
- {
50
- title: "Open Project",
51
- annotations: hints.idempotent,
52
- description: "Open a project for editing. Required before working with blocks.",
53
- inputSchema: z.object({
54
- projectId: projectIdInput.describe("Project ID from list_projects or create_project"),
55
- }),
56
- },
57
- async ({ projectId }) => {
58
- const entry = await ctx.resolveProject(projectId);
59
- await ctx.requireMl().openProject(entry.id);
60
- await ctx.callbacks.onProjectOpened?.(projectId);
61
- return textResult({ ok: true });
62
- },
63
- );
64
-
65
- server.registerTool(
66
- "close_project",
67
- {
68
- title: "Close Project",
69
- annotations: hints.idempotent,
70
- description:
71
- "Close an opened project, releasing its resources in the application. Nothing is deleted.",
72
- inputSchema: z.object({ projectId: projectIdInput.describe("Project ID") }),
73
- },
74
- async ({ projectId }) => {
75
- const entry = await ctx.resolveProject(projectId);
76
- await ctx.requireMl().closeProject(entry.id);
77
- await ctx.callbacks.onProjectClosed?.(projectId);
78
- return textResult({ ok: true });
79
- },
80
- );
81
-
82
45
  server.registerTool(
83
46
  "delete_project",
84
47
  {
85
48
  title: "Delete Project",
86
49
  annotations: hints.destructive,
87
- description: "Delete a project permanently. The project must be closed first.",
50
+ description:
51
+ "Delete a project permanently, with all its blocks and results. Refused while the project " +
52
+ "is in use by another agent or by the user in the application.",
88
53
  inputSchema: z.object({ projectId: projectIdInput.describe("Project ID") }),
89
54
  },
90
55
  async ({ projectId }) => {
91
56
  const entry = await ctx.resolveProject(projectId);
92
- await ctx.requireMl().deleteProject(entry.id);
57
+ try {
58
+ // This server's own holds, kept or of calls still running, end with the delete: a deleted
59
+ // project is not snapshotted. Anyone else's hold refuses it.
60
+ await ctx.requireMl().deleteProject(entry.id, {
61
+ refuseIfHeldBy: (holder) => holder !== ctx.projectHolder,
62
+ });
63
+ } catch (e: unknown) {
64
+ if (!isProjectInUseError(e)) throw e;
65
+ return errorResult(
66
+ `Project ${projectId} was not deleted: it is still in use by another agent or by the ` +
67
+ "user in the application.",
68
+ );
69
+ }
93
70
  await ctx.callbacks.onProjectDeleted?.(projectId);
94
71
  return textResult({ ok: true });
95
72
  },