@milaboratories/pl-mcp-server 53.1.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 (78) hide show
  1. package/README.md +15 -12
  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 +8 -0
  13. package/dist/server-log.cjs.map +1 -1
  14. package/dist/server-log.js +8 -0
  15. package/dist/server-log.js.map +1 -1
  16. package/dist/server.cjs +29 -6
  17. package/dist/server.cjs.map +1 -1
  18. package/dist/server.d.ts +19 -7
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/server.js +29 -7
  21. package/dist/server.js.map +1 -1
  22. package/dist/tools/await.cjs +59 -58
  23. package/dist/tools/await.cjs.map +1 -1
  24. package/dist/tools/await.js +59 -58
  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 +46 -41
  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/data-query.cjs +111 -80
  43. package/dist/tools/data-query.cjs.map +1 -1
  44. package/dist/tools/data-query.js +113 -82
  45. package/dist/tools/data-query.js.map +1 -1
  46. package/dist/tools/ids.cjs +16 -0
  47. package/dist/tools/ids.cjs.map +1 -1
  48. package/dist/tools/ids.js +13 -1
  49. package/dist/tools/ids.js.map +1 -1
  50. package/dist/tools/logs.cjs +28 -26
  51. package/dist/tools/logs.cjs.map +1 -1
  52. package/dist/tools/logs.js +28 -26
  53. package/dist/tools/logs.js.map +1 -1
  54. package/dist/tools/projects.cjs +10 -27
  55. package/dist/tools/projects.cjs.map +1 -1
  56. package/dist/tools/projects.js +11 -28
  57. package/dist/tools/projects.js.map +1 -1
  58. package/dist/tools/types.cjs.map +1 -1
  59. package/dist/tools/types.js.map +1 -1
  60. package/package.json +5 -5
  61. package/src/instructions.ts +3 -2
  62. package/src/project-holds.test.ts +183 -0
  63. package/src/project-holds.ts +105 -0
  64. package/src/server-log.test.ts +17 -5
  65. package/src/server-log.ts +9 -0
  66. package/src/server.logging.test.ts +8 -5
  67. package/src/server.test.ts +15 -5
  68. package/src/server.ts +42 -10
  69. package/src/tools/await.ts +94 -93
  70. package/src/tools/block-action-context.ts +14 -13
  71. package/src/tools/block-params.ts +4 -3
  72. package/src/tools/block-state.ts +58 -56
  73. package/src/tools/blocks.ts +47 -37
  74. package/src/tools/data-query.ts +148 -104
  75. package/src/tools/ids.ts +22 -1
  76. package/src/tools/logs.ts +41 -40
  77. package/src/tools/projects.ts +20 -42
  78. package/src/tools/types.ts +8 -1
@@ -16,26 +16,27 @@ export function registerBlockStateTools(server: ToolRegistrar, ctx: ToolContext)
16
16
  description:
17
17
  "Get project overview with all blocks and their statuses (calculationStatus, canRun, stale, errors, upstreams/downstreams)",
18
18
  inputSchema: z.object({
19
- projectId: projectIdInput.describe("Project ID (must be opened)"),
19
+ projectId: projectIdInput.describe("Project ID"),
20
20
  }),
21
21
  },
22
22
  async ({ projectId }) => {
23
- const project = await ctx.getOpenedProject(projectId);
24
- const overview = await project.overview.getValue();
25
- if (!overview) return errorResult("Project overview not available yet.");
26
- return textResult({
27
- label: overview.meta.label,
28
- blocks: overview.blocks.map((b) => ({
29
- id: b.id,
30
- title: b.title ?? b.label,
31
- calculationStatus: b.calculationStatus,
32
- canRun: b.canRun,
33
- stale: b.stale,
34
- inputsValid: b.inputsValid,
35
- outputErrors: b.outputErrors,
36
- upstreams: b.upstreams,
37
- downstreams: b.downstreams,
38
- })),
23
+ return await ctx.withProject(projectId, async (project) => {
24
+ const overview = await project.overview.getValue();
25
+ if (!overview) return errorResult("Project overview not available yet.");
26
+ return textResult({
27
+ label: overview.meta.label,
28
+ blocks: overview.blocks.map((b) => ({
29
+ id: b.id,
30
+ title: b.title ?? b.label,
31
+ calculationStatus: b.calculationStatus,
32
+ canRun: b.canRun,
33
+ stale: b.stale,
34
+ inputsValid: b.inputsValid,
35
+ outputErrors: b.outputErrors,
36
+ upstreams: b.upstreams,
37
+ downstreams: b.downstreams,
38
+ })),
39
+ });
39
40
  });
40
41
  },
41
42
  );
@@ -72,27 +73,28 @@ export function registerBlockStateTools(server: ToolRegistrar, ctx: ToolContext)
72
73
  }),
