@milaboratories/pl-mcp-server 53.1.0 → 55.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 (208) hide show
  1. package/README.md +30 -37
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +16 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +16 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +122 -0
  14. package/dist/project-holds.cjs.map +1 -0
  15. package/dist/project-holds.js +122 -0
  16. package/dist/project-holds.js.map +1 -0
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +48 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +48 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +71 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +37 -24
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +71 -19
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -72
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -74
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +14 -9
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +14 -9
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +275 -6
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +273 -8
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +343 -57
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +337 -61
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +199 -76
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +193 -76
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +470 -101
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +465 -106
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +72 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +63 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +111 -30
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +108 -31
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +68 -38
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +69 -40
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +16 -12
  143. package/src/project-holds.test.ts +362 -0
  144. package/src/project-holds.ts +207 -0
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +71 -6
  148. package/src/server-log.ts +58 -27
  149. package/src/server.logging.test.ts +46 -51
  150. package/src/server.test.ts +166 -22
  151. package/src/server.ts +97 -37
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -122
  156. package/src/tools/block-action-context.ts +17 -13
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +626 -10
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +678 -83
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +354 -113
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +839 -145
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +89 -1
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +154 -44
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +136 -48
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +84 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -1,47 +1,105 @@
1
1
  import type {
2
2
  PFrameHandle,
3
+ PoolFrame,
4
+ PoolFrameRefusal,
3
5
  PTableHandle,
4
6
  PTableColumnSpec,
5
7
  PTableVector,
6
8
  } from "@milaboratories/pl-middle-layer";
7
9
  import {
8
10
  Annotation,
11
+ getAxisId,
12
+ isValueNA,
13
+ ValueType,
14
+ isPFrameDriverError,
9
15
  pTableValue,
10
16
  readAnnotation,
11
- PFrameDriver,
17
+ type AxisSpec,
18
+ type ColumnUniversalId,
19
+ type PColumnIdAndSpec,
20
+ type PFrameDriver,
21
+ createColumnValueIds,
22
+ isGlobalPObjectId,
23
+ type PTableRecordFilter,
24
+ type ProjectId,
25
+ type PTableShape,
26
+ type TableRange,
27
+ type UniqueValuesRequest,
28
+ type UniqueValuesResponse,
12
29
  } from "@milaboratories/pl-model-common";
13
30
  import { z } from "zod";
14
- import { projectIdInput, blockIdInput } from "./ids";
31
+ import { clamp, isPlainObject } from "@milaboratories/helpers";
32
+ import { ownValue } from "./block-storage";
33
+ import {
34
+ blockIdInput,
35
+ columnIdFromAgent,
36
+ frameColumnIdInput,
37
+ pFrameHandleInput,
38
+ projectIdInput,
39
+ pTableHandleInput,
40
+ } from "./ids";
15
41
  import type { ToolContext, ToolRegistrar } from "./types";
16
- import { safeEval } from "./sandbox";
17
- import { errorResult, hints, textResult, transformFailedResult } from "./types";
42
+ import { expressionTimeoutText, safeEval } from "./sandbox";
43
+ import {
44
+ errorResult,
45
+ hints,
46
+ readSignal,
47
+ RESULT_CHAR_LIMIT,
48
+ textResult,
49
+ transformFailedResult,
50
+ } from "./types";
51
+ import { findBlock, STALE_RESULTS_NOTE } from "./readiness";
52
+ import { clipMiddle, failedOutputsNote, outputErrorText, summarizeOutputs } from "./tokens";
18
53
 
19
54
  const HEX_HASH_RE = /^[a-f0-9]{64}$/;
20
55
 
56
+ /**
57
+ * The error of a tool given a handle the driver does not know (any more). A handle lives as long as
58
+ * a project it came from stays loaded, and the server lets a project go some time after the last
59
+ * call on it.
60
+ */
61
+ function staleHandleResult(kind: "PFrame" | "PTable", handle: string, err: Error) {
62
+ return errorResult(
63
+ `${kind} handle ${handle} is not valid: ${err.message}`,
64
+ "Handles stop working some time after the last call on their project. " +
65
+ (kind === "PTable"
66
+ ? "Call get_block_outputs again for a fresh handle, or create_table again for a table " +
67
+ "of your own (those also go when dropped or not read for a while)."
68
+ : "Call get_block_outputs again for a fresh handle."),
69
+ );
70
+ }
71
+
72
+ /** Whether `err` is the driver's answer to a handle it does not know (any more). */
73
+ function isUnknownHandleError(err: unknown): err is Error {
74
+ return isPFrameDriverError(err) && /^Invalid P(Frame|Table) handle/.test(err.message);
75
+ }
76
+
77
+ /** What summing up the handles of block outputs uses of the PFrame driver. */
78
+ export type OutputsDriver = Pick<PFrameDriver, "getSpec" | "listColumns">;
79
+
21
80
  /**
22
81
  * Try to resolve a 64-char hex handle as PTable, then PFrame.
23
82
  * Returns a summary object or the original string if neither works.
24
83
  */
