@t2nagi/filebrowser-quantum-mcp 0.0.0-stage → 0.1.0-rc.1

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 (49) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +21 -0
  3. package/README.ja.md +335 -0
  4. package/README.md +328 -2
  5. package/dist/client/api.js +222 -0
  6. package/dist/client/errors.js +120 -0
  7. package/dist/client/http.js +172 -0
  8. package/dist/client/types.js +2 -0
  9. package/dist/config.js +168 -0
  10. package/dist/core/approvals.js +75 -0
  11. package/dist/core/confirm.js +66 -0
  12. package/dist/core/content.js +28 -0
  13. package/dist/core/display.js +65 -0
  14. package/dist/core/inspect.js +180 -0
  15. package/dist/core/lock.js +54 -0
  16. package/dist/core/messages.js +131 -0
  17. package/dist/core/names.js +114 -0
  18. package/dist/core/paths.js +41 -0
  19. package/dist/core/reads.js +39 -0
  20. package/dist/core/recovery.js +55 -0
  21. package/dist/core/replace.js +131 -0
  22. package/dist/core/shares.js +46 -0
  23. package/dist/core/sources.js +18 -0
  24. package/dist/core/state.js +154 -0
  25. package/dist/core/text.js +44 -0
  26. package/dist/core/writeflow.js +497 -0
  27. package/dist/index.js +83 -0
  28. package/dist/log.js +32 -0
  29. package/dist/server.js +117 -0
  30. package/dist/tools/archive.js +159 -0
  31. package/dist/tools/common.js +68 -0
  32. package/dist/tools/create-folder.js +94 -0
  33. package/dist/tools/delete.js +195 -0
  34. package/dist/tools/find-duplicates.js +59 -0
  35. package/dist/tools/get-info.js +53 -0
  36. package/dist/tools/index.js +45 -0
  37. package/dist/tools/list-dir.js +68 -0
  38. package/dist/tools/list-sources.js +45 -0
  39. package/dist/tools/move-copy.js +231 -0
  40. package/dist/tools/read-file.js +69 -0
  41. package/dist/tools/rename.js +99 -0
  42. package/dist/tools/search.js +93 -0
  43. package/dist/tools/shares.js +219 -0
  44. package/dist/tools/unarchive.js +147 -0
  45. package/dist/tools/write-common.js +89 -0
  46. package/dist/tools/write-file.js +160 -0
  47. package/dist/version.js +5 -0
  48. package/npm-shrinkwrap.json +2657 -0
  49. package/package.json +57 -4