73
74
  },
74
75
  async ({ projectId, blockId, transform, transformTimeout }) => {
75
- const project = await ctx.getOpenedProject(projectId);
76
- const state = await project.getBlockState(blockId).getValue();
77
- const data = deriveDataFromStorage(state.blockStorage);
78
- if (transform) {
79
- try {
80
- const result = await safeEval(
81
- transform,
82
- { data, outputs: state.outputs },
83
- transformTimeout,
84
- );
85
- return textResult(result);
86
- } catch (e: unknown) {
87
- return transformFailedResult(
88
- e,
89
- "Check your JS expression syntax. Available variables: data, outputs.",
90
- );
76
+ return await ctx.withProject(projectId, async (project) => {
77
+ const state = await project.getBlockState(blockId).getValue();
78
+ const data = deriveDataFromStorage(state.blockStorage);
79
+ if (transform) {
80
+ try {
81
+ const result = await safeEval(
82
+ transform,
83
+ { data, outputs: state.outputs },
84
+ transformTimeout,
85
+ );
86
+ return textResult(result);
87
+ } catch (e: unknown) {
88
+ return transformFailedResult(
89
+ e,
90
+ "Check your JS expression syntax. Available variables: data, outputs.",
91
+ );
92
+ }
91
93
  }
92
- }
93
- return textResult({
94
- data,
95
- outputs: summarizeOutputs(state.outputs as Record<string, unknown> | undefined),
94
+ return textResult({
95
+ data,
96
+ outputs: summarizeOutputs(state.outputs as Record<string, unknown> | undefined),
97
+ });
96
98
  });
97
99
  },
98
100
  );
@@ -110,27 +112,27 @@ export function registerBlockStateTools(server: ToolRegistrar, ctx: ToolContext)
110
112
  }),
111
113
  },
112
114
  async ({ projectId, blockId, data }) => {
113
- const project = await ctx.getOpenedProject(projectId);
115
+ return await ctx.withProject(projectId, async (project) => {
116
+ // V1 state shape: { args, uiState } — callers may pass either the full state
117
+ // or just the args object. Unwrap once for both V2 and V1 paths.
118
+ const value = data.args ?? data;
114
119
 
115
- // V1 state shape: { args, uiState } — callers may pass either the full state
116
- // or just the args object. Unwrap once for both V2 and V1 paths.
117
- const value = data.args ?? data;
118
-
119
- // Try V2 (BlockModelV3 storage facade) first, fall back to V1 (legacy setBlockArgs).
120
- try {
121
- await project.mutateBlockStorage(
122
- blockId,
123
- { operation: "update-block-data", value },
124
- ctx.getAuthorMarker(),
125
- );
126
- } catch (e: unknown) {
127
- if (e instanceof ModelAPIVersionMismatchError) {
128
- await project.setBlockArgs(blockId, value, ctx.getAuthorMarker());
129
- } else {
130
- throw e;
120
+ // Try V2 (BlockModelV3 storage facade) first, fall back to V1 (legacy setBlockArgs).
121
+ try {
122
+ await project.mutateBlockStorage(
123
+ blockId,
124
+ { operation: "update-block-data", value },
125
+ ctx.getAuthorMarker(),
126
+ );
127
+ } catch (e: unknown) {
128
+ if (e instanceof ModelAPIVersionMismatchError) {
129
+ await project.setBlockArgs(blockId, value, ctx.getAuthorMarker());
130
+ } else {
131
+ throw e;
132
+ }
131
133
  }
132
- }
133
- return textResult({ ok: true });
134
+ return textResult({ ok: true });
135
+ });
134
136
  },
135
137
  );
136
138
  }
@@ -20,7 +20,7 @@ function errorMessage(e: unknown): string {
20
20
  }
21
21
 