25
84
  async function resolveHandle(
26
85
  handle: string,
27
- driver: PFrameDriver,
86
+ driver: OutputsDriver,
28
87
  maxColumns: number,
29
88
  cache: Map<string, unknown>,
30
89
  ): Promise<unknown> {
31
90
  if (cache.has(handle)) return cache.get(handle);
32
91
 
33
- // Try PTable first (has rows — more useful info)
92
+ // Try PTable first. Its spec only: counting rows would build the whole join.
34
93
  try {
35
94
  const spec = await driver.getSpec(handle as PTableHandle);
36
- const shape = await driver.getShape(handle as PTableHandle);
37
95
  const summary: Record<string, unknown> = {
38
96
  _type: "PTable",
39
97
  handle,
40
- rows: shape.rows,
41
98
  columnCount: spec.length,
42
99
  columns: spec.slice(0, maxColumns).map((s: PTableColumnSpec, idx: number) => ({
43
100
  index: idx,
44
101
  type: s.type,
102
+ ...(s.type === "column" ? { columnId: s.id } : {}),
45
103
  name: s.spec.name,
46
104
  valueType: s.type === "column" ? s.spec.valueType : s.spec.type,
47
105
  label: readAnnotation(s.spec, Annotation.Label),
@@ -65,6 +123,7 @@ async function resolveHandle(
65
123
  handle,
66
124
  columnCount: columns.length,
67
125
  columns: columns.slice(0, maxColumns).map((c) => ({
126
+ columnId: c.columnId,
68
127
  name: c.spec.name,
69
128
  valueType: c.spec.valueType,
70
129
  label: readAnnotation(c.spec, Annotation.Label),
@@ -86,11 +145,11 @@ async function resolveHandle(
86
145
 
87
146
  /**
88
147
  * Recursively walk a value tree, replacing 64-char hex handles
89
- * with PFrame/PTable summaries (column specs + row count).
148
+ * with PFrame/PTable summaries (column specs).
90
149
  */
91
150
  async function resolveHandlesInValue(
92
151
  value: unknown,
93
- driver: Parameters<typeof resolveHandle>[1],
152
+ driver: OutputsDriver,
94
153
  maxColumns: number,
95
154
  cache: Map<string, unknown>,
96
155
  ): Promise<unknown> {
@@ -102,35 +161,659 @@ async function resolveHandlesInValue(
102
161
  if (Array.isArray(value)) {
103
162
  return Promise.all(value.map((v) => resolveHandlesInValue(v, driver, maxColumns, cache)));
104
163
  }
105
- const out: Record<string, unknown> = {};
164
+ const entries: [string, unknown][] = [];
106
165
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
107
- out[k] = await resolveHandlesInValue(v, driver, maxColumns, cache);
166
+ entries.push([k, await resolveHandlesInValue(v, driver, maxColumns, cache)]);
108
167
  }
109
- return out;
168
+ // `Object.fromEntries` defines own keys: a key such as `__proto__` stays a key of the copy.
169
+ return Object.fromEntries(entries);
170
+ }
171
+
172
+ /**
173
+ * Replaces every PFrame or PTable summary of `outputs` (output key → resolved value) whose handle
174
+ * an earlier one already summed up with `{ sameAs: "<path>" }`, the path to that first summary in
175
+ * `outputs`, written as a JavaScript accessor: `main.table`, `list[0]`, `["a key"].x`. Outputs are
176
+ * walked in their order, values depth-first. A block often gives the same table in two outputs
177
+ * (D-025): each summary is then given once, and every repeat names the one it repeats.
178
+ */
179
+ export function dedupeHandleSummaries(outputs: Record<string, unknown>): Record<string, unknown> {
180
+ const firstSeen = new Map<string, string>();
181
+ const walk = (value: unknown, path: string): unknown => {
182
+ if (typeof value !== "object" || value === null) return value;
183
+ if (Array.isArray(value)) return value.map((v, i) => walk(v, `${path}[${i}]`));
184
+ const record: Record<string, unknown> = Object.fromEntries(Object.entries(value));
185
+ const handle = record.handle;
186
+ if ((record._type === "PTable" || record._type === "PFrame") && typeof handle === "string") {
187
+ const first = firstSeen.get(handle);
188
+ if (first !== undefined) return { sameAs: first };
189
+ firstSeen.set(handle, path);
190
+ return record;
191
+ }
192
+ return Object.fromEntries(
193
+ Object.entries(record).map(([k, v]) => [k, walk(v, `${path}${propertyAccessor(k)}`)]),
194
+ );
195
+ };
196
+ return Object.fromEntries(
197
+ Object.entries(outputs).map(([key, v]) => [
198
+ key,
199
+ walk(v, JS_IDENTIFIER.test(key) ? key : propertyAccessor(key)),
200
+ ]),
201
+ );
202
+ }
203
+
204
+ /** A name JavaScript accepts after a dot. */
205
+ const JS_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
206
+
207
+ /** How JavaScript reads property `key`: `.key`, or `["key"]` for a key that is not a plain name. */
208
+ function propertyAccessor(key: string): string {
209
+ return JS_IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
110
210
  }
111
211
 
112
- /** Converts a PTableVector column to a JSON-serializable array using the SDK helper. */
113
- function vectorToJson(vector: PTableVector, rows: number): (string | number | null)[] {
114
- const result: (string | number | null)[] = [];
212
+ /**
213
+ * Converts a PTableVector column to a JSON-serializable array using the SDK helper. Binary values,
214
+ * which the helper does not read, are given by their size, `{bytes: N}`; NA as `null`.
215
+ */
216
+ function vectorToJson(vector: PTableVector, rows: number): unknown[] {
217
+ const result: unknown[] = [];
115
218
  for (let i = 0; i < rows; i++) {
116
- result.push(pTableValue(vector, i));
219
+ if (vector.type === ValueType.Bytes) {
220
+ const value: unknown = vector.data[i];
221
+ result.push(
222
+ isValueNA(vector, i) || !(value instanceof Uint8Array) ? null : { bytes: value.length },
223
+ );
224
+ } else result.push(pTableValue(vector, i));
117
225
  }
118
226
  return result;
119
227
  }
120
228
 
229
+ const MIN_SAFE_BIGINT = BigInt(Number.MIN_SAFE_INTEGER);
230
+ const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
231
+
232
+ /**
233
+ * The value at `row` of `vector`, or null for NA. A Long outside the safe integer range is its
234
+ * exact decimal text: `pTableValue` rounds it to a number, and a value's id is built from its text.
235
+ */
236
+ function exactValue(vector: PTableVector, row: number): string | number | null {
237
+ const raw = vector.data[row];
238
+ if (typeof raw === "bigint" && !isValueNA(vector, row))
239
+ return raw >= MIN_SAFE_BIGINT && raw <= MAX_SAFE_BIGINT ? Number(raw) : raw.toString();
240
+ return pTableValue(vector, row, { na: null });
241
+ }
242
+
243
+ /** The most rows one `query_table` call returns. */
244
+ export const QUERY_MAX_ROWS = 10_000;
245
+ /** Columns `list_columns` gives by default. */
246
+ export const LIST_COLUMNS_DEFAULT = 100;
247
+ /** The most columns one `list_columns` page has. */
248
+ export const LIST_COLUMNS_MAX = 1000;
249
+ /** Values `get_column_values` gives by default. */
250
+ export const COLUMN_VALUES_DEFAULT = 100;
251
+ /** The most values one `get_column_values` call asks the driver for. */
252
+ export const COLUMN_VALUES_MAX = 10_000;
253
+
254
+ /**
255
+ * What the data query tools use of the PFrame driver: the public methods, and the internal
256
+ * driver's `signal` on the ones that take it.
257
+ */
258
+ export type DataQueryDriver = Pick<PFrameDriver, "getSpec" | "listColumns"> & {
259
+ getShape(handle: PTableHandle, signal?: AbortSignal): Promise<PTableShape>;
260
+ getUniqueValues(
261
+ handle: PFrameHandle,
262
+ request: UniqueValuesRequest,
263
+ signal?: AbortSignal,
264
+ ): Promise<UniqueValuesResponse>;
265
+ getData(
266
+ handle: PTableHandle,
267
+ columnIndices: number[],
268
+ range: TableRange | undefined,
269
+ signal?: AbortSignal,
270
+ ): Promise<PTableVector[]>;
271
+ };
272
+
273
+ function clampInt(v: number | undefined, fallback: number, min: number, max: number): number {
274
+ if (v === undefined || !Number.isFinite(v)) return fallback;
275
+ return clamp(Math.floor(v), min, max);
276
+ }
277
+
278
+ /** Options of {@link listColumnsResult}. */
279
+ export type ListColumnsOptions = {
280
+ offset?: number;
281
+ limit?: number;
282
+ detail?: "brief" | "full";
283
+ /** Case-insensitive substring of the column's name or label. */
284
+ name?: string;
285
+ valueType?: string;
286
+ /** Annotation key → value every listed column must have. */
287
+ annotations?: Record<string, string>;
288
+ };
289
+
290
+ /** The columns of a PFrame, filtered and paged (`list_columns`). */
291
+ export async function listColumnsResult(
292
+ driver: DataQueryDriver,
293
+ pFrameHandle: PFrameHandle,
294
+ options: ListColumnsOptions,
295
+ ) {
296
+ let columns: PColumnIdAndSpec[];
297
+ try {
298
+ columns = await driver.listColumns(pFrameHandle);
299
+ } catch (err) {
300
+ if (isUnknownHandleError(err)) return staleHandleResult("PFrame", pFrameHandle, err);
301
+ throw err;
302
+ }
303
+ const needle = options.name?.toLowerCase();
304
+ const matching = columns.filter((c) => {
305
+ if (options.valueType !== undefined && c.spec.valueType !== options.valueType) return false;
306
+ if (needle !== undefined) {
307
+ const label = readAnnotation(c.spec, Annotation.Label) ?? "";
308
+ if (!c.spec.name.toLowerCase().includes(needle) && !label.toLowerCase().includes(needle))
309
+ return false;
310
+ }
311
+ // Filter keys are names an agent gives: only keys a spec has itself match them.
312
+ for (const [key, value] of Object.entries(options.annotations ?? {}))
313
+ if (ownValue(c.spec.annotations ?? {}, key) !== value) return false;
314
+ return true;
315
+ });
316
+ const offset = clampInt(options.offset, 0, 0, Number.MAX_SAFE_INTEGER);
317
+ const limit = clampInt(options.limit, LIST_COLUMNS_DEFAULT, 1, LIST_COLUMNS_MAX);
318
+ const page = matching.slice(offset, offset + limit);
319
+ const end = offset + page.length;
320
+ const full = options.detail === "full";
321
+ return textResult(
322
+ {
323
+ total: matching.length,
324
+ ...(matching.length !== columns.length ? { inFrame: columns.length } : {}),
325
+ offset,
326
+ hasMore: end < matching.length,
327
+ ...(end < matching.length ? { nextOffset: end } : {}),
328
+ columns: page.map((c) => ({
329
+ columnId: c.columnId,
330
+ name: c.spec.name,
331
+ valueType: c.spec.valueType,
332
+ label: readAnnotation(c.spec, Annotation.Label),
333
+ ...(full
334
+ ? {
335
+ visibility: readAnnotation(c.spec, Annotation.Table.Visibility),
336
+ domain: c.spec.domain,
337
+ annotations: c.spec.annotations,
338
+ axes: c.spec.axesSpec.map((a) => ({
339
+ name: a.name,
340
+ type: a.type,
341
+ domain: a.domain,
342
+ label: readAnnotation(a, Annotation.Label),
343
+ })),
344
+ }
345
+ : { axes: c.spec.axesSpec.map((a) => a.name) }),
346
+ })),
347
+ },
348
+ { hint: 'Ask for fewer columns: a smaller `limit`, `detail: "brief"`, or a `name` filter.' },
349
+ );
350
+ }
351
+
352
+ /** Input of {@link columnValuesResult}. */
353
+ export type ColumnValuesInput = {
354
+ pFrameHandle: PFrameHandle;
355
+ /** The column's id as the agent wrote it: as listed, or any written form of the same id. */
356
+ columnId: string;
357
+ /** An axis of the column, by index or name: its values instead of the column's. */
358
+ axis?: number | string;
359
+ /** Case-insensitive substring the values must contain (string values only). */
360
+ search?: string;
361
+ limit?: number;
362
+ };
363
+
364
+ /**
365
+ * The column of a PFrame an agent's column id names: listed under exactly that id, or under the
366
+ * same id written another way (escaped, other spacing or key order at its top level, a PlRef for a
367
+ * global id). Ids of older block APIs are not `ColumnUniversalId`s: they match only as listed.
368
+ */
369
+ function findFrameColumn(
370
+ listed: readonly PColumnIdAndSpec[],
371
+ written: string,
372
+ ): PColumnIdAndSpec | undefined {
373
+ const exact = listed.find((c) => c.columnId === written);
374
+ if (exact !== undefined) return exact;
375
+ const canonical = columnIdFromAgent(written);
376
+ if (canonical === undefined) return undefined;
377
+ return listed.find((c) => columnIdFromAgent(c.columnId) === canonical);
378
+ }
379
+
380
+ /** The distinct values of a column, or of one of its axes, in a PFrame (`get_column_values`). */
381
+ export async function columnValuesResult(
382
+ driver: DataQueryDriver,
383
+ input: ColumnValuesInput,
384
+ signal?: AbortSignal,
385
+ ) {
386
+ const handle = input.pFrameHandle;
387
+ let listed: PColumnIdAndSpec[];
388
+ try {
389
+ listed = await driver.listColumns(handle);
390
+ } catch (err) {
391
+ if (isUnknownHandleError(err)) return staleHandleResult("PFrame", input.pFrameHandle, err);
392
+ throw err;
393
+ }
394
+ const column = findFrameColumn(listed, input.columnId);
395
+ if (column === undefined)
396
+ return errorResult(
397
+ `Column ${input.columnId} is not in PFrame ${input.pFrameHandle}.`,
398
+ "list_columns on the PFrame gives the ids of its columns; ids can change when a block " +
399
+ "runs again: list again.",
400
+ );
401
+ const { columnId, spec } = column;
402
+
403
+ let axisSpec: AxisSpec | undefined;
404
+ if (input.axis !== undefined) {
405
+ const axes = spec.axesSpec;
406
+ axisSpec =
407
+ typeof input.axis === "number" ? axes[input.axis] : axes.find((a) => a.name === input.axis);
408
+ if (axisSpec === undefined)
409
+ return errorResult(
410
+ `The column has no axis ${JSON.stringify(input.axis)}.`,
411
+ `Its axes: ${axes.map((a, i) => `${i}: ${a.name}`).join(", ")}.`,
412
+ );
413
+ }
414
+ const valueType = axisSpec !== undefined ? axisSpec.type : spec.valueType;
415
+ if (input.search !== undefined && valueType !== "String")
416
+ return errorResult(
417
+ `\`search\` works on string values; these are ${valueType}.`,
418
+ "Leave out `search`.",
419
+ );
420
+
421
+ const axisId = axisSpec !== undefined ? getAxisId(axisSpec) : undefined;
422
+ const filters: PTableRecordFilter[] =
423
+ input.search === undefined || input.search === ""
424
+ ? []
425
+ : [
426
+ {
427
+ type: "bySingleColumnV2",
428
+ column:
429
+ axisId !== undefined
430
+ ? { type: "axis", id: axisId }
431
+ : { type: "column", id: columnId },
432
+ predicate: { operator: "StringIContains", substring: input.search },
433
+ },
434
+ ];
435
+ const limit = clampInt(input.limit, COLUMN_VALUES_DEFAULT, 1, COLUMN_VALUES_MAX);
436
+ let response: UniqueValuesResponse;
437
+ try {
438
+ response = await driver.getUniqueValues(
439
+ handle,
440
+ { columnId, ...(axisId !== undefined ? { axis: axisId } : {}), filters, limit },
441
+ signal,
442
+ );
443
+ } catch (err) {
444
+ if (isUnknownHandleError(err)) return staleHandleResult("PFrame", input.pFrameHandle, err);
445
+ if (signal?.aborted)
446
+ return errorResult(
447
+ "Reading the values was stopped: it took too long or the request was cancelled.",
448
+ "Narrow it with `search`, or ask for a smaller `limit`.",
449
+ );
450
+ return errorResult(`Reading the values failed: ${errorMessage(err)}`);
451
+ }
452
+ const values: (string | number)[] = [];
453
+ let naDropped = 0;
454
+ for (let i = 0; i < response.values.data.length; i++) {
455
+ const v = exactValue(response.values, i);
456
+ if (v === null) naDropped++;
457
+ else values.push(v);
458
+ }
459
+ // A picked value is named by its ColumnValueId; only a column's own values have one, and only
460
+ // a column a block can use: a block's export itself (GlobalPObjectId). Not a column local to
461
+ // the block that made the frame, and not a filtered, overridden or discovered id over an
462
+ // export, since block workflows resolve leaf ids only.
463
+ const valueIds =
464
+ axisSpec === undefined && isGlobalPObjectId(columnId)
465
+ ? createColumnValueIds({ column: columnId, values: values.map(String) })
466
+ : undefined;
467
+ return textResult(
468
+ {
469
+ columnId,
470
+ ...(axisSpec !== undefined ? { axis: axisSpec.name } : {}),
471
+ valueType,
472
+ count: values.length,
473
+ overflow: response.overflow,
474
+ ...(naDropped > 0 ? { naDropped } : {}),
475
+ values,
476
+ ...(valueIds !== undefined ? { valueIds } : {}),
477
+ },
478
+ { hint: "Ask for fewer values: a smaller `limit`, or `search`." },
479
+ );
480
+ }
481
+
482
+ /** What get_column_values needs of a project to read a pool column: a frame over the column. */
483
+ export interface PoolFrameProject {
484
+ createPoolFrame(ids: readonly ColumnUniversalId[]): {
485
+ getValue(): Promise<PoolFrame>;
486
+ resetState(): void;
487
+ };
488
+ }
489
+
490
+ /** Input of {@link poolColumnValuesResult}: that of {@link columnValuesResult}, with no frame. */
491
+ export type PoolColumnValuesInput = Omit<ColumnValuesInput, "pFrameHandle">;
492
+
493
+ /**
494
+ * The distinct values of a column of the result pool, or of one of its axes (`get_column_values`
495
+ * with `projectId`): read from a frame built over the column alone and released after. Its
496
+ * `valueIds` name the column by its pool id, and come, as for a frame, only for a block's export
497
+ * itself: a discovered pool column gets none.
498
+ */
499
+ export async function poolColumnValuesResult(
500
+ project: PoolFrameProject,
501
+ projectId: ProjectId,
502
+ driver: DataQueryDriver,
503
+ input: PoolColumnValuesInput,
504
+ signal?: AbortSignal,
505
+ ) {
506
+ const id = columnIdFromAgent(input.columnId);
507
+ if (id === undefined)
508
+ return errorResult(
509
+ `${input.columnId} is not a column id of the result pool.`,
510
+ "Copy `columnId` whole from list_pool_columns.",
511
+ );
512
+ const frame = project.createPoolFrame([id]);
513
+ try {
514
+ let built: PoolFrame;
515
+ try {
516
+ built = await frame.getValue();
517
+ } catch (err) {
518
+ return errorResult(`Reading column ${id} failed: ${errorMessage(err)}`);
519
+ }
520
+ if (built.type === "refused") return poolColumnRefusedResult(built.refused, projectId);
521
+ return await columnValuesResult(
522
+ driver,
523
+ { ...input, pFrameHandle: built.handle, columnId: id },
524
+ signal,
525
+ );
526
+ } finally {
527
+ frame.resetState();
528
+ }
529
+ }
530
+
531
+ /** Why the values of pool columns cannot be read, by the issue the middle layer names. */
532
+ function poolColumnRefusedResult(refused: readonly PoolFrameRefusal[], projectId: ProjectId) {
533
+ const lines: string[] = [];
534
+ const hints = new Set<string>();
535
+ for (const r of refused) {
536
+ switch (r.issue) {
537
+ case "unknown":
538
+ lines.push(`${r.columnId}: not in the result pool of project ${projectId}.`);
539
+ hints.add("Ids follow current specs: list_pool_columns again.");
540
+ break;
541
+ case "noData":
542
+ lines.push(
543
+ `${r.columnId}: has no data; its block has not run, or exports it from a pre-run only.`,
544
+ );
545
+ hints.add("Run the block (run_block), wait for it (await_block_done), then try again.");
546
+ break;
547
+ case "notReady":
548
+ lines.push(`${r.columnId}: still being calculated by its block.`);
549
+ hints.add("Wait for the block (await_block_done), then try again.");
550
+ break;
551
+ case "failed":
552
+ lines.push(`${r.columnId}: its data failed: ${r.message ?? "no message"}.`);
553
+ hints.add("get_block_logs and get_project_overview tell why the block failed.");
554
+ break;
555
+ case "filtered":
556
+ lines.push(`${r.columnId}: filters an axis; its values would be the whole column's.`);
557
+ hints.add("Read the values of the column it filters, its `source`.");
558
+ break;
559
+ }
560
+ }
561
+ return errorResult(`The values cannot be read.\n${lines.join("\n")}`, [...hints].join(" "));
562
+ }
563
+
564
+ /** Input of {@link queryTableResult}. */
565
+ export type QueryTableInput = {
566
+ pTableHandle: PTableHandle;
567
+ columns?: number[];
568
+ offset: number;
569
+ limit: number;
570
+ transform?: string;
571
+ transformTimeout: number;
572
+ };
573
+
574
+ /** What {@link queryTableResult} knows of a table an agent built with create_table. */
575
+ export type AgentTableRead = {
576
+ /** What the table was built from may have changed since. */
577
+ stale: boolean;
578
+ };
579
+
580
+ const STALE_TABLE_NOTE =
581
+ "The columns this table was built from changed since (a block ran again, or the project " +
582
+ "changed): call create_table again for current data.";
583
+
584
+ /**
585
+ * Rows of a PTable (`query_table`). `agentTable`: the table is one an agent built with
586
+ * create_table; the answer says so when it is stale, and the hints name create_table.
587
+ */
588
+ export async function queryTableResult(
589
+ driver: DataQueryDriver,
590
+ input: QueryTableInput,
591
+ signal?: AbortSignal,
592
+ agentTable?: AgentTableRead,
593
+ ) {
594
+ const { pTableHandle, columns, transform, transformTimeout } = input;
595
+ const handle = pTableHandle;
596
+ const isAgentTable = agentTable !== undefined;
597
+ const staleFlag = agentTable?.stale === true ? { stale: true, staleNote: STALE_TABLE_NOTE } : {};
598
+
599
+ let spec: PTableColumnSpec[];
600
+ let totalRows: number;
601
+ try {
602
+ spec = await driver.getSpec(handle);
603
+ totalRows = (await driver.getShape(handle, signal)).rows;
604
+ } catch (err) {
605
+ if (isUnknownHandleError(err)) return staleHandleResult("PTable", pTableHandle, err);
606
+ if (signal?.aborted)
607
+ return errorResult(
608
+ `Reading the size of the table failed: ${errorMessage(err)}`,
609
+ "The read took too long or was cancelled: try again, or ask for a smaller table.",
610
+ );
611
+ throw err;
612
+ }
613
+
614
+ if (columns !== undefined && columns.length === 0)
615
+ return errorResult(
616
+ "`columns` is empty: there is nothing to read.",
617
+ "Leave `columns` out to read every column, or name the indices of the ones you need.",
618
+ );
619
+ const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);
620
+ const outOfRange = columnIndices.filter((i) => !Number.isInteger(i) || i < 0 || i >= spec.length);
621
+ if (outOfRange.length > 0)
622
+ return errorResult(
623
+ `No columns ${outOfRange.join(", ")}: the table has columns 0 to ${spec.length - 1}.`,
624
+ isAgentTable
625
+ ? "create_table listed the table's columns with their indices."
626
+ : "get_block_outputs lists the table's columns with their indices.",
627
+ );
628
+
629
+ const offset = clampInt(input.offset, 0, 0, Number.MAX_SAFE_INTEGER);
630
+ const effectiveLimit = clampInt(input.limit, 50, 0, QUERY_MAX_ROWS);
631
+ const length = Math.max(0, Math.min(effectiveLimit, totalRows - offset));
632
+ const range = { offset, length };
633
+
634
+ let vectors: PTableVector[];
635
+ try {
636
+ vectors = length === 0 ? [] : await driver.getData(handle, columnIndices, range, signal);
637
+ } catch (err) {
638
+ if (isUnknownHandleError(err)) return staleHandleResult("PTable", pTableHandle, err);
639
+ return errorResult(
640
+ `Reading rows ${offset} to ${offset + length} of columns [${columnIndices.join(", ")}] ` +
641
+ `failed: ${errorMessage(err)}`,
642
+ signal?.aborted
643
+ ? "The read took too long or was cancelled: ask for fewer rows or columns."
644
+ : isAgentTable
645
+ ? "Ask for fewer rows or columns; if a block it reads ran again, call create_table " +
646
+ "again."
647
+ : "Ask for fewer rows or columns; if the block ran again, get_block_outputs gives a " +
648
+ "fresh handle.",
649
+ );
650
+ }
651
+
652
+ const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;
653
+ const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));
654
+ const rows: unknown[][] = [];
655
+ for (let r = 0; r < actualRows; r++) rows.push(columnVectors.map((col) => col[r]));
656
+
657
+ const columnHeaders = columnIndices.map((idx: number) => {
658
+ const s = spec[idx];
659
+ return {
660
+ index: idx,
661
+ type: s.type,
662
+ ...(s.type === "column" ? { columnId: s.id } : {}),
663
+ name: s.spec.name,
664
+ label: readAnnotation(s.spec, Annotation.Label),
665
+ };
666
+ });
667
+ const bytesColumns = columnIndices.filter((_, i) => vectors[i]?.type === ValueType.Bytes);
668
+ const bytesNote =
669
+ bytesColumns.length > 0
670
+ ? {
671
+ note:
672
+ `Columns ${bytesColumns.join(", ")} hold binary values; they are given by their ` +
673
+ "size, `{bytes: N}`.",
674
+ }
675
+ : {};
676
+ const hasMore = offset + actualRows < totalRows;
677
+
678
+ if (transform) {
679
+ try {
680
+ const result = await safeEval(
681
+ transform,
682
+ { rows, columns: columnHeaders, offset, rowCount: actualRows, totalRows },
683
+ transformTimeout,
684
+ );
685
+ return textResult(result);
686
+ } catch (e: unknown) {
687
+ return transformFailedResult(
688
+ e,
689
+ "Check your JS expression syntax. Available variables: rows, columns, offset, rowCount, " +
690
+ "totalRows.",
691
+ );
692
+ }
693
+ }
694
+
695
+ return textResult(
696
+ {
697
+ ...staleFlag,
698
+ offset,
699
+ rowCount: actualRows,
700
+ totalRows,
701
+ hasMore,
702
+ ...(hasMore ? { nextOffset: offset + actualRows } : {}),
703
+ ...bytesNote,
704
+ columns: columnHeaders,
705
+ rows,
706
+ },
707
+ { hint: "Ask for fewer rows (`limit`) or columns (`columns`), or use `transform`." },
708
+ );
709
+ }
710
+
711
+ /** Options of {@link blockOutputsResult}. */
712
+ export type BlockOutputsOptions = {
713
+ /** The block the outputs are of: where its run stands, and whether its results follow its data. */
714
+ block: { calculationStatus: string; stale: boolean };
715
+ keys?: string[];
716
+ maxColumns: number;
717
+ };
718
+
719
+ /** The most characters of the error text of one output named in `keys`; it is cut in the middle. */
720
+ export const NAMED_OUTPUT_ERROR_CHARS = RESULT_CHAR_LIMIT / 2;
721
+
722
+ /**
723
+ * The outputs of a block for `get_block_outputs`: `{ calculationStatus, stale, note?, outputs }`,
724
+ * `outputs` output key → value, PFrame and PTable handles summed up (once per handle). An output
725
+ * that failed, or has no value, gives its `status` instead; a failed output named in `keys` also
726
+ * its error text, one not named a note saying how to read it. `note` says when the results are
727
+ * from an earlier configuration.
728
+ */
729
+ export async function blockOutputsResult(
730
+ outputs: Record<string, unknown>,
731
+ driver: OutputsDriver,
732
+ options: BlockOutputsOptions,
733
+ ) {
734
+ const all = Object.keys(outputs);
735
+ if (options.keys !== undefined) {
736
+ const unknown = options.keys.filter((k) => !Object.hasOwn(outputs, k));
737
+ if (unknown.length > 0)
738
+ return errorResult(
739
+ `The block has no outputs ${unknown.join(", ")}.`,
740
+ `Its outputs: ${all.join(", ") || "none"}.`,
741
+ );
742
+ }
743
+ const keys = options.keys ?? all;
744
+ const selected = Object.fromEntries(keys.map((k) => [k, outputs[k]]));
745
+ const summaries = new Map(summarizeOutputs(selected).map((s) => [s.key, s]));
746
+ const cache = new Map<string, unknown>();
747
+
748
+ const result: Record<string, unknown> = {};
749
+ for (const key of keys) {
750
+ const output = selected[key];
751
+ const summary = summaries.get(key);
752
+ if (summary === undefined || !summary.hasValue) {
753
+ const status = summary?.status ?? "error";
754
+ const error = status === "error" ? outputErrorText(output) : undefined;
755
+ result[key] =
756
+ error === undefined
757
+ ? { status }
758
+ : options.keys !== undefined
759
+ ? { status, error: clipMiddle(error, NAMED_OUTPUT_ERROR_CHARS) }
760
+ : { status, note: failedOutputsNote(1, key) };
761
+ continue;
762
+ }
763
+ const value = isPlainObject(output) ? output.value : undefined;
764
+ result[key] = await resolveHandlesInValue(value, driver, options.maxColumns, cache);
765
+ }
766
+
767
+ const { calculationStatus, stale } = options.block;
768
+ return textResult(
769
+ {
770
+ calculationStatus,
771
+ stale,
772
+ ...(calculationStatus === "Done" && stale ? { note: STALE_RESULTS_NOTE } : {}),
773
+ outputs: dedupeHandleSummaries(result),
774
+ },
775
+ {
776
+ hint:
777
+ "Ask for fewer outputs (`keys`), a smaller `maxColumns`, or read one output with " +
778
+ "get_block_state `transform`, e.g. `outputs.<key>?.value`.",
779
+ },
780
+ );
781
+ }
782
+
783
+ function errorMessage(err: unknown): string {
784
+ if (err instanceof Error) {
785
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : "";
786
+ return `${err.message}${cause}`;
787
+ }
788
+ return String(err);
789
+ }
790
+
121
791
  export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext): void {
792
+ const driver = (): DataQueryDriver => ctx.requireMl().internalDriverKit.pFrameDriver;
793
+
122
794
  server.registerTool(
123
795
  "get_block_outputs",
124
796
  {
125
797
  title: "Get Block Outputs",
126
798
  annotations: hints.read,
127
799
  description:
128
- "Get block output values as a JSON map. " +
129
- "PFrame/PTable handles are resolved inline to summaries with column specs and row counts. " +
800
+ "Get block output values: `{ calculationStatus, stale, note?, outputs }`, `outputs` a " +
801
+ "JSON map, output key → value. `stale: true` with `calculationStatus` Done means the " +
802
+ "results are from an earlier configuration (`note` says so); run_block runs it again. " +
803
+ "PFrame/PTable handles are resolved inline to summaries with column specs (with " +
804
+ "`columnId`, for get_column_values); query_table counts rows; " +
805
+ 'a handle already summed up earlier appears as `{ sameAs: "<path>" }`, the path to its summary ' +
806
+ "in this result written as a JS accessor (`main.table`, `list[0]`). " +
807
+ "An output that failed or has no value gives `{ status }` instead (error or pending); a " +
808
+ "failed one named in `keys` adds its `error` text. " +
130
809
  "Use this to discover block results and available data before querying tables.",
131
810
  inputSchema: z.object({
132
811
  projectId: projectIdInput.describe("Project ID"),
133
812
  blockId: blockIdInput.describe("Block ID"),
813
+ keys: z
814
+ .array(z.string())
815
+ .optional()
816
+ .describe("Only these outputs (default: all). get_block_state lists the output keys."),
134
817
  maxColumns: z
135
818
  .number()
136
819
  .optional()
@@ -138,29 +821,18 @@ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext):
138
821
  .describe("Max columns to show per PFrame/PTable summary (default 30)."),
139
822
  }),
140
823
  },
141
- 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>();
153
-
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;
159
- }
160
- result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);
161
- }
162
-
163
- return textResult(result);
824
+ async ({ projectId, blockId, keys, maxColumns }) => {
825
+ return await ctx.withProject(projectId, async (project) => {
826
+ const { block, error } = await findBlock(project, projectId, blockId);
827
+ if (error) return error;
828
+ const state = await project.getBlockState(blockId).getValue();
829
+ if (!state.outputs)
830
+ return errorResult(
831
+ "Block has no outputs yet.",
832
+ "The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.",
833
+ );
834
+ return await blockOutputsResult(state.outputs, driver(), { block, keys, maxColumns });
835
+ });
164
836
  },
165
837
  );
166
838
 
@@ -170,29 +842,104 @@ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext):
170
842
  title: "List Columns",
171
843
  annotations: hints.read,
172
844
  description:
173
- "List all columns in a PFrame with their specs. Use get_block_outputs first to find the PFrame handle.",
845
+ "List the columns of a PFrame, a page at a time: `{ total, offset, hasMore, " +
846
+ "nextOffset?, columns: [{ columnId, name, valueType, label, axes }] }`. Filter by " +
847
+ '`name` (part of the name or label), `valueType` or `annotations`; `detail: "full"` ' +
848
+ "adds domains, annotations and axis specs. `columnId` is the column's id as a block or " +
849
+ "table refers to it. Use get_block_outputs first to find the PFrame handle; " +
850
+ "get_column_values reads a column's values and their `valueIds` by its `columnId`.",
851
+ inputSchema: z.object({
852
+ projectId: projectIdInput.describe("Project the handle came from"),
853
+ pFrameHandle: pFrameHandleInput.describe(
854
+ "PFrame handle (64-char hex hash from get_block_outputs)",
855
+ ),
856
+ name: z
857
+ .string()
858
+ .optional()
859
+ .describe("Only columns whose name or label contains this (case-insensitive)."),
860
+ valueType: z
861
+ .string()
862
+ .optional()
863
+ .describe("Only columns of this value type: Int, Long, Float, Double, String…"),
864
+ annotations: z
865
+ .record(z.string(), z.string())
866
+ .optional()
867
+ .describe(
868
+ 'Only columns with these annotation values, e.g. `{"pl7.app/isAnchor": "true"}`.',
869
+ ),
870
+ detail: z
871
+ .enum(["brief", "full"])
872
+ .optional()
873
+ .describe("`brief` (default): ids, names, labels, axis names; `full`: whole specs."),
874
+ offset: z.number().optional().describe("Columns to skip (default 0)."),
875
+ limit: z
876
+ .number()
877
+ .optional()
878
+ .describe(
879
+ `Columns per page (default ${LIST_COLUMNS_DEFAULT}, at most ${LIST_COLUMNS_MAX}).`,
880
+ ),
881
+ }),
882
+ },
883
+ async ({ projectId, pFrameHandle, ...options }) => {
884
+ // The handle lives as long as its project stays loaded: the read holds it.
885
+ return await ctx.withProject(projectId, () =>
886
+ listColumnsResult(driver(), pFrameHandle, options),
887
+ );
888
+ },
889
+ );
890
+
891
+ server.registerTool(
892
+ "get_column_values",
893
+ {
894
+ title: "Get Column Values",
895
+ annotations: hints.read,
896
+ description:
897
+ "Get the distinct values of a column of a PFrame, or of one of its axes: the choices a " +
898
+ "block offers for a value of its data (a sample, a chain, a gene…). Result: `{ " +
899
+ "columnId, axis?, valueType, count, overflow, naDropped?, values, valueIds? }`; " +
900
+ "`valueIds` holds the ColumnValueId of each value, in the same order: copy it into a " +
901
+ "block that picks values. `valueIds` come only for a block's export itself, the " +
902
+ "columns a block can use; a column local to one block, a filtered, overridden or " +
903
+ "discovered column, or an axis, gives none. `overflow: true` means there are more " +
904
+ "than `limit` values. " +
905
+ "Missing values (NA) are left out. Column ids come from list_columns or the PFrame " +
906
+ "summaries of get_block_outputs; values of a pool column come by its `columnId` from " +
907
+ "list_pool_columns, without `pFrameHandle`.",
174
908
  inputSchema: z.object({
175
- pFrameHandle: z
909
+ projectId: projectIdInput.describe(
910
+ "Project the handle came from, or of the result-pool column.",
911
+ ),
912
+ pFrameHandle: pFrameHandleInput
913
+ .optional()
914
+ .describe(
915
+ "PFrame handle (64-char hex hash from get_block_outputs); omit for a pool column.",
916
+ ),
917
+ columnId: frameColumnIdInput.describe(
918
+ "Column id, from list_columns, or from list_pool_columns without `pFrameHandle`.",
919
+ ),
920
+ axis: z
921
+ .union([z.number(), z.string()])
922
+ .optional()
923
+ .describe("An axis of the column, by index or name: its values instead of the column's."),
924
+ search: z
176
925
  .string()
177
- .describe("PFrame handle (64-char hex hash from get_block_outputs)"),
926
+ .optional()
927
+ .describe("Only values that contain this text (case-insensitive; string values only)."),
928
+ limit: z
929
+ .number()
930
+ .optional()
931
+ .describe(
932
+ `The most values to return (default ${COLUMN_VALUES_DEFAULT}, at most ` +
933
+ `${COLUMN_VALUES_MAX}).`,
934
+ ),
178
935
  }),
179
936
  },
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),
194
- })),
195
- })),
937
+ async ({ pFrameHandle, projectId, ...input }, call) => {
938
+ const signal = readSignal(call?.mcpReq.signal);
939
+ return await ctx.withProject(projectId, (project) =>
940
+ pFrameHandle === undefined
941
+ ? poolColumnValuesResult(project, projectId, driver(), input, signal)
942
+ : columnValuesResult(driver(), { ...input, pFrameHandle }, signal),
196
943
  );
197
944
  },