@@ -0,0 +1,59 @@
1
+ import { z } from "zod";
2
+ import { normalizePath } from "../core/paths.js";
3
+ import { resolveSource } from "../core/sources.js";
4
+ import { defineTool, pathArg, READ_ONLY_ANNOTATIONS, sourceArg } from "./common.js";
5
+ const inputSchema = z.strictObject({
6
+ source: sourceArg,
7
+ path: pathArg("Folder to scan, starting with /.").default("/"),
8
+ minSizeMb: z.number().int().min(1).default(1).describe("Only files at least this large (MB)."),
9
+ limit: z
10
+ .number()
11
+ .int()
12
+ .min(1)
13
+ .max(500)
14
+ .default(50)
15
+ .describe("Maximum number of groups to return."),
16
+ });
17
+ const outputSchema = z.strictObject({
18
+ source: z.string(),
19
+ groups: z.array(z.strictObject({
20
+ count: z.number().int(),
21
+ size: z.number(),
22
+ files: z.array(z.strictObject({ path: z.string(), size: z.number(), modified: z.string() })),
23
+ })),
24
+ totalGroups: z.number().int(),
25
+ truncated: z.boolean(),
26
+ incomplete: z.boolean().describe("Reported by the server when it stopped early."),
27
+ reason: z.string().nullable(),
28
+ });
29
+ export const registerFindDuplicates = (server, ctx) => defineTool(server, ctx.log, {
30
+ name: "fb_find_duplicates",
31
+ title: "Find duplicate files",
32
+ description: "Find groups of duplicate files under a folder. The server only groups files whose names are at least 50% similar, and returns 503 (unavailable) while indexing. This can take a while.",
33
+ inputSchema,
34
+ outputSchema,
35
+ annotations: READ_ONLY_ANNOTATIONS,
36
+ handler: async (args, extra) => {
37
+ const facts = await ctx.state.ready();
38
+ const source = resolveSource(facts, args.source);
39
+ const path = normalizePath(args.path);
40
+ const res = await ctx.client.findDuplicates(source.name, path, args.minSizeMb, {
41
+ signal: extra.signal,
42
+ });
43
+ const groups = res.groups;
44
+ return {
45
+ structured: {
46
+ source: source.name,
47
+ groups: groups.slice(0, args.limit).map((g) => ({
48
+ count: g.count,
49
+ size: g.size,
50
+ files: g.files.map(({ path, size, modified }) => ({ path, size, modified })),
51
+ })),
52
+ totalGroups: groups.length,
53
+ truncated: groups.length > args.limit,
54
+ incomplete: res.incomplete,
55
+ reason: res.reason,
56
+ },
57
+ };
58
+ },
59
+ });
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+ import { normalizePath } from "../core/paths.js";
3
+ import { previousOperationSchema } from "../core/recovery.js";
4
+ import { resolveSource } from "../core/sources.js";
5
+ import { defineTool, pathArg, READ_ONLY_ANNOTATIONS, sourceArg } from "./common.js";
6
+ const inputSchema = z.strictObject({
7
+ source: sourceArg,
8
+ path: pathArg("File or folder path inside the source, starting with /."),
9
+ });
10
+ const outputSchema = z.strictObject({
11
+ source: z.string(),
12
+ path: z.string(),
13
+ name: z.string(),
14
+ type: z.string().describe('"directory" for folders, otherwise the MIME type.'),
15
+ size: z.number().describe("Size as reported by the server (may be disk usage)."),
16
+ modified: z.string().describe("ISO 8601, UTC, with the server's precision."),
17
+ hidden: z.boolean(),
18
+ childCount: z
19
+ .number()
20
+ .int()
21
+ .optional()
22
+ .describe("Folders only: number of files and folders inside."),
23
+ previousOperation: previousOperationSchema.optional(),
24
+ });
25
+ export const registerGetInfo = (server, ctx) => defineTool(server, ctx.log, {
26
+ name: "fb_get_info",
27
+ title: "Get file or folder info",
28
+ description: "Get the type, size and modification time of a file or folder (for folders, the number of children instead of a listing).",
29
+ inputSchema,
30
+ outputSchema,
31
+ annotations: READ_ONLY_ANNOTATIONS,
32
+ previous: ctx.recovery,
33
+ handler: async (args, extra) => {
34
+ const facts = await ctx.state.ready();
35
+ const source = resolveSource(facts, args.source);
36
+ const path = normalizePath(args.path);
37
+ const res = await ctx.client.getResource(source.name, path, { signal: extra.signal });
38
+ return {
39
+ structured: {
40
+ source: source.name,
41
+ path,
42
+ name: res.name,
43
+ type: res.type,
44
+ size: res.size,
45
+ modified: res.modified,
46
+ hidden: res.hidden === true,
47
+ ...(res.type === "directory"
48
+ ? { childCount: (res.files?.length ?? 0) + (res.folders?.length ?? 0) }
49
+ : {}),
50
+ },
51
+ };
52
+ },
53
+ });
@@ -0,0 +1,45 @@
1
+ // Picks the tools to register for the current settings (design §6.1).
2
+ import { registerArchive } from "./archive.js";
3
+ import { registerCreateFolder } from "./create-folder.js";
4
+ import { registerDelete } from "./delete.js";
5
+ import { registerFindDuplicates } from "./find-duplicates.js";
6
+ import { registerGetInfo } from "./get-info.js";
7
+ import { registerListDir } from "./list-dir.js";
8
+ import { registerListSources } from "./list-sources.js";
9
+ import { registerCopy, registerMove } from "./move-copy.js";
10
+ import { registerReadFile } from "./read-file.js";
11
+ import { registerRename } from "./rename.js";
12
+ import { registerSearch } from "./search.js";
13
+ import { registerCreateShare, registerDeleteShare, registerListShares } from "./shares.js";
14
+ import { registerUnarchive } from "./unarchive.js";
15
+ import { registerWriteFile } from "./write-file.js";
16
+ export function registerTools(server, ctx) {
17
+ const tools = new Map();
18
+ const add = (name, register) => tools.set(name, register(server, ctx));
19
+ add("fb_list_sources", registerListSources);
20
+ add("fb_list_dir", registerListDir);
21
+ add("fb_get_info", registerGetInfo);
22
+ add("fb_read_file", registerReadFile);
23
+ add("fb_search", registerSearch);
24
+ add("fb_find_duplicates", registerFindDuplicates);
25
+ if (!ctx.config.readOnly) {
26
+ add("fb_create_folder", registerCreateFolder);
27
+ add("fb_write_file", registerWriteFile);
28
+ add("fb_move", registerMove);
29
+ add("fb_copy", registerCopy);
30
+ add("fb_rename", registerRename);
31
+ add("fb_archive", registerArchive);
32
+ add("fb_unarchive", registerUnarchive);
33
+ if (ctx.config.allowDelete)
34
+ add("fb_delete", registerDelete);
35
+ if (ctx.config.allowShare) {
36
+ add("fb_create_share", registerCreateShare);
37
+ add("fb_delete_share", registerDeleteShare);
38
+ }
39
+ }
40
+ // Listing shares never changes anything, but it is only useful (and only exposes share
41
+ // metadata to the LLM) when sharing is enabled (design §6.1).
42
+ if (ctx.config.allowShare)
43
+ add("fb_list_shares", registerListShares);
44
+ return tools;
45
+ }
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
2
+ import { ToolError } from "../client/errors.js";
3
+ import { normalizePath } from "../core/paths.js";
4
+ import { previousOperationSchema } from "../core/recovery.js";
5
+ import { resolveSource } from "../core/sources.js";
6
+ import { defineTool, pathArg, READ_ONLY_ANNOTATIONS, sourceArg } from "./common.js";
7
+ const inputSchema = z.strictObject({
8
+ source: sourceArg,
9
+ path: pathArg("Folder path inside the source, starting with /.").default("/"),
10
+ only: z.enum(["files", "folders"]).optional().describe("Return only files or only folders."),
11
+ limit: z.number().int().min(1).max(1000).default(200),
12
+ offset: z.number().int().min(0).default(0),
13
+ });
14
+ const outputSchema = z.strictObject({
15
+ source: z.string(),
16
+ path: z.string(),
17
+ entries: z.array(z.strictObject({
18
+ name: z.string(),
19
+ type: z.string().describe('"directory" for folders, otherwise the MIME type.'),
20
+ size: z
21
+ .number()
22
+ .describe("Size as reported by the server. Can be disk usage (e.g. 4096) unless the source uses logical sizes."),
23
+ modified: z.string().describe("ISO 8601, UTC."),
24
+ })),
25
+ total: z.number().int(),
26
+ nextOffset: z.number().int().nullable(),
27
+ previousOperation: previousOperationSchema.optional(),
28
+ });
29
+ /** Sort by UTF-8 byte order (design §6.3), encoding each name once. */
30
+ function sortByName(entries) {
31
+ return entries
32
+ .map((e) => ({ e, key: Buffer.from(e.name, "utf8") }))
33
+ .sort((a, b) => Buffer.compare(a.key, b.key))
34
+ .map(({ e }) => e);
35
+ }
36
+ export const registerListDir = (server, ctx) => defineTool(server, ctx.log, {
37
+ name: "fb_list_dir",
38
+ title: "List folder",
39
+ description: "List the entries of a folder: folders first, then files, each sorted by name. Hidden files and items excluded by the source's rules are not shown. Use offset/limit to page.",
40
+ inputSchema,
41
+ outputSchema,
42
+ annotations: READ_ONLY_ANNOTATIONS,
43
+ previous: ctx.recovery,
44
+ handler: async (args, extra) => {
45
+ const facts = await ctx.state.ready();
46
+ const source = resolveSource(facts, args.source);
47
+ const path = normalizePath(args.path);
48
+ const res = await ctx.client.getResource(source.name, path, { signal: extra.signal });
49
+ if (res.type !== "directory") {
50
+ throw new ToolError("invalid_argument", "The path is a file, not a folder. Use fb_get_info or fb_read_file.", { source: source.name, path });
51
+ }
52
+ const all = [
53
+ ...(args.only === "files" ? [] : sortByName(res.folders ?? [])),
54
+ ...(args.only === "folders" ? [] : sortByName(res.files ?? [])),
55
+ ];
56
+ const page = all.slice(args.offset, args.offset + args.limit);
57
+ const next = args.offset + page.length;
58
+ return {
59
+ structured: {
60
+ source: source.name,
61
+ path,
62
+ entries: page.map(({ name, type, size, modified }) => ({ name, type, size, modified })),
63
+ total: all.length,
64
+ nextOffset: next < all.length ? next : null,
65
+ },
66
+ };
67
+ },
68
+ });
@@ -0,0 +1,45 @@
1
+ import { z } from "zod";
2
+ import { previousOperationSchema } from "../core/recovery.js";
3
+ import { defineTool, READ_ONLY_ANNOTATIONS } from "./common.js";
4
+ const outputSchema = z.strictObject({
5
+ sources: z.array(z.strictObject({
6
+ name: z.string(),
7
+ scope: z.string().describe("The user's scope inside the source."),
8
+ permissions: z.strictObject({
9
+ view: z.boolean(),
10
+ download: z.boolean(),
11
+ modify: z.boolean(),
12
+ create: z.boolean(),
13
+ delete: z.boolean(),
14
+ }),
15
+ writable: z.boolean().describe("Whether this MCP server allows writes to the source."),
16
+ })),
17
+ userPermissions: z.strictObject({ share: z.boolean() }),
18
+ tokenCanShare: z.boolean(),
19
+ sharedDestinationCheck: z
20
+ .boolean()
21
+ .describe("Whether writes into shared folders can be detected (needs the token's share permission)."),
22
+ defaultSource: z.string().nullable(),
23
+ previousOperation: previousOperationSchema.optional(),
24
+ });
25
+ export const registerListSources = (server, ctx) => defineTool(server, ctx.log, {
26
+ name: "fb_list_sources",
27
+ title: "List sources",
28
+ description: "List the FileBrowser sources this server can use, with the user's permissions on each. Call this first when you do not know the source name.",
29
+ inputSchema: z.strictObject({}),
30
+ outputSchema,
31
+ annotations: READ_ONLY_ANNOTATIONS,
32
+ previous: ctx.recovery,
33
+ handler: async () => {
34
+ const facts = await ctx.state.ready();
35
+ return {
36
+ structured: {
37
+ sources: facts.sources,
38
+ userPermissions: { share: facts.userCanShare },
39
+ tokenCanShare: facts.tokenCanShare,
40
+ sharedDestinationCheck: facts.tokenCanShare,
41
+ defaultSource: facts.defaultSource,
42
+ },
43
+ };
44
+ },
45
+ });
@@ -0,0 +1,231 @@
1
+ // fb_move and fb_copy (design §6.4). One implementation; the differences are which
2
+ // sources must be writable, and how an existing file is replaced.
3
+ import { z } from "zod";
4
+ import { kindFromItemMessage, sanitizeServerMessage, ToolError } from "../client/errors.js";
5
+ import { approvalCodeArg } from "../core/approvals.js";
6
+ import { Inspector } from "../core/inspect.js";
7
+ import { foldName } from "../core/names.js";
8
+ import { normalizePath } from "../core/paths.js";
9
+ import { replaceViaTemp } from "../core/replace.js";
10
+ import { resolveSource } from "../core/sources.js";
11
+ import { assertWritable, onConflictArg, runWriteFlow, } from "../core/writeflow.js";
12
+ import { defineTool, pathArg, sourceArg } from "./common.js";
13
+ import { callInfo, commonFields, commonOutput, conflictsOutput, flowDeps, result, WRITE_ANNOTATIONS, WRITE_NOTE, } from "./write-common.js";
14
+ const inputSchema = z.strictObject({
15
+ approvalCode: approvalCodeArg,
16
+ items: z
17
+ .array(z.strictObject({
18
+ source: sourceArg,
19
+ path: pathArg("Item to move/copy, starting with /."),
20
+ toSource: z
21
+ .string()
22
+ .min(1)
23
+ .max(255)
24
+ .optional()
25
+ .describe("Destination source. Default: same as source."),
26
+ toPath: pathArg("Full destination path including the name, starting with /."),
27
+ }))
28
+ .min(1)
29
+ .max(100),
30
+ onConflict: onConflictArg,
31
+ });
32
+ const opSchema = z.strictObject({
33
+ fromSource: z.string(),
34
+ from: z.string(),
35
+ toSource: z.string(),
36
+ to: z.string(),
37
+ });
38
+ const outputSchema = z.strictObject({
39
+ ...commonOutput,
40
+ ...conflictsOutput,
41
+ succeeded: z.array(opSchema).optional(),
42
+ failed: z.array(opSchema.extend({ kind: z.string(), message: z.string() })).optional(),
43
+ });
44
+ /** Same, inside, or containing (bytes, and NFC + case-insensitive). */
45
+ function related(a, b) {
46
+ const check = (x, y) => x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`);
47
+ return check(a, b) || check(foldName(a), foldName(b));
48
+ }
49
+ function register(action) {
50
+ return (server, ctx) => defineTool(server, ctx.log, {
51
+ name: action === "move" ? "fb_move" : "fb_copy",
52
+ title: action === "move" ? "Move" : "Copy",
53
+ description: action === "move"
54
+ ? `Move files or folders (they disappear from where they were). All items must share one source and one destination source. Overwriting is not possible when moving to another source. ${WRITE_NOTE}`
55
+ : `Copy files or folders (the originals stay). All items must share one source and one destination source. Names inside copied folders are not checked. ${WRITE_NOTE}`,
56
+ inputSchema,
57
+ outputSchema,
58
+ annotations: WRITE_ANNOTATIONS,
59
+ previous: ctx.recovery,
60
+ handler: async (args, extra) => {
61
+ const facts = await ctx.state.ready();
62
+ const items = args.items.map((it) => {
63
+ const fromSource = resolveSource(facts, it.source).name;
64
+ const toSource = it.toSource === undefined ? fromSource : resolveSource(facts, it.toSource).name;
65
+ return {
66
+ fromSource,
67
+ from: normalizePath(it.path),
68
+ toSource,
69
+ to: normalizePath(it.toPath, "toPath"),
70
+ };
71
+ });
72
+ // Step 2: checks within the call (the server overwrites destinations unconditionally).
73
+ const fromSources = new Set(items.map((i) => i.fromSource));
74
+ const toSources = new Set(items.map((i) => i.toSource));
75
+ if (fromSources.size > 1 || toSources.size > 1) {
76
+ throw new ToolError("invalid_argument", "All items in one call must share one source and one destination source.");
77
+ }
78
+ const fromSource = items[0]?.fromSource ?? "";
79
+ const toSource = items[0]?.toSource ?? "";
80
+ const sameSource = fromSource === toSource;
81
+ for (const [i, a] of items.entries()) {
82
+ if (a.from === "/")
83
+ throw new ToolError("invalid_argument", "The root of a source cannot be moved or copied.");
84
+ if (sameSource && related(a.from, a.to)) {
85
+ throw new ToolError("invalid_argument", "An item cannot be moved or copied onto itself, into itself, or onto a folder that contains it.", {
86
+ source: fromSource,
87
+ path: a.from,
88
+ });
89
+ }
90
+ for (const b of items.slice(i + 1)) {
91
+ if (related(a.to, b.to))
92
+ throw new ToolError("invalid_argument", "Two destinations in this call overlap (same, or one inside the other).");
93
+ if (related(a.from, b.from))
94
+ throw new ToolError("invalid_argument", "Two items in this call overlap (same, or one inside the other).");
95
+ if (sameSource && (related(a.to, b.from) || related(b.to, a.from))) {
96
+ throw new ToolError("invalid_argument", "A destination in this call overlaps another item being moved or copied.");
97
+ }
98
+ }
99
+ }
100
+ // Step 3: writable sources (a move also changes its source).
101
+ const [toInfo] = assertWritable(ctx.config, facts, action === "move" ? [toSource, fromSource] : [toSource]);
102
+ // The items must exist; their type decides how a conflict can be resolved.
103
+ const look = new Inspector(ctx.client, facts, { signal: extra.signal });
104
+ const flowItems = [];
105
+ for (const it of items) {
106
+ const p = await look.probe(it.fromSource, it.from);
107
+ if (p.kind !== "present") {
108
+ throw new ToolError(p.kind === "absent" ? "not_found" : "permission_denied", "An item to move or copy does not exist or cannot be accessed.", {
109
+ source: it.fromSource,
110
+ path: it.from,
111
+ });
112
+ }
113
+ flowItems.push({
114
+ ...it,
115
+ fromInfo: { size: p.size, modified: p.modified },
116
+ newType: p.type === "directory" ? "directory" : "file",
117
+ newSize: p.size,
118
+ });
119
+ }
120
+ const perms = toInfo?.permissions;
121
+ const outcome = await runWriteFlow(flowDeps(ctx, facts), {
122
+ approval: { code: args.approvalCode, args },
123
+ tool: action === "move" ? "fb_move" : "fb_copy",
124
+ verb: action,
125
+ items: flowItems,
126
+ onConflict: args.onConflict,
127
+ crossSource: !sameSource,
128
+ renameStyle: (p) => (p.item.newType === "directory" ? "folder" : "file"),
129
+ tempMayRemain: action === "copy" && perms?.delete !== true,
130
+ blockOverwrite: () => action === "move" ? !sameSource : perms?.create !== true || perms?.modify !== true,
131
+ execute: async (finals, run) => {
132
+ const succeeded = [];
133
+ const failed = [];
134
+ const op = (f) => ({
135
+ fromSource,
136
+ from: f.item.from ?? "",
137
+ toSource,
138
+ to: f.finalTo,
139
+ });
140
+ // Parents first (copy / move do not create them), top-down, once each.
141
+ const folders = [...new Set(finals.flatMap((f) => f.missing))].sort((a, b) => a.length - b.length);
142
+ await run.createParents(toSource, folders);
143
+ const direct = finals.filter((f) => !(action === "copy" && f.resolution === "overwrite"));
144
+ if (direct.length > 0) {
145
+ const body = direct.map((f) => ({
146
+ fromSource,
147
+ fromPath: f.item.from ?? "",
148
+ toSource,
149
+ toPath: f.finalTo,
150
+ }));
151
+ const res = await run.send(direct.map(op), [], (signal) => ctx.client.moveCopy(action, body, { signal }));
152
+ const failedKeys = new Set(res.failed.map((x) => `${x.fromPath}\n${x.toPath}`));
153
+ for (const f of direct) {
154
+ const bad = res.failed.find((x) => x.fromPath === f.item.from && x.toPath === f.finalTo);
155
+ if (failedKeys.has(`${f.item.from}\n${f.finalTo}`) && bad) {
156
+ const message = sanitizeServerMessage(bad.message ?? "");
157
+ failed.push({
158
+ ...op(f),
159
+ kind: kindFromItemMessage(bad.message ?? ""),
160
+ message,
161
+ });
162
+ if (action === "move" && !sameSource) {
163
+ // A failed move to another source can leave a partial copy (verified).
164
+ const left = await new Inspector(ctx.client, facts, {}).probe(toSource, f.finalTo);
165
+ if (left.kind !== "absent") {
166
+ run.leftovers.push({
167
+ source: toSource,
168
+ path: f.finalTo,
169
+ kind: "partial_copy",
170
+ originalStillExists: true,
171
+ });
172
+ }
173
+ }
174
+ }
175
+ else {
176
+ succeeded.push(op(f));
177
+ }
178
+ }
179
+ }
180
+ for (const f of finals.filter((x) => action === "copy" && x.resolution === "overwrite")) {
181
+ try {
182
+ await replaceViaTemp({
183
+ client: ctx.client,
184
+ facts,
185
+ run,
186
+ source: toSource,
187
+ target: f.finalTo,
188
+ approved: f.existing,
189
+ from: { source: fromSource, path: f.item.from ?? "" },
190
+ create: async (temp) => {
191
+ const res = await ctx.client.moveCopy("copy", [
192
+ { fromSource, fromPath: f.item.from ?? "", toSource, toPath: temp },
193
+ ]);
194
+ const bad = res.failed[0];
195
+ if (bad)
196
+ throw new ToolError(kindFromItemMessage(bad.message ?? ""), sanitizeServerMessage(bad.message ?? "copy failed"));
197
+ },
198
+ });
199
+ succeeded.push(op(f));
200
+ }
201
+ catch (err) {
202
+ if (err instanceof ToolError && err.kind === "timeout")
203
+ throw err;
204
+ const e = err instanceof ToolError ? err : new ToolError("server_error", String(err));
205
+ failed.push({ ...op(f), kind: e.kind, message: e.message });
206
+ }
207
+ }
208
+ return { succeeded, failed };
209
+ },
210
+ }, callInfo(extra));
211
+ const common = commonFields(outcome);
212
+ if (outcome.status === "cancelled")
213
+ return result(common, outcome);
214
+ const { succeeded, failed } = outcome.result;
215
+ if (succeeded.length === 0 && failed.length > 0) {
216
+ const kinds = new Set(failed.map((f) => f.kind));
217
+ const kind = kinds.size === 1 ? failed[0]?.kind : "server_error";
218
+ throw new ToolError(kind, `Every item failed to ${action}.`, {
219
+ details: {
220
+ failed,
221
+ ...(outcome.createdFolders.length ? { createdFolders: outcome.createdFolders } : {}),
222
+ ...(outcome.leftovers.length ? { leftovers: outcome.leftovers } : {}),
223
+ },
224
+ });
225
+ }
226
+ return result({ ...common, status: failed.length > 0 ? "partial" : "completed", succeeded, failed }, outcome);
227
+ },
228
+ });
229
+ }
230
+ export const registerMove = register("move");
231
+ export const registerCopy = register("copy");
@@ -0,0 +1,69 @@
1
+ import { z } from "zod";
2
+ import { readTextFile } from "../core/content.js";
3
+ import { normalizePath } from "../core/paths.js";
4
+ import { resolveSource } from "../core/sources.js";
5
+ import { sliceUtf8 } from "../core/text.js";
6
+ import { defineTool, pathArg, READ_ONLY_ANNOTATIONS, sourceArg } from "./common.js";
7
+ const inputSchema = z.strictObject({
8
+ source: sourceArg,
9
+ path: pathArg("File path inside the source, starting with /."),
10
+ offset: z.number().int().min(0).default(0).describe("Start position in UTF-8 bytes."),
11
+ maxBytes: z
12
+ .number()
13
+ .int()
14
+ .min(1)
15
+ .optional()
16
+ .describe("Maximum bytes to return. Values above the server's limit are reduced to it."),
17
+ });
18
+ const outputSchema = z.strictObject({
19
+ source: z.string(),
20
+ path: z.string(),
21
+ type: z.string(),
22
+ size: z.number(),
23
+ modified: z
24
+ .string()
25
+ .describe("Modification time with the server's precision. Pass it to fb_write_file as expectedModified."),
26
+ content: z.string(),
27
+ offset: z.number().int(),
28
+ returnedBytes: z.number().int(),
29
+ nextOffset: z
30
+ .number()
31
+ .int()
32
+ .nullable()
33
+ .describe("Offset for the next call, or null at the end of the file."),
34
+ });
35
+ export const registerReadFile = (server, ctx) => defineTool(server, ctx.log, {
36
+ name: "fb_read_file",
37
+ title: "Read text file",
38
+ description: `Read a UTF-8 text file (up to ${ctx.config.maxReadBytes} bytes per call; continue with nextOffset). Binary files and other encodings are not supported. The first content block is metadata, the second the text itself.`,
39
+ inputSchema,
40
+ outputSchema,
41
+ annotations: READ_ONLY_ANNOTATIONS,
42
+ handler: async (args, extra) => {
43
+ const facts = await ctx.state.ready();
44
+ const source = resolveSource(facts, args.source);
45
+ const path = normalizePath(args.path);
46
+ const file = await readTextFile(ctx.client, source.name, path, { signal: extra.signal });
47
+ const maxBytes = Math.min(args.maxBytes ?? ctx.config.maxReadBytes, ctx.config.maxReadBytes);
48
+ const slice = sliceUtf8(Buffer.from(file.text, "utf8"), args.offset, maxBytes);
49
+ ctx.reads.record(source.name, path, file.modified, slice.start, slice.start + slice.bytes, slice.nextOffset === null);
50
+ const meta = {
51
+ source: source.name,
52
+ path,
53
+ type: file.type,
54
+ size: file.size,
55
+ modified: file.modified,
56
+ offset: slice.start,
57
+ returnedBytes: slice.bytes,
58
+ nextOffset: slice.nextOffset,
59
+ };
60
+ return {
61
+ structured: { ...meta, content: slice.text },
62
+ // Metadata first so that it survives truncation and cannot be faked by the file's tail (§5.3).
63
+ content: [
64
+ { type: "text", text: JSON.stringify(meta) },
65
+ { type: "text", text: slice.text },
66
+ ],
67
+ };
68
+ },
69
+ });