22
22
  const addBlockInput = z.object({
23
- projectId: projectIdInput.describe("Project ID (must be opened)"),
23
+ projectId: projectIdInput.describe("Project ID"),
24
24
  label: z.string().describe("Block label"),
25
25
  spec: z
26
26
  .union([
@@ -146,7 +146,7 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
146
146
  title: "Add Block",
147
147
  annotations: hints.additive,
148
148
  description:
149
- "Add a block to an opened project, optionally configured from initialization params.\n\n" +
149
+ "Add a block to a project, optionally configured from initialization params.\n\n" +
150
150
  "`spec` names the block: `kind` (a block kind reference, resolved to the newest block " +
151
151
  "implementing it), `from-registry-v2` (an exact published block) or `dev-v2` (a local dev " +
152
152
  "block folder).\n\n" +
@@ -161,16 +161,20 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
161
161
  },
162
162
  async (input) => {
163
163
  const ml = ctx.requireMl();
164
- return await addBlock(
165
- {
166
- project: await ctx.getOpenedProject(input.projectId),
167
- resolveKind: (kind, registryUrl, allowUnstable) =>
168
- ml.blockRegistryProvider
169
- .getRegistry(registryUrl ?? centralBlockRegistryUrl())
170
- .resolveKind(kind, { allowUnstable }),
171
- author: ctx.getAuthorMarker(),
172
- },
173
- input,
164
+ return await ctx.withProject(
165
+ input.projectId,
166
+ async (project) =>
167
+ await addBlock(
168
+ {
169
+ project,
170
+ resolveKind: (kind, registryUrl, allowUnstable) =>
171
+ ml.blockRegistryProvider
172
+ .getRegistry(registryUrl ?? centralBlockRegistryUrl())
173
+ .resolveKind(kind, { allowUnstable }),
174
+ author: ctx.getAuthorMarker(),
175
+ },
176
+ input,
177
+ ),
174
178
  );
175
179
  },
176
180
  );
@@ -183,7 +187,7 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
183
187
  description:
184
188
  "Update an existing block's pack (reload from registry or dev folder). Use after rebuilding a dev block to pick up changes without removing/re-adding it.",
185
189
  inputSchema: z.object({
186
- projectId: projectIdInput.describe("Project ID (must be opened)"),
190
+ projectId: projectIdInput.describe("Project ID"),
187
191
  blockId: blockIdInput.describe("Block ID to update"),
188
192
  spec: z
189
193
  .union([
@@ -209,14 +213,15 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
209
213
  }),
210
214
  },
211
215
  async ({ projectId, blockId, spec, resetArgs }) => {
212
- const project = await ctx.getOpenedProject(projectId);
213
- await project.updateBlockPack(
214
- blockId,
215
- spec as BlockPackSpecAny,
216
- resetArgs ?? false,
217
- ctx.getAuthorMarker(),
218
- );
219
- return textResult({ ok: true });
216
+ return await ctx.withProject(projectId, async (project) => {
217
+ await project.updateBlockPack(
218
+ blockId,
219
+ spec as BlockPackSpecAny,
220
+ resetArgs ?? false,
221
+ ctx.getAuthorMarker(),
222
+ );
223
+ return textResult({ ok: true });
224
+ });
220
225
  },
221
226
  );
222
227
 
@@ -226,16 +231,17 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
226
231
  title: "Remove Block",
227
232
  annotations: hints.destructive,
228
233
  description:
229
- "Remove a block from an opened project, with its configuration and results. Blocks below that refer to it are left with a missing reference.",
234
+ "Remove a block from a project, with its configuration and results. Blocks below that refer to it are left with a missing reference.",
230
235
  inputSchema: z.object({
231
236
  projectId: projectIdInput.describe("Project ID"),
232
237
  blockId: blockIdInput.describe("Block ID to remove"),
233
238
  }),
234
239
  },
235
240
  async ({ projectId, blockId }) => {
236
- const project = await ctx.getOpenedProject(projectId);
237
- await project.deleteBlock(blockId, ctx.getAuthorMarker());
238
- return textResult({ ok: true });
241
+ return await ctx.withProject(projectId, async (project) => {
242
+ await project.deleteBlock(blockId, ctx.getAuthorMarker());
243
+ return textResult({ ok: true });
244
+ });
239
245
  },
240
246
  );
241
247
 
@@ -253,9 +259,10 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
253
259
  }),
254
260
  },