198
945
  );
@@ -203,112 +950,59 @@ export function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext):
203
950
  title: "Query Table",
204
951
  annotations: hints.read,
205
952
  description:
206
- "Query data from a PTable. Returns rows as arrays of values. Use get_block_outputs first to find the PTable handle. " +
953
+ "Query data from a PTable. Returns rows as arrays of values, with `columns: [{ index, " +
954
+ "type, columnId?, name, label }]` (`columnId` on columns, not axes), `totalRows`, " +
955
+ "`hasMore` and `nextOffset` for the next page. At most " +
956
+ `${QUERY_MAX_ROWS} rows per call. The handle comes from get_block_outputs, or from ` +
957
+ "create_table for a table of your own; for such a table `stale: true` says its source " +
958
+ "columns changed since it was built (not given with `transform`). " +
207
959
  "Use `transform` to process results server-side and return only what you need.",
208
960
  inputSchema: z.object({
209
- pTableHandle: z
210
- .string()
211
- .describe("PTable handle (64-char hex hash from get_block_outputs)"),
961
+ projectId: projectIdInput.describe("Project the handle came from"),
962
+ pTableHandle: pTableHandleInput.describe(
963
+ "PTable handle (64-char hex hash from get_block_outputs or create_table)",
964
+ ),
212
965
  columns: z
213
966
  .array(z.number())
214
967
  .optional()
215
968
  .describe(
216
- "Column indices to retrieve (default: all). Use get_block_outputs to see column indices.",
969
+ "Column indices to retrieve (default: all; not empty). get_block_outputs and " +
970
+ "create_table list column indices. Binary columns give each value's size, " +
971
+ "`{bytes: N}`.",
217
972
  ),
218
973
  offset: z.number().optional().default(0).describe("Row offset (default 0)"),
219
- limit: z.number().optional().default(50).describe("Number of rows to return (default 50)."),
220
- maxLimit: z
974
+ limit: z
221
975
  .number()
222
976
  .optional()
223
- .default(1000)
224
- .describe("Upper bound for limit (default 1000). Increase for large exports."),
977
+ .default(50)
978
+ .describe(`Number of rows to return (default 50, at most ${QUERY_MAX_ROWS}).`),
225
979
  transform: z
226
980
  .string()
227
981
  .optional()
228
982
  .describe(
229
983
  "JS expression evaluated server-side against query results. " +
230
- "Available variables: `rows` (array of row arrays), `columns` (column headers), `offset`, `rowCount`. " +
984
+ "Available variables: `rows` (array of row arrays), `columns` (column headers), " +
985
+ "`offset`, `rowCount`, `totalRows`. " +
231
986
  "Example: `rows.map(r => r[0])` — extract first column only.",
232
987
  ),
233
988
  transformTimeout: z
234
989
  .number()
235
990
  .optional()
236
991
  .default(5000)
237
- .describe("Timeout in ms for transform evaluation (default 5000)."),
992
+ .describe(expressionTimeoutText("transform evaluation", 5000)),
238
993
  }),
