@milaboratories/pl-mcp-server 54.0.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 +15 -25
  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 +15 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +15 -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 +58 -8
  14. package/dist/project-holds.cjs.map +1 -1
  15. package/dist/project-holds.js +58 -8
  16. package/dist/project-holds.js.map +1 -1
  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 +40 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +40 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +48 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +21 -20
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +48 -18
  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 -73
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -75
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +3 -0
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +3 -0
  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 +272 -4
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +270 -6
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +323 -42
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +317 -46
  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 +183 -70
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +177 -70
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +451 -113
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +446 -118
  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 +56 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +51 -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 +98 -19
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +95 -20
  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 +66 -19
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +66 -20
  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 +15 -12
  143. package/src/project-holds.test.ts +179 -0
  144. package/src/project-holds.ts +114 -12
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +54 -1
  148. package/src/server-log.ts +49 -27
  149. package/src/server.logging.test.ts +38 -46
  150. package/src/server.test.ts +151 -17
  151. package/src/server.ts +62 -34
  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 -123
  156. package/src/tools/block-action-context.ts +3 -0
  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 +623 -8
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +659 -66
  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 +336 -105
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +807 -157
  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 +67 -0
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +130 -21
  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 +135 -25
  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 +77 -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
@@ -0,0 +1,990 @@
1
+ import type {
2
+ ImportFileHandle,
3
+ LocalBlobHandle,
4
+ LocalImportFileHandle,
5
+ ProjectId,
6
+ RemoteBlobHandle,
7
+ StorageEntry,
8
+ StorageHandle,
9
+ TableRange,
10
+ } from "@milaboratories/pl-model-common";
11
+ import {
12
+ getFilePathFromHandle,
13
+ isImportFileHandleIndex,
14
+ isImportFileHandleUpload,
15
+ } from "@milaboratories/pl-model-common";
16
+ import * as fsp from "node:fs/promises";
17
+ import * as path from "node:path";
18
+ import { z } from "zod";
19
+ import { clamp, isPlainObject, trimChars } from "@milaboratories/helpers";
20
+ import { projectIdInput } from "./ids";
21
+ import { isImportHandle } from "./imports";
22
+ import { expressionTimeoutText, safeEval, SandboxError, TIMEOUT } from "./sandbox";
23
+ import type { ToolContext, ToolRegistrar } from "./types";
24
+ import {
25
+ errorResult,
26
+ hints,
27
+ readSignal,
28
+ RESULT_CHAR_LIMIT,
29
+ textResult,
30
+ transformFailedResult,
31
+ } from "./types";
32
+
33
+ /** Entries `list_files` gives by default. */
34
+ export const LIST_DEFAULT_LIMIT = 100;
35
+ /** The most entries one `list_files` page has. */
36
+ export const LIST_MAX_LIMIT = 500;
37
+ /** The most files one `get_file_handles` call makes handles for. */
38
+ export const MAX_HANDLES = 200;
39
+ /** Bytes `read_file` reads by default. */
40
+ export const READ_DEFAULT_BYTES = 16_384;
41
+ /** The most bytes `read_file` returns. */
42
+ export const READ_MAX_BYTES = 65_536;
43
+ /** The most bytes `read_file` reads for a `transform`. */
44
+ export const READ_MAX_TRANSFORM_BYTES = 4 * 1024 * 1024;
45
+ /** How long matching `pattern` against the names of one folder may take, in milliseconds. */
46
+ export const PATTERN_TIME_BUDGET_MS = 500;
47
+ /** Default timeout of a `transform`, in milliseconds. */
48
+ const DEFAULT_TRANSFORM_TIMEOUT = 5000;
49
+
50
+ /** What the file tools use of the middle layer's ls driver (`InternalLsDriver`). */
51
+ export type FileLsDriver = {
52
+ getStorageList(): Promise<StorageEntry[]>;
53
+ getLocalFileHandle(localPath: string): Promise<LocalImportFileHandle>;
54
+ getLocalFileSize(file: LocalImportFileHandle): Promise<number>;
55
+ getLocalFileContent(file: LocalImportFileHandle, range?: TableRange): Promise<Uint8Array>;
56
+ listRemoteFilesWithFileStats(
57
+ storage: StorageHandle,
58
+ fullPath: string,
59
+ ): Promise<{
60
+ entries: (
61
+ | { type: "dir"; name: string; fullPath: string; size: number }
62
+ | { type: "file"; name: string; fullPath: string; handle: ImportFileHandle; size: number }
63
+ )[];
64
+ }>;
65
+ };
66
+
67
+ /** What `read_file` uses of the middle layer's blob driver (`DownloadDriver`). */
68
+ export type FileBlobDriver = {
69
+ getLocalPath(handle: LocalBlobHandle): string;
70
+ getContent(
71
+ handle: LocalBlobHandle | RemoteBlobHandle,
72
+ options: { range?: { from: number; to: number }; signal?: AbortSignal },
73
+ ): Promise<Uint8Array>;
74
+ };
75
+
76
+ // ---------------------------------------------------------------------------------------------
77
+ // Handles parsed from strings: the only place their brands are put on.
78
+ // ---------------------------------------------------------------------------------------------
79
+
80
+ const LOCAL_BLOB_RE = /^blob\+local:\/\/download\/.*#.*$/;
81
+ const REMOTE_BLOB_RE = /^blob\+remote:\/\/download\/.+\/(\d+)#.*$/;
82
+
83
+ /** A blob handle of a block output, with the size a remote one carries. */
84
+ export type ParsedBlobHandle =
85
+ | { kind: "local"; handle: LocalBlobHandle }
86
+ | { kind: "remote"; handle: RemoteBlobHandle; size: number };
87
+
88
+ /** Parses a block-output blob handle (`blob+local://` or `blob+remote://`); else `undefined`. */
89
+ export function parseBlobHandle(s: string): ParsedBlobHandle | undefined {
90
+ if (LOCAL_BLOB_RE.test(s)) return { kind: "local", handle: s as LocalBlobHandle };
91
+ const remote = REMOTE_BLOB_RE.exec(s);
92
+ if (remote !== null)
93
+ return { kind: "remote", handle: s as RemoteBlobHandle, size: Number(remote[1]) };
94
+ return undefined;
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------------------------
98
+ // Storages
99
+ // ---------------------------------------------------------------------------------------------
100
+
101
+ /** Whether a storage is on this computer (`local://` handle) or a remote data library. */
102
+ export function storageKind(entry: StorageEntry): "local" | "remote" {
103
+ return entry.handle.startsWith("local://") ? "local" : "remote";
104
+ }
105
+
106
+ /** The root folder of a local storage, from its handle (`local://<id>/<encoded root>`). */
107
+ export function localStorageRoot(entry: StorageEntry): string {
108
+ return decodeURIComponent(entry.handle.slice(entry.handle.lastIndexOf("/") + 1));
109
+ }
110
+
111
+ /** Finds a storage by its id, then by its name. */
112
+ export function findStorage(storages: StorageEntry[], ref: string): StorageEntry | undefined {
113
+ return storages.find((s) => s.id === ref) ?? storages.find((s) => s.name === ref);
114
+ }
115
+
116
+ function unknownStorage(ref: string, storages: StorageEntry[]) {
117
+ return errorResult(
118
+ `No storage "${ref}".`,
119
+ `Storages: ${storages.map((s) => s.id).join(", ") || "none"}. list_files with no arguments lists them.`,
120
+ );
121
+ }
122
+
123
+ /** A path of a local storage made absolute: a relative one is under the storage's root. */
124
+ function localPath(entry: StorageEntry | undefined, p: string): string {
125
+ if (path.isAbsolute(p)) return p;
126
+ return path.join(entry === undefined ? "/" : localStorageRoot(entry), p);
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------------------------
130
+ // list_files
131
+ // ---------------------------------------------------------------------------------------------
132
+
133
+ /** One entry of a folder. */
134
+ export type ListedEntry = { name: string; type: "file" | "dir"; path: string; size?: number };
135
+
136
+ /** A page of a folder's entries. */
137
+ export type ListPage = {
138
+ total: number;
139
+ offset: number;
140
+ entries: ListedEntry[];
141
+ hasMore: boolean;
142
+ nextOffset?: number;
143
+ };
144
+
145
+ /** Options of {@link pageEntries}. */
146
+ export type PageOptions = {
147
+ /** A regular expression the name must match, tested in the sandbox ({@link matchNames}). */
148
+ pattern?: string;
149
+ type?: "file" | "dir";
150
+ offset: number;
151
+ limit: number;
152
+ };
153
+
154
+ /** A `pattern` of `list_files` that does not parse, or takes too long to match. */
155
+ export class PatternError extends Error {
156
+ constructor(
157
+ message: string,
158
+ readonly hint: string,
159
+ ) {
160
+ super(message);
161
+ this.name = "PatternError";
162
+ }
163
+ }
164
+
165
+ /**
166
+ * The indices of the names `pattern` matches. The caller's regular expression runs in the
167
+ * sandbox, all names in one evaluation under `budgetMs`: a pattern that backtracks
168
+ * catastrophically is stopped there instead of blocking the server. Throws a
169
+ * {@link PatternError} when the pattern does not parse or runs out of time.
170
+ */
171
+ export async function matchNames(
172
+ pattern: string,
173
+ names: string[],
174
+ budgetMs: number = PATTERN_TIME_BUDGET_MS,
175
+ ): Promise<number[]> {
176
+ try {
177
+ const hits = await safeEval(
178
+ "(() => { const re = new RegExp(pattern); const hits = []; " +
179
+ "for (let i = 0; i < names.length; i++) if (re.test(names[i])) hits.push(i); " +
180
+ "return hits; })()",
181
+ { pattern, names },
182
+ budgetMs,
183
+ );
184
+ return hits as number[];
185
+ } catch (e: unknown) {
186
+ if (e instanceof SandboxError && e.errorClass === TIMEOUT)
187
+ throw new PatternError(
188
+ `\`pattern\` took longer than ${budgetMs} ms to match ${names.length} ` +
189
+ `${names.length === 1 ? "name" : "names"}.`,
190
+ "Simplify it: avoid nested repetition such as `(a+)+`, or anchor it with ^…$.",
191
+ );
192
+ if (e instanceof SandboxError && e.errorClass === "SyntaxError")
193
+ throw new PatternError(
194
+ `\`pattern\` is not a valid regular expression: ${e.message}`,
195
+ "Give a JavaScript regular expression, e.g. `^S\\d+_R[12]\\.fastq\\.gz$`.",
196
+ );
197
+ throw e;
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Filters entries by `type` and `pattern` (tested against the name), sorts them by name and
203
+ * returns the page `[offset, offset + limit)`.
204
+ */
205
+ export async function pageEntries<E extends { name: string; type: "file" | "dir" }>(
206
+ entries: E[],
207
+ options: PageOptions,
208
+ ): Promise<{ total: number; page: E[]; hasMore: boolean; nextOffset?: number }> {
209
+ let matching = entries.filter((e) => options.type === undefined || e.type === options.type);
210
+ if (options.pattern !== undefined) {
211
+ const candidates = matching;
212
+ const hits = await matchNames(
213
+ options.pattern,
214
+ candidates.map((e) => e.name),
215
+ );
216
+ matching = hits.map((i) => candidates[i]);
217
+ }
218
+ matching.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
219
+ const page = matching.slice(options.offset, options.offset + options.limit);
220
+ const end = options.offset + page.length;
221
+ const hasMore = end < matching.length;
222
+ return { total: matching.length, page, hasMore, ...(hasMore ? { nextOffset: end } : {}) };
223
+ }
224
+
225
+ /** The page size asked for, clamped to `[1, LIST_MAX_LIMIT]`. */
226
+ export function clampLimit(limit: number | undefined, fallback: number, max: number): number {
227
+ if (limit === undefined || !Number.isFinite(limit)) return fallback;
228
+ return clamp(Math.floor(limit), 1, max);
229
+ }
230
+
231
+ /**
232
+ * Lists a local folder. Every entry's type comes from the folder listing (a symbolic link from a
233
+ * `stat` of its target); sizes are read with one `stat` per file of the returned page only, so a
234
+ * large folder costs one listing, not one `stat` per entry.
235
+ */
236
+ export async function listLocalFolder(dir: string, options: PageOptions): Promise<ListPage> {
237
+ const dirents = await fsp.readdir(dir, { withFileTypes: true });
238
+ const entries: ListedEntry[] = [];
239
+ for (const d of dirents) {
240
+ const full = path.join(dir, d.name);
241
+ let type: "file" | "dir" | undefined;
242
+ if (d.isFile()) type = "file";
243
+ else if (d.isDirectory()) type = "dir";
244
+ else if (d.isSymbolicLink()) {
245
+ try {
246
+ const st = await fsp.stat(full);
247
+ type = st.isFile() ? "file" : st.isDirectory() ? "dir" : undefined;
248
+ } catch {
249
+ type = undefined; // a dangling link
250
+ }
251
+ }
252
+ if (type !== undefined) entries.push({ name: d.name, type, path: full });
253
+ }
254
+ const { total, page, hasMore, nextOffset } = await pageEntries(entries, options);
255
+ const withSizes = await Promise.all(
256
+ page.map(async (e): Promise<ListedEntry> => {
257
+ if (e.type !== "file") return e;
258
+ try {
259
+ return { ...e, size: (await fsp.stat(e.path)).size };
260
+ } catch {
261
+ return e;
262
+ }
263
+ }),
264
+ );
265
+ return {
266
+ total,
267
+ offset: options.offset,
268
+ entries: withSizes,
269
+ hasMore,
270
+ ...(nextOffset !== undefined ? { nextOffset } : {}),
271
+ };
272
+ }
273
+
274
+ /** Lists a folder of a remote storage; the listing gives sizes. */
275
+ export async function listRemoteFolder(
276
+ ls: FileLsDriver,
277
+ storage: StorageEntry,
278
+ dir: string,
279
+ options: PageOptions,
280
+ ): Promise<ListPage> {
281
+ const listing = await ls.listRemoteFilesWithFileStats(storage.handle, dir);
282
+ const entries = listing.entries.map((e): ListedEntry => ({
283
+ name: e.name,
284
+ type: e.type,
285
+ path: e.fullPath,
286
+ ...(e.type === "file" ? { size: e.size } : {}),
287
+ }));
288
+ const { total, page, hasMore, nextOffset } = await pageEntries(entries, options);
289
+ return {
290
+ total,
291
+ offset: options.offset,
292
+ entries: page,
293
+ hasMore,
294
+ ...(nextOffset !== undefined ? { nextOffset } : {}),
295
+ };
296
+ }
297
+
298
+ // ---------------------------------------------------------------------------------------------
299
+ // get_file_handles
300
+ // ---------------------------------------------------------------------------------------------
301
+
302
+ /** The handle of one file, or why there is none. */
303
+ export type HandleResult =
304
+ | { path: string; handle: ImportFileHandle; size?: number }
305
+ | { path: string; error: string };
306
+
307
+ /** Makes the import handle of a local file; a folder or a relative path gets an error. */
308
+ export async function localFileHandle(ls: FileLsDriver, p: string): Promise<HandleResult> {
309
+ if (!path.isAbsolute(p)) return { path: p, error: "Not an absolute path." };
310
+ try {
311
+ const st = await fsp.stat(p);
312
+ if (!st.isFile()) return { path: p, error: "Not a file." };
313
+ return { path: p, handle: await ls.getLocalFileHandle(p), size: st.size };
314
+ } catch (e: unknown) {
315
+ return { path: p, error: errorText(e) };
316
+ }
317
+ }
318
+
319
+ /**
320
+ * The `index://` handles of files of a remote storage. A handle carries what the storage's
321
+ * listing gives, so the folder of each file is listed (once per folder) and the file looked up in
322
+ * it by its full path.
323
+ */
324
+ export async function remoteFileHandles(
325
+ ls: FileLsDriver,
326
+ storage: StorageEntry,
327
+ paths: string[],
328
+ ): Promise<HandleResult[]> {
329
+ const folderOf = (p: string) => {
330
+ const trimmed = trimChars(p, ["/"]);
331
+ const slash = trimmed.lastIndexOf("/");
332
+ return slash < 0 ? "" : trimmed.slice(0, slash);
333
+ };
334
+ const listings = new Map<
335
+ string,
336
+ Promise<Awaited<ReturnType<FileLsDriver["listRemoteFilesWithFileStats"]>>>
337
+ >();
338
+ return await Promise.all(
339
+ paths.map(async (p): Promise<HandleResult> => {
340
+ const folder = folderOf(p);
341
+ let listing = listings.get(folder);
342
+ if (listing === undefined) {
343
+ listing = ls.listRemoteFilesWithFileStats(storage.handle, folder);
344
+ listings.set(folder, listing);
345
+ }
346
+ try {
347
+ const { entries } = await listing;
348
+ const entry = entries.find(
349
+ (e) => e.fullPath === p || trimChars(e.fullPath, ["/"]) === trimChars(p, ["/"]),
350
+ );
351
+ if (entry === undefined) return { path: p, error: "No such file in the storage." };
352
+ if (entry.type !== "file") return { path: p, error: "Not a file." };
353
+ return { path: p, handle: entry.handle, size: entry.size };
354
+ } catch (e: unknown) {
355
+ return { path: p, error: errorText(e) };
356
+ }
357
+ }),
358
+ );
359
+ }
360
+
361
+ // ---------------------------------------------------------------------------------------------
362
+ // read_file
363
+ // ---------------------------------------------------------------------------------------------
364
+
365
+ /** A range clamped to a size: `[from, to)`, empty at or past the end. */
366
+ export function clampRange(
367
+ offset: number,
368
+ length: number,
369
+ size: number,
370
+ ): { from: number; to: number } {
371
+ const from = clamp(offset, 0, size);
372
+ return { from, to: clamp(from + length, from, size) };
373
+ }
374
+
375
+ /** The most bytes of one UTF-8 character: the shortest read, so that text always advances. */
376
+ export const UTF8_MAX_BYTES = 4;
377
+
378
+ function isUtf8Continuation(b: number): boolean {
379
+ return (b & 0xc0) === 0x80;
380
+ }
381
+
382
+ /** Decoded content: text when it is UTF-8 without NUL bytes, otherwise binary. */
383
+ export type Decoded =
384
+ | { encoding: "utf-8"; text: string; skippedBytes: number; usedBytes: number }
385
+ | { encoding: "binary"; usedBytes: number };
386
+
387
+ /**
388
+ * Decodes `bytes`, a range of a file, as text of whole characters:
389
+ * - `skipLead` (the range does not start the file): up to 3 leading continuation bytes, the tail
390
+ * of a character begun before the range, are skipped (`skippedBytes`);
391
+ * - unless `atEnd` (the range ends the file), an incomplete character at the end is left for the
392
+ * next read: `usedBytes` stops before it.
393
+ *
394
+ * Content that is not UTF-8, or holds NUL bytes, is binary: all the bytes, none skipped.
395
+ */
396
+ export function decodeContent(
397
+ bytes: Uint8Array,
398
+ options: { skipLead?: boolean; atEnd?: boolean } = {},
399
+ ): Decoded {
400
+ let start = 0;
401
+ if (options.skipLead === true)
402
+ while (start < UTF8_MAX_BYTES - 1 && start < bytes.length && isUtf8Continuation(bytes[start]))
403
+ start++;
404
+ const part = bytes.subarray(start);
405
+ if (part.includes(0)) return { encoding: "binary", usedBytes: bytes.length };
406
+ try {
407
+ const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(part, {
408
+ stream: options.atEnd !== true,
409
+ });
410
+ return {
411
+ encoding: "utf-8",
412
+ text,
413
+ skippedBytes: start,
414
+ usedBytes: Buffer.byteLength(text, "utf8"),
415
+ };
416
+ } catch {
417
+ return { encoding: "binary", usedBytes: bytes.length };
418
+ }
419
+ }
420
+
421
+ /** Characters of a `read_file` result the content may take; the rest is for the other fields. */
422
+ export const READ_CONTENT_CHARS = RESULT_CHAR_LIMIT - 1000;
423
+
424
+ /**
425
+ * Cuts decoded content so that the result stays under the result size limit: text to the
426
+ * characters whose JSON fits in {@link READ_CONTENT_CHARS}, base64 to the bytes whose encoding
427
+ * fits. `usedBytes` then counts the bytes kept, so `nextOffset` continues after them.
428
+ */
429
+ export function fitToResult(decoded: Decoded, base64: boolean): Decoded {
430
+ if (decoded.encoding === "binary") {
431
+ if (!base64) return decoded;
432
+ const maxBytes = Math.floor(READ_CONTENT_CHARS / 4) * 3;
433
+ return decoded.usedBytes <= maxBytes ? decoded : { encoding: "binary", usedBytes: maxBytes };
434
+ }
435
+ if (JSON.stringify(decoded.text).length <= READ_CONTENT_CHARS) return decoded;
436
+ // The longest prefix whose JSON fits; a cut never splits a surrogate pair.
437
+ let lo = 0;
438
+ let hi = decoded.text.length;
439
+ while (lo < hi) {
440
+ const mid = Math.ceil((lo + hi) / 2);
441
+ if (JSON.stringify(decoded.text.slice(0, mid)).length <= READ_CONTENT_CHARS) lo = mid;
442
+ else hi = mid - 1;
443
+ }
444
+ let cut = lo;
445
+ const code = decoded.text.charCodeAt(cut - 1);
446
+ if (cut > 0 && code >= 0xd800 && code <= 0xdbff) cut--;
447
+ const text = decoded.text.slice(0, cut);
448
+ return { ...decoded, text, usedBytes: Buffer.byteLength(text, "utf8") };
449
+ }
450
+
451
+ /** What a source of `read_file` reads: its size, and a range of its bytes. */
452
+ type ReadSource = {
453
+ kind: "local" | "upload" | "blob";
454
+ size: number;
455
+ read(range: { from: number; to: number }): Promise<Uint8Array>;
456
+ };
457
+
458
+ /**
459
+ * Reads ranges of a local file through the ls driver, by its import handle. The driver takes no
460
+ * signal, so the wait for a read ends when `signal` aborts; the read itself goes on and closes its
461
+ * file.
462
+ */
463
+ function localSource(
464
+ ls: FileLsDriver,
465
+ kind: "local" | "upload",
466
+ handle: LocalImportFileHandle,
467
+ size: number,
468
+ signal: AbortSignal,
469
+ ): ReadSource {
470
+ return {
471
+ kind,
472
+ size,
473
+ read: (range) =>
474
+ raceAbort(
475
+ () => ls.getLocalFileContent(handle, { offset: range.from, length: range.to - range.from }),
476
+ signal,
477
+ ),
478
+ };
479
+ }
480
+
481
+ /**
482
+ * The result of `start()`, or a rejection with the reason of `signal` when it aborts first. An
483
+ * aborted signal does not start the work; a work that fails after the abort fails unobserved.
484
+ */
485
+ function raceAbort<T>(start: () => Promise<T>, signal: AbortSignal): Promise<T> {
486
+ if (signal.aborted) return Promise.reject(signal.reason);
487
+ const work = start();
488
+ work.catch(() => {});
489
+ return new Promise<T>((resolve, reject) => {
490
+ const onAbort = () => reject(signal.reason);
491
+ signal.addEventListener("abort", onAbort, { once: true });
492
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
493
+ });
494
+ }
495
+
496
+ /** The error a `read_file` of an `index://` handle gets. */
497
+ export const INDEX_HANDLE_ERROR =
498
+ "An index:// handle names a file in a remote data library; MCP cannot read it from here.";
499
+ export const INDEX_HANDLE_HINT =
500
+ "Give the handle to the block (set_block_data) and read what the block makes of it: blocks " +
501
+ "that read such a file in their pre-run give its content, or a part of it, as an output blob " +
502
+ "(a blob+remote:// or blob+local:// handle in get_block_state outputs); read_file reads that " +
503
+ "handle.";
504
+
505
+ /** Resolves what `read_file` was given to a source; an error result when it cannot be read. */
506
+ async function resolveSource(
507
+ ls: FileLsDriver,
508
+ blob: FileBlobDriver,
509
+ input: { path?: string; handle?: string },
510
+ signal: AbortSignal,
511
+ ): Promise<ReadSource | ReturnType<typeof errorResult>> {
512
+ if (input.path !== undefined) {
513
+ const p = input.path;
514
+ if (!path.isAbsolute(p)) return errorResult(`Not an absolute path: ${p}`);
515
+ const st = await fsp.stat(p);
516
+ if (!st.isFile()) return errorResult(`Not a file: ${p}`);
517
+ return localSource(ls, "local", await ls.getLocalFileHandle(p), st.size, signal);
518
+ }
519
+ const handle = input.handle ?? "";
520
+ if (isImportHandle(handle)) {
521
+ if (isImportFileHandleIndex(handle)) return errorResult(INDEX_HANDLE_ERROR, INDEX_HANDLE_HINT);
522
+ const upload = handle as LocalImportFileHandle;
523
+ return localSource(ls, "upload", upload, await ls.getLocalFileSize(upload), signal);
524
+ }
525
+ const parsed = parseBlobHandle(handle);
526
+ if (parsed !== undefined) {
527
+ const size =
528
+ parsed.kind === "remote"
529
+ ? parsed.size
530
+ : (await fsp.stat(blob.getLocalPath(parsed.handle))).size;
531
+ return {
532
+ kind: "blob",
533
+ size,
534
+ read: (range) => blob.getContent(parsed.handle, { range, signal }),
535
+ };
536
+ }
537
+ return errorResult(
538
+ "Not a handle read_file reads.",
539
+ "Give `path` (an absolute local path), an upload:// import handle (get_file_handles), or a " +
540
+ "blob+local:// / blob+remote:// handle from a block's outputs.",
541
+ );
542
+ }
543
+
544
+ // ---------------------------------------------------------------------------------------------
545
+ // Import handles written into block data
546
+ // ---------------------------------------------------------------------------------------------
547
+
548
+ /** One import handle in a value, with its JSON path. */
549
+ export type FoundHandle = { path: string; handle: ImportFileHandle };
550
+
551
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
552
+
553
+ /** Every import handle in `value`, with its path (`a.b[2]`, `(root)` for the value itself). */
554
+ export function importHandlesIn(value: unknown): FoundHandle[] {
555
+ const found: FoundHandle[] = [];
556
+ const walk = (v: unknown, p: string) => {
557
+ if (isImportHandle(v)) found.push({ path: p || "(root)", handle: v });
558
+ else if (Array.isArray(v)) v.forEach((item, i) => walk(item, `${p}[${i}]`));
559
+ else if (isPlainObject(v))
560
+ for (const [k, item] of Object.entries(v))
561
+ walk(
562
+ item,
563
+ IDENTIFIER.test(k) ? (p === "" ? k : `${p}.${k}`) : `${p}[${JSON.stringify(k)}]`,
564
+ );
565
+ };
566
+ walk(value, "");
567
+ return found;
568
+ }
569
+
570
+ /** A handle a write would store that does not check out. */
571
+ export type InvalidHandle = { path: string; error: string };
572
+
573
+ /**
574
+ * Checks the import handles `next` carries that `current` does not: an `upload://` handle must be
575
+ * signed by this computer and name a file that exists unchanged since the handle was made; an
576
+ * `index://` handle must parse. Handles already stored are not checked: their file may have
577
+ * changed since, and that must not keep the rest of the data from being written.
578
+ */
579
+ export async function invalidNewImportHandles(
580
+ ls: Pick<FileLsDriver, "getLocalFileSize">,
581
+ current: unknown,
582
+ next: unknown,
583
+ ): Promise<InvalidHandle[]> {
584
+ const stored = new Set(importHandlesIn(current).map((h) => h.handle));
585
+ const fresh = importHandlesIn(next).filter((h) => !stored.has(h.handle));
586
+ const unique = [...new Set(fresh.map((h) => h.handle))];
587
+ const problems = new Map(
588
+ await Promise.all(unique.map(async (h) => [h, await handleProblem(ls, h)] as const)),
589
+ );
590
+ return fresh.flatMap(({ path: p, handle }) => {
591
+ const error = problems.get(handle);
592
+ return error === undefined ? [] : [{ path: p, error }];
593
+ });
594
+ }
595
+
596
+ /** What is wrong with an import handle a write would store; `undefined` when it checks out. */
597
+ async function handleProblem(
598
+ ls: Pick<FileLsDriver, "getLocalFileSize">,
599
+ handle: ImportFileHandle,
600
+ ): Promise<string | undefined> {
601
+ if (isImportFileHandleUpload(handle)) {
602
+ try {
603
+ await ls.getLocalFileSize(handle as LocalImportFileHandle);
604
+ return undefined;
605
+ } catch (e: unknown) {
606
+ return errorText(e);
607
+ }
608
+ }
609
+ try {
610
+ getFilePathFromHandle(handle);
611
+ return undefined;
612
+ } catch {
613
+ return "The index:// handle does not parse.";
614
+ }
615
+ }
616
+
617
+ /** The most invalid handles a refusal names. */
618
+ const MAX_INVALID_NAMED = 10;
619
+
620
+ /** The refusal of a write that carries invalid new import handles. */
621
+ export function invalidHandlesResult(invalid: InvalidHandle[]) {
622
+ const named = invalid
623
+ .slice(0, MAX_INVALID_NAMED)
624
+ .map((h) => `${h.path}: ${h.error}`)
625
+ .join("; ");
626
+ const more =
627
+ invalid.length > MAX_INVALID_NAMED ? ` (and ${invalid.length - MAX_INVALID_NAMED} more)` : "";
628
+ return errorResult(
629
+ `The new data has ${invalid.length} import handle(s) that do not check out: ${named}${more}. ` +
630
+ "Nothing was changed.",
631
+ "Make the handles with get_file_handles and copy them as they are. A handle of a local file " +
632
+ "stops checking out when the file is changed, moved or deleted: make a new one.",
633
+ );
634
+ }
635
+
636
+ function errorText(e: unknown): string {
637
+ return e instanceof Error ? e.message : String(e);
638
+ }
639
+
640
+ // ---------------------------------------------------------------------------------------------
641
+ // Tools
642
+ // ---------------------------------------------------------------------------------------------
643
+
644
+ /** Input of `list_files`. */
645
+ export type ListFilesInput = {
646
+ storage?: string;
647
+ path?: string;
648
+ pattern?: string;
649
+ type?: "file" | "dir";
650
+ offset?: number;
651
+ limit?: number;
652
+ };
653
+
654
+ /** The storages, or a page of a folder's entries (`list_files`). */
655
+ export async function listFilesResult(ls: FileLsDriver, input: ListFilesInput) {
656
+ const { storage, path: dir, pattern, type, offset, limit } = input;
657
+ const storages = await ls.getStorageList();
658
+ if (storage === undefined && dir === undefined)
659
+ return textResult({
660
+ storages: storages.map((s) => ({
661
+ id: s.id,
662
+ name: s.name,
663
+ kind: storageKind(s),
664
+ initialPath: s.initialFullPath,
665
+ })),
666
+ });
667
+
668
+ const options: PageOptions = {
669
+ pattern: pattern === undefined || pattern === "" ? undefined : pattern,
670
+ type,
671
+ offset: Math.max(0, Math.floor(offset ?? 0)),
672
+ limit: clampLimit(limit, LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT),
673
+ };
674
+
675
+ const entry = storage === undefined ? undefined : findStorage(storages, storage);
676
+ if (storage !== undefined && entry === undefined) return unknownStorage(storage, storages);
677
+ try {
678
+ if (entry !== undefined && storageKind(entry) === "remote") {
679
+ const folder = dir ?? "";
680
+ return textResult({
681
+ storage: entry.id,
682
+ path: folder,
683
+ ...(await listRemoteFolder(ls, entry, folder, options)),
684
+ });
685
+ }
686
+ const folder = localPath(entry, dir ?? entry?.initialFullPath ?? "/");
687
+ return textResult({
688
+ ...(entry !== undefined ? { storage: entry.id } : {}),
689
+ path: folder,
690
+ ...(await listLocalFolder(folder, options)),
691
+ });
692
+ } catch (e: unknown) {
693
+ if (e instanceof PatternError) return errorResult(e.message, e.hint);
694
+ return errorResult(
695
+ `Cannot list ${dir ?? "the folder"}: ${errorText(e)}`,
696
+ "Check the path with list_files on its parent folder.",
697
+ );
698
+ }
699
+ }
700
+
701
+ /** Import handles for files (`get_file_handles`). */
702
+ export async function fileHandlesResult(
703
+ ls: FileLsDriver,
704
+ input: { paths: string[]; storage?: string },
705
+ ) {
706
+ const { paths, storage } = input;
707
+ if (paths.length === 0) return errorResult("`paths` is empty.");
708
+ if (paths.length > MAX_HANDLES)
709
+ return errorResult(
710
+ `${paths.length} paths; at most ${MAX_HANDLES} per call.`,
711
+ "Split the paths over several calls.",
712
+ );
713
+ let results: HandleResult[];
714
+ if (storage === undefined) {
715
+ results = await Promise.all(paths.map((p) => localFileHandle(ls, p)));
716
+ } else {
717
+ const storages = await ls.getStorageList();
718
+ const entry = findStorage(storages, storage);
719
+ if (entry === undefined) return unknownStorage(storage, storages);
720
+ results =
721
+ storageKind(entry) === "remote"
722
+ ? await remoteFileHandles(ls, entry, paths)
723
+ : await Promise.all(paths.map((p) => localFileHandle(ls, localPath(entry, p))));
724
+ }
725
+ const handles = results.filter((r) => "handle" in r);
726
+ const errors = results.filter((r) => "error" in r);
727
+ return textResult({ handles, ...(errors.length > 0 ? { errors } : {}) });
728
+ }
729
+
730
+ /** Input of `read_file`. */
731
+ export type ReadFileInput = {
732
+ path?: string;
733
+ handle?: string;
734
+ /** The project whose block outputs gave a blob `handle`. */
735
+ projectId?: ProjectId;
736
+ offset?: number;
737
+ length?: number;
738
+ base64?: boolean;
739
+ transform?: string;
740
+ transformTimeout?: number;
741
+ };
742
+
743
+ /** Runs `read` holding the project `projectId` (the server's `withProject`). */
744
+ export type ProjectHold = <T>(projectId: ProjectId, read: () => Promise<T>) => Promise<T>;
745
+
746
+ /**
747
+ * A bounded read of a file (`read_file`). A blob handle is read inside `holdProject` on the
748
+ * project that gave it: while that project is held, it is not unloaded, so the block's downloaded
749
+ * file keeps its owner and is not deleted from the cache between two pages of a read.
750
+ */
751
+ export async function readFileResult(
752
+ ls: FileLsDriver,
753
+ blob: FileBlobDriver,
754
+ input: ReadFileInput,
755
+ signal: AbortSignal,
756
+ holdProject?: ProjectHold,
757
+ ): Promise<ReturnType<typeof textResult> | ReturnType<typeof errorResult>> {
758
+ if ((input.path === undefined) === (input.handle === undefined))
759
+ return errorResult("Give either `path` or `handle`.");
760
+ const isBlob = input.handle !== undefined && parseBlobHandle(input.handle) !== undefined;
761
+ if (isBlob && holdProject !== undefined) {
762
+ if (input.projectId === undefined)
763
+ return errorResult(
764
+ "A blob handle is read with `projectId`: the project whose block outputs gave it.",
765
+ );
766
+ return await holdProject(input.projectId, () => readFileResult(ls, blob, input, signal));
767
+ }
768
+
769
+ let source: ReadSource | ReturnType<typeof errorResult>;
770
+ try {
771
+ source = await resolveSource(ls, blob, input, signal);
772
+ } catch (e: unknown) {
773
+ return errorResult(
774
+ `Cannot read ${input.path ?? "the handle"}: ${errorText(e)}`,
775
+ input.path === undefined
776
+ ? "A handle of a local file stops working when the file changes; make a new one " +
777
+ "with get_file_handles. A blob handle comes from get_block_state outputs."
778
+ : undefined,
779
+ );
780
+ }
781
+ if ("isError" in source) return source;
782
+
783
+ const max = input.transform !== undefined ? READ_MAX_TRANSFORM_BYTES : READ_MAX_BYTES;
784
+ // A text read takes at least one whole character; a base64 read returns bytes as they are.
785
+ const min = input.base64 === true ? 1 : UTF8_MAX_BYTES;
786
+ const length = clamp(Math.floor(input.length ?? READ_DEFAULT_BYTES), min, max);
787
+ const range = clampRange(Math.floor(input.offset ?? 0), length, source.size);
788
+ let bytes: Uint8Array;
789
+ try {
790
+ bytes = range.to > range.from ? await source.read(range) : new Uint8Array(0);
791
+ } catch (e: unknown) {
792
+ return errorResult(
793
+ `Read failed: ${errorText(e)}`,
794
+ signal.aborted
795
+ ? "The read took too long or was cancelled: try again, or read a smaller range."
796
+ : undefined,
797
+ );
798
+ }
799
+ // A base64 read returns the bytes of the range as they are: text only when they are whole
800
+ // characters.
801
+ let decoded =
802
+ input.base64 === true
803
+ ? decodeContent(bytes, { atEnd: true })
804
+ : decodeContent(bytes, { skipLead: range.from > 0, atEnd: range.to >= source.size });
805
+ if (input.transform === undefined) decoded = fitToResult(decoded, input.base64 === true);
806
+ const skipped = decoded.encoding === "utf-8" ? decoded.skippedBytes : 0;
807
+ const used = decoded.usedBytes;
808
+ bytes = bytes.subarray(skipped, skipped + used);
809
+ const start = range.from + skipped;
810
+ const end = start + used;
811
+ const meta = {
812
+ source: source.kind,
813
+ size: source.size,
814
+ offset: start,
815
+ bytesRead: used,
816
+ eof: end >= source.size,
817
+ ...(end < source.size ? { nextOffset: end } : {}),
818
+ encoding: decoded.encoding,
819
+ };
820
+ const base64 = decoded.encoding === "binary" ? Buffer.from(bytes).toString("base64") : undefined;
821
+
822
+ if (input.transform !== undefined) {
823
+ try {
824
+ const result = await safeEval(
825
+ input.transform,
826
+ {
827
+ text: decoded.encoding === "utf-8" ? decoded.text : undefined,
828
+ base64,
829
+ size: meta.size,
830
+ offset: meta.offset,
831
+ bytesRead: meta.bytesRead,
832
+ eof: meta.eof,
833
+ },
834
+ input.transformTimeout ?? DEFAULT_TRANSFORM_TIMEOUT,
835
+ );
836
+ return textResult({ ...meta, result });
837
+ } catch (e: unknown) {
838
+ return transformFailedResult(
839
+ e,
840
+ "Check the expression. Available variables: text, base64, size, offset, bytesRead, eof.",
841
+ );
842
+ }
843
+ }
844
+ if (decoded.encoding === "utf-8") return textResult({ ...meta, text: decoded.text });
845
+ return textResult(input.base64 === true ? { ...meta, base64 } : meta);
846
+ }
847
+
848
+ export function registerFileTools(server: ToolRegistrar, ctx: ToolContext): void {
849
+ const drivers = () => {
850
+ const kit = ctx.requireMl().internalDriverKit;
851
+ const ls: FileLsDriver = kit.lsDriver;
852
+ const blob: FileBlobDriver = kit.blobDriver;
853
+ return { ls, blob };
854
+ };
855
+
856
+ server.registerTool(
857
+ "list_files",
858
+ {
859
+ title: "List Files",
860
+ annotations: hints.read,
861
+ description:
862
+ "List the storages files can be taken from, or the entries of a folder in one. With no " +
863
+ "arguments: the storages, `[{ id, name, kind: local|remote, initialPath }]` (local: " +
864
+ "this computer; remote: data libraries of the server). With `storage` (an id) and " +
865
+ "`path`: the folder's entries `{ name, type: file|dir, path, size? }`, sorted by name, " +
866
+ "a page at a time (`total`, `hasMore`, `nextOffset`). `path` alone lists a folder of " +
867
+ "this computer. Listing gives no handles: get_file_handles makes them for the files " +
868
+ "you pick, and that is how files are given to a block.",
869
+ inputSchema: z.object({
870
+ storage: z
871
+ .string()
872
+ .optional()
873
+ .describe("Storage id (or name) from the storage list. Omit for this computer."),
874
+ path: z
875
+ .string()
876
+ .optional()
877
+ .describe(
878
+ "Folder to list. Local: absolute, or relative to the storage's root; omitted, the " +
879
+ "storage's initial folder. Remote: the folder's path in the storage, '' for its top.",
880
+ ),
881
+ pattern: z
882
+ .string()
883
+ .optional()
884
+ .describe(
885
+ "JavaScript regular expression the entry name must match (tested anywhere in the " +
886
+ "name: anchor it with ^…$ for the whole name), e.g. `^S\\d+_R[12]\\.fastq\\.gz$`. " +
887
+ `Matching one folder may take at most ${PATTERN_TIME_BUDGET_MS} ms.`,
888
+ ),
889
+ type: z.enum(["file", "dir"]).optional().describe("Only files, or only folders."),
890
+ offset: z.number().optional().describe("Entries to skip (default 0)."),
891
+ limit: z
892
+ .number()
893
+ .optional()
894
+ .describe(`Entries per page (default ${LIST_DEFAULT_LIMIT}, at most ${LIST_MAX_LIMIT}).`),
895
+ }),
896
+ },
897
+ async (input) => listFilesResult(drivers().ls, input),
898
+ );
899
+
900
+ server.registerTool(
901
+ "get_file_handles",
902
+ {
903
+ title: "Get File Handles",
904
+ annotations: hints.read,
905
+ description:
906
+ "Make import handles for files: this is how files are given to a block. Put a handle " +
907
+ "into the block's data where the block takes a file (set_block_data). When the block " +
908
+ "uses the file (its pre-run, which follows every change of the data, or its run), a " +
909
+ "file of this computer is uploaded to the server, a file of a data library is used " +
910
+ "where it is. get_block_state shows the progress under `imports`; await_block_done " +
911
+ "with waitForImports waits for it.\n\n" +
912
+ "`paths`: absolute paths of files of this computer, or with `storage`, paths in that " +
913
+ "storage (as list_files gives them). Result: `{ handles: [{ path, handle, size? }], " +
914
+ `errors?: [{ path, error }] }\`, in the order asked. At most ${MAX_HANDLES} files per ` +
915
+ "call. Copy handles as they are; a local file's handle stops working when the file " +
916
+ "changes.",
917
+ inputSchema: z.object({
918
+ paths: z.array(z.string()).describe("File paths."),
919
+ storage: z
920
+ .string()
921
+ .optional()
922
+ .describe("Storage id (or name) the paths are in. Omit for this computer."),
923
+ }),
924
+ },
925
+ async (input) => fileHandlesResult(drivers().ls, input),
926
+ );
927
+
928
+ server.registerTool(
929
+ "read_file",
930
+ {
931
+ title: "Read File",
932
+ annotations: hints.read,
933
+ description:
934
+ "Read a part of a file: a local file (`path`), an upload:// import handle, or a blob " +
935
+ "handle from a block's outputs (blob+local://, blob+remote://). Reads " +
936
+ `\`length\` bytes from \`offset\` (default ${READ_DEFAULT_BYTES}, at most ` +
937
+ `${READ_MAX_BYTES}); a range past the end is cut to it. Result: \`{ size, offset, ` +
938
+ "bytesRead, eof, nextOffset?, encoding: utf-8|binary, text? , base64? }`: text when the " +
939
+ "bytes are UTF-8, otherwise only their count (base64 with `base64: true`). Text keeps " +
940
+ "whole characters: a range that starts inside one starts after it (`offset` says where) " +
941
+ "and one that ends inside one stops before it (`nextOffset`). With `base64: true` the " +
942
+ "range is returned as it is. With " +
943
+ "`transform` the server reads up to 4 MiB and returns only the expression's value. " +
944
+ "index:// handles (files of a data library) cannot be read here: read the block's " +
945
+ "output blob instead.",
946
+ inputSchema: z.object({
947
+ path: z.string().optional().describe("Absolute path of a local file."),
948
+ handle: z
949
+ .string()
950
+ .optional()
951
+ .describe("An upload:// import handle, or a blob handle from a block's outputs."),
952
+ projectId: projectIdInput
953
+ .optional()
954
+ .describe("With a blob handle (required): the project whose block outputs gave it."),
955
+ offset: z.number().optional().describe("Byte to start at (default 0)."),
956
+ length: z
957
+ .number()
958
+ .optional()
959
+ .describe(
960
+ `Bytes to read (default ${READ_DEFAULT_BYTES}; at most ${READ_MAX_BYTES}, or ` +
961
+ `${READ_MAX_TRANSFORM_BYTES} with \`transform\`).`,
962
+ ),
963
+ base64: z
964
+ .boolean()
965
+ .optional()
966
+ .describe("Return binary content as base64 (default false: its byte count only)."),
967
+ transform: z
968
+ .string()
969
+ .optional()
970
+ .describe(
971
+ "JS expression evaluated in the server against the content: `text` (UTF-8 content, " +
972
+ "or undefined), `base64` (binary content, or undefined), `size`, `offset`, " +
973
+ "`bytesRead`, `eof`. Example: `text.split('\\n').slice(0, 3)` for the first lines.",
974
+ ),
975
+ transformTimeout: z
976
+ .number()
977
+ .optional()
978
+ .describe(expressionTimeoutText("the transform", DEFAULT_TRANSFORM_TIMEOUT)),
979
+ }),
980
+ },
981
+ async (input, call) =>
982
+ readFileResult(
983
+ drivers().ls,
984
+ drivers().blob,
985
+ input,
986
+ readSignal(call?.mcpReq.signal),
987
+ (projectId, read) => ctx.withProject(projectId, () => read()),
988
+ ),
989
+ );
990
+ }