255
261
  async ({ projectId, blockId }) => {
256
- const project = await ctx.getOpenedProject(projectId);
257
- await project.runBlock(blockId);
258
- return textResult({ ok: true });
262
+ return await ctx.withProject(projectId, async (project) => {
263
+ await project.runBlock(blockId);
264
+ return textResult({ ok: true });
265
+ });
259
266
  },
260
267
  );
261
268
 
@@ -271,9 +278,10 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
271
278
  }),
272
279
  },
273
280
  async ({ projectId, blockId }) => {
274
- const project = await ctx.getOpenedProject(projectId);
275
- await project.stopBlock(blockId);
276
- return textResult({ ok: true });
281
+ return await ctx.withProject(projectId, async (project) => {
282
+ await project.stopBlock(blockId);
283
+ return textResult({ ok: true });
284
+ });
277
285
  },
278
286
  );
279
287
 
@@ -289,9 +297,10 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
289
297
  }),
290
298
  },
291
299
  async ({ projectId, blockIds }) => {
292
- const project = await ctx.getOpenedProject(projectId);
293
- await project.reorderBlocks(blockIds);
294
- return textResult({ ok: true });
300
+ return await ctx.withProject(projectId, async (project) => {
301
+ await project.reorderBlocks(blockIds);
302
+ return textResult({ ok: true });
303
+ });
295
304
  },
296
305
  );
297
306
 