239
994
  },
240
- async ({ pTableHandle, columns, offset, limit, maxLimit, transform, transformTimeout }) => {
241
- const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;
242
- const handle = pTableHandle as PTableHandle;
243
-
244
- let spec;
245
- try {
246
- spec = await pFrameDriver.getSpec(handle);
247
- } catch (err) {
248
- return textResult({ error: `getSpec failed: ${err}` });
249
- }
250
-
251
- const effectiveLimit = Math.min(limit, maxLimit);
252
- const range = { offset, length: effectiveLimit };
253
-
254
- // If no columns specified, get all
255
- const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);
256
-
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
- }
267
-
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
- }
274
-
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
- });
284
-
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
- );
303
- }
304
- }
305
-
306
- return textResult({
307
- offset,
308
- rowCount: actualRows,
309
- columns: columnHeaders,
310
- rows,
311
- });
312
- },
995
+ async (input, call) =>
996
+ // The handle lives as long as its project stays loaded: the read holds it. A table of the
997
+ // agent's own counts as used, so its idle time starts again.
998
+ await ctx.withProject(input.projectId, async (_project, ml) => {
999
+ const table = ctx.agentTables.use(input.pTableHandle);
1000
+ return await queryTableResult(
1001
+ ml.internalDriverKit.pFrameDriver,
1002
+ input,
1003
+ readSignal(call?.mcpReq.signal),
1004
+ table === undefined ? undefined : { stale: table.stale },
1005
+ );
1006
+ }),
313
1007
  );
314
1008
  }