@@ -352,7 +361,9 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
352
361
  {
353
362
  title: "Show Block in the Application",
354
363
  annotations: hints.idempotent,
355
- description: "Navigate the desktop UI to show a specific block's interface",
364
+ description:
365
+ "Show a block to the user in the application: the application's window opens the block. " +
366
+ "Use it only when the user asks to be shown something; working with blocks does not need it.",
356
367
  inputSchema: z.object({
357
368
  projectId: projectIdInput.describe("Project ID"),
358
369
  blockId: blockIdInput.describe("Block ID to display"),
@@ -361,8 +372,7 @@ export function registerBlockTools(server: ToolRegistrar, ctx: ToolContext): voi
361
372
  async ({ projectId, blockId }) => {
362
373
  if (!ctx.callbacks.selectBlock) {
363
374
  return errorResult(
364
- "Failed to select the block.",
365
- "This feature requires server connected and open project. Use get_connection_status and list_projects to check. If there are no connection, use list_connections and ask user which should be used.",
375
+ "Failed to show the block: this server is not running inside the desktop application.",
366
376
  );
367
377
  }
368
378
  await ctx.callbacks.selectBlock(projectId, blockId);
@@ -6,18 +6,37 @@ import type {
6
6
  } from "@milaboratories/pl-middle-layer";
7
7
  import {
8
8
  Annotation,
9
+ isPFrameDriverError,
9
10
  pTableValue,
10
11
  readAnnotation,
11
12
  PFrameDriver,
12
13
  } from "@milaboratories/pl-model-common";
13
14
  import { z } from "zod";
14
- import { projectIdInput, blockIdInput } from "./ids";
15
+ import { projectIdInput, blockIdInput, pFrameHandleInput, pTableHandleInput } from "./ids";
15
16
  import type { ToolContext, ToolRegistrar } from "./types";
16
17
  import { safeEval } from "./sandbox";
17
18
  import { errorResult, hints, textResult, transformFailedResult } from "./types";
18
19
 
19
20
  const HEX_HASH_RE = /^[a-f0-9]{64}$/;
20
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
+
21
40
  /**
22
41
  * Try to resolve a 64-char hex handle as PTable, then PFrame.
23
42
  * Returns a summary object or the original string if neither works.
@@ -139,28 +158,28 @@ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext):
139
158
  }),
140
159
  },
141
160
  async ({ projectId, blockId, maxColumns }) => {
142
- const project = await ctx.getOpenedProject(projectId);
143
- const state = await project.getBlockState(blockId).getValue();
144
- if (!state.outputs)
145
- return errorResult(
146
- "Block has no outputs yet.",
147
- "The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.",
148
- );
149
-
150
- const outputs = state.outputs as Record<string, { ok?: boolean; value?: unknown }>;
151
- const driver = ctx.requireMl().internalDriverKit.pFrameDriver;
152
- 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>();
153
171
 
154
- const result: Record<string, unknown> = {};
155
- for (const [key, output] of Object.entries(outputs)) {
156
- if (!output?.ok || output.value == null) {
157
- result[key] = { ok: output?.ok ?? false };
158
- 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);
159
179
  }
160
- result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);
161
- }
162
180
 
163
- return textResult(result);
181
+ return textResult(result);
182
+ });
164
183
  },
165
184
  );
166
185
 
@@ -172,28 +191,38 @@ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext):
172
191
  description:
173
192
  "List all columns in a PFrame with their specs. Use get_block_outputs first to find the PFrame handle.",
174
193
  inputSchema: z.object({
175
- pFrameHandle: z
176
- .string()
177
- .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
+ ),
178
198
  }),
179
199
  },
180
- async ({ pFrameHandle }) => {
181
- const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;
182
- const columns = await pFrameDriver.listColumns(pFrameHandle as PFrameHandle);
183
- return textResult(
184
- columns.map((c) => ({
185
- columnId: c.columnId,
186
- name: c.spec.name,
187
- valueType: c.spec.valueType,
188
- label: readAnnotation(c.spec, Annotation.Label),
189
- visibility: readAnnotation(c.spec, Annotation.Table.Visibility),
190
- axes: c.spec.axesSpec.map((a) => ({
191
- name: a.name,
192
- type: a.type,
193
- 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
+ })),
194
223
  })),
195
- })),
196
- );
224
+ );
225
+ });
197
226
  },
198
227
  );
199
228
 
@@ -206,9 +235,10 @@ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext):
206
235
  "Query data from a PTable. Returns rows as arrays of values. Use get_block_outputs first to find the PTable handle. " +
207
236
  "Use `transform` to process results server-side and return only what you need.",
208
237
  inputSchema: z.object({
209
- pTableHandle: z
210
- .string()
211
- .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
+ ),
212
242
  columns: z
213
243
  .array(z.number())
214
244
  .optional()
@@ -237,77 +267,91 @@ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext):
237
267
  .describe("Timeout in ms for transform evaluation (default 5000)."),
238
268
  }),
239
269
  },
240
- async ({ pTableHandle, columns, offset, limit, maxLimit, transform, transformTimeout }) => {
241
- const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;
242
- 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;
243
284
 
244
- let spec;
245
- try {
246
- spec = await pFrameDriver.getSpec(handle);
247
- } catch (err) {
248
- return textResult({ error: `getSpec failed: ${err}` });
249
- }
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
+ }
250
292
 
251
- const effectiveLimit = Math.min(limit, maxLimit);
252
- const range = { offset, length: effectiveLimit };
293
+ const effectiveLimit = Math.min(limit, maxLimit);
294
+ const range = { offset, length: effectiveLimit };
253
295
 
254
- // If no columns specified, get all
255
- 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);
256
298
 
257
- let vectors: PTableVector[];
258
- try {
259
- vectors = await pFrameDriver.getData(handle, columnIndices, range);
260
- } catch (err) {
261
- return textResult({
262
- error: `getData failed: ${err}`,
263
- columnIndices,
264
- range,
265
- });
266
- }
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
+ }
267
310
 
268
- const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;
269
- const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));
270
- const rows: unknown[][] = [];
271
- for (let r = 0; r < actualRows; r++) {
272
- rows.push(columnVectors.map((col) => col[r]));
273
- }
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
+ }
274
317
 
275
- const columnHeaders = columnIndices.map((idx: number) => {
276
- const s = spec[idx];
277
- return {
278
- index: idx,
279
- type: s.type,
280
- name: s.type === "column" ? s.spec.name : s.spec.name,
281
- label: readAnnotation(s.spec, Annotation.Label),
282
- };
283
- });
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
+ });
284
327
 
285
- if (transform) {
286
- try {
287
- const result = await safeEval(
288
- transform,
289
- {
290
- rows,
291
- columns: columnHeaders,
292
- offset,
293
- rowCount: actualRows,
294
- },
295
- transformTimeout,
296
- );
297
- return textResult(result);
298
- } catch (e: unknown) {
299
- return transformFailedResult(
300
- e,
301
- "Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.",
302
- );
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
+ }
303
347
  }
304
- }
305
348
 
306
- return textResult({
307
- offset,
308
- rowCount: actualRows,
309
- columns: columnHeaders,
310
- rows,
349
+ return textResult({
350
+ offset,
351
+ rowCount: actualRows,
352
+ columns: columnHeaders,
353
+ rows,
354
+ });
311
355
  });
312
356
  },
313
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);