@t2nagi/filebrowser-quantum-mcp 0.0.0-stage → 0.1.0-rc.2
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.
- package/LICENSE +202 -0
- package/NOTICE +21 -0
- package/README.ja.md +335 -0
- package/README.md +328 -2
- package/dist/client/api.js +222 -0
- package/dist/client/errors.js +120 -0
- package/dist/client/http.js +172 -0
- package/dist/client/types.js +2 -0
- package/dist/config.js +168 -0
- package/dist/core/approvals.js +75 -0
- package/dist/core/confirm.js +66 -0
- package/dist/core/content.js +28 -0
- package/dist/core/display.js +65 -0
- package/dist/core/inspect.js +180 -0
- package/dist/core/lock.js +54 -0
- package/dist/core/messages.js +131 -0
- package/dist/core/names.js +114 -0
- package/dist/core/paths.js +41 -0
- package/dist/core/reads.js +39 -0
- package/dist/core/recovery.js +55 -0
- package/dist/core/replace.js +131 -0
- package/dist/core/shares.js +46 -0
- package/dist/core/sources.js +18 -0
- package/dist/core/state.js +154 -0
- package/dist/core/text.js +44 -0
- package/dist/core/writeflow.js +497 -0
- package/dist/index.js +83 -0
- package/dist/log.js +32 -0
- package/dist/server.js +117 -0
- package/dist/tools/archive.js +159 -0
- package/dist/tools/common.js +68 -0
- package/dist/tools/create-folder.js +94 -0
- package/dist/tools/delete.js +195 -0
- package/dist/tools/find-duplicates.js +59 -0
- package/dist/tools/get-info.js +53 -0
- package/dist/tools/index.js +45 -0
- package/dist/tools/list-dir.js +68 -0
- package/dist/tools/list-sources.js +45 -0
- package/dist/tools/move-copy.js +231 -0
- package/dist/tools/read-file.js +69 -0
- package/dist/tools/rename.js +99 -0
- package/dist/tools/search.js +93 -0
- package/dist/tools/shares.js +219 -0
- package/dist/tools/unarchive.js +147 -0
- package/dist/tools/write-common.js +89 -0
- package/dist/tools/write-file.js +160 -0
- package/dist/version.js +5 -0
- package/npm-shrinkwrap.json +1235 -0
- package/package.json +57 -4
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// The common flow of every write tool (design §6.2.2):
|
|
2
|
+
// inspect -> decide (maybe ask the user) -> lock -> recheck -> pick names -> execute.
|
|
3
|
+
// Steps before the lock never write.
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { ToolError } from "../client/errors.js";
|
|
6
|
+
import { certainlyNotSent } from "../client/http.js";
|
|
7
|
+
import { requireApproval } from "./approvals.js";
|
|
8
|
+
import { askUser } from "./confirm.js";
|
|
9
|
+
import { displayPath, displaySource, formatSize, formatTime } from "./display.js";
|
|
10
|
+
import { baseName, Inspector, parentOf, sameProbe } from "./inspect.js";
|
|
11
|
+
import { cancelMessage, texts, verbLabel, } from "./messages.js";
|
|
12
|
+
import { alternativeNames, foldName } from "./names.js";
|
|
13
|
+
import { joinPath } from "./paths.js";
|
|
14
|
+
// ---- Shared output pieces (design §6.2.11) -------------------------------
|
|
15
|
+
export const leftoverSchema = z.strictObject({
|
|
16
|
+
source: z.string(),
|
|
17
|
+
path: z.string(),
|
|
18
|
+
kind: z.enum([
|
|
19
|
+
"temp_with_new_content",
|
|
20
|
+
"unreachable_temp",
|
|
21
|
+
"partial_copy",
|
|
22
|
+
"unknown",
|
|
23
|
+
"created_folder",
|
|
24
|
+
]),
|
|
25
|
+
originalStillExists: z.boolean(),
|
|
26
|
+
intendedPath: z.string().optional(),
|
|
27
|
+
});
|
|
28
|
+
export const conflictOutSchema = z.strictObject({
|
|
29
|
+
from: z.string().optional(),
|
|
30
|
+
to: z.string(),
|
|
31
|
+
resolution: z.enum(["overwritten", "renamed", "cancelled"]),
|
|
32
|
+
renamedTo: z.string().optional(),
|
|
33
|
+
});
|
|
34
|
+
export const statusSchema = z.enum(["completed", "partial", "cancelled"]);
|
|
35
|
+
export const cancelReasonSchema = z.enum([
|
|
36
|
+
"declined",
|
|
37
|
+
"dismissed",
|
|
38
|
+
"unconfirmed",
|
|
39
|
+
"timeout",
|
|
40
|
+
"invalid_response",
|
|
41
|
+
"client_error",
|
|
42
|
+
]);
|
|
43
|
+
export const decidedBySchema = z.enum(["user", "argument", "policy"]).nullable();
|
|
44
|
+
export const onConflictArg = z
|
|
45
|
+
.enum(["ask", "overwrite", "rename"])
|
|
46
|
+
.default("ask")
|
|
47
|
+
.describe('What to do if the destination exists. "ask" (default): the user decides. "rename": save as name(1).ext without asking. "overwrite": still needs the user\'s confirmation.');
|
|
48
|
+
async function withProgress(call, message, fn) {
|
|
49
|
+
const stop = call.progress?.(message);
|
|
50
|
+
try {
|
|
51
|
+
return await fn();
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
stop?.();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const MAX_CONFIRM_ITEMS = 20;
|
|
58
|
+
// ---- Helpers ----------------------------------------------------------------
|
|
59
|
+
export function assertWritable(config, facts, sources) {
|
|
60
|
+
return [...new Set(sources)].map((name) => {
|
|
61
|
+
const info = facts.sources.find((s) => s.name === name);
|
|
62
|
+
if (!info) {
|
|
63
|
+
throw new ToolError("source_not_found", "The source does not exist or is not available. Use fb_list_sources to see the available sources.", { source: name });
|
|
64
|
+
}
|
|
65
|
+
if (config.readOnly || !info.writable) {
|
|
66
|
+
throw new ToolError("read_only", "This MCP server is not allowed to write to the source (FILEBROWSER_READ_ONLY / FILEBROWSER_WRITABLE_SOURCES).", { source: name });
|
|
67
|
+
}
|
|
68
|
+
return info;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
function overwritable(spec, p) {
|
|
72
|
+
if (spec.neverOverwrite)
|
|
73
|
+
return false;
|
|
74
|
+
if (p.existing.kind !== "present")
|
|
75
|
+
return false;
|
|
76
|
+
if (p.existing.type === "directory" || p.item.newType !== "file")
|
|
77
|
+
return false;
|
|
78
|
+
return !spec.blockOverwrite?.(p);
|
|
79
|
+
}
|
|
80
|
+
function existingInfo(p) {
|
|
81
|
+
return p.existing.kind === "present"
|
|
82
|
+
? { type: p.existing.type, size: p.existing.size, modified: p.existing.modified }
|
|
83
|
+
: null;
|
|
84
|
+
}
|
|
85
|
+
async function prepareAll(spec, inspector) {
|
|
86
|
+
const out = [];
|
|
87
|
+
for (const item of spec.items) {
|
|
88
|
+
const resolved = await inspector.resolve(item.toSource, item.to);
|
|
89
|
+
const existing = await inspector.probe(item.toSource, resolved.path);
|
|
90
|
+
const shared = await inspector.isShared(item.toSource, resolved.path);
|
|
91
|
+
out.push({ item, dest: resolved.path, missing: resolved.missing, existing, shared });
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
function sameState(a, b) {
|
|
96
|
+
return a.every((x, i) => {
|
|
97
|
+
const y = b[i];
|
|
98
|
+
return (y !== undefined &&
|
|
99
|
+
x.dest === y.dest &&
|
|
100
|
+
x.shared === y.shared &&
|
|
101
|
+
x.missing.join("\n") === y.missing.join("\n") &&
|
|
102
|
+
sameProbe(x.existing, y.existing));
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/** First free alternative name, checked by listing, reservations and a direct GET. */
|
|
106
|
+
async function freeName(deps, inspector, p, style, taken, probe) {
|
|
107
|
+
const parent = parentOf(p.dest);
|
|
108
|
+
const names = new Set(((await inspector.list(p.item.toSource, parent)) ?? []).map(foldName));
|
|
109
|
+
for (const candidate of alternativeNames(baseName(p.dest), style)) {
|
|
110
|
+
const path = joinPath(parent, candidate);
|
|
111
|
+
const key = foldName(path);
|
|
112
|
+
if (names.has(foldName(candidate)) || taken.has(key))
|
|
113
|
+
continue;
|
|
114
|
+
if (deps.lock.isReserved(p.item.toSource, path))
|
|
115
|
+
continue;
|
|
116
|
+
if (probe && (await inspector.probe(p.item.toSource, path)).kind !== "absent")
|
|
117
|
+
continue;
|
|
118
|
+
return path;
|
|
119
|
+
}
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
function conflictError(deps, spec, conflicts, suggestions, reason) {
|
|
123
|
+
const all = conflicts.every((p) => overwritable(spec, p));
|
|
124
|
+
const allowed = reason !== "exists"
|
|
125
|
+
? []
|
|
126
|
+
: deps.config.confirmPolicy === "trust-client" && all
|
|
127
|
+
? ["overwrite", "rename"]
|
|
128
|
+
: ["rename"];
|
|
129
|
+
const messages = {
|
|
130
|
+
exists: 'The destination already exists. Ask the user whether to save under a new name (onConflict: "rename") or to stop.' +
|
|
131
|
+
(allowed.includes("overwrite")
|
|
132
|
+
? ""
|
|
133
|
+
: ' Overwriting is not possible with this client and settings: it needs a client that supports elicitation, or the user changing FILEBROWSER_CONFIRM_POLICY. Do not retry with onConflict "overwrite".'),
|
|
134
|
+
changed_before_send: "The destination changed while the operation was being confirmed, so nothing was done. Check the current state and ask the user again.",
|
|
135
|
+
no_free_name: "No free alternative name was found (tried name(1) to name(1000)). Nothing was done.",
|
|
136
|
+
};
|
|
137
|
+
return new ToolError("conflict", messages[reason], {
|
|
138
|
+
details: {
|
|
139
|
+
reason,
|
|
140
|
+
conflicts: conflicts.map((p) => {
|
|
141
|
+
const entry = {
|
|
142
|
+
toSource: p.item.toSource,
|
|
143
|
+
to: p.dest,
|
|
144
|
+
existing: existingInfo(p),
|
|
145
|
+
overwritable: overwritable(spec, p),
|
|
146
|
+
};
|
|
147
|
+
if (p.item.from !== undefined) {
|
|
148
|
+
entry.fromSource = p.item.fromSource;
|
|
149
|
+
entry.from = p.item.from;
|
|
150
|
+
}
|
|
151
|
+
const suggested = suggestions.get(p);
|
|
152
|
+
if (suggested !== undefined)
|
|
153
|
+
entry.suggestedName = baseName(suggested);
|
|
154
|
+
return entry;
|
|
155
|
+
}),
|
|
156
|
+
allowedResolutions: allowed,
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
function buildQuestion(lang, spec, prepared, conflicts, askChoice, offerOverwrite, external, example) {
|
|
161
|
+
const t = texts(lang);
|
|
162
|
+
const lines = [];
|
|
163
|
+
const shown = askChoice ? conflicts : prepared;
|
|
164
|
+
const folders = shown.filter((p) => p.existing.kind === "present" && p.existing.type === "directory").length;
|
|
165
|
+
lines.push(`[${verbLabel(lang, spec.verb)}] ${askChoice ? t.conflictHead(shown.length, shown.length - folders, folders) : t.externalHead}`);
|
|
166
|
+
const first = prepared[0]?.item;
|
|
167
|
+
lines.push(t.sources(first?.fromSource === undefined ? undefined : displaySource(first.fromSource), displaySource(first?.toSource ?? "")));
|
|
168
|
+
lines.push("----");
|
|
169
|
+
shown.forEach((p, i) => {
|
|
170
|
+
const n = `${i + 1}. `;
|
|
171
|
+
const pad = " ".repeat(n.length);
|
|
172
|
+
if (p.item.from !== undefined && p.item.fromSource !== undefined) {
|
|
173
|
+
const info = p.item.fromInfo
|
|
174
|
+
? `(${formatSize(p.item.fromInfo.size)}, ${formatTime(p.item.fromInfo.modified)})`
|
|
175
|
+
: "";
|
|
176
|
+
lines.push(`${n}${t.from}: ${displayPath(p.item.fromSource, p.item.from)}${info}`);
|
|
177
|
+
lines.push(`${pad}${t.to}: ${displayPath(p.item.toSource, p.dest)}${existingSuffix(lang, p)}`);
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
lines.push(`${n}${displayPath(p.item.toSource, p.dest)}${existingSuffix(lang, p)}`);
|
|
181
|
+
if (askChoice && p.item.newSize !== undefined) {
|
|
182
|
+
lines.push(`${pad}${texts(lang).newContent(formatSize(p.item.newSize))}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (askChoice &&
|
|
186
|
+
p.existing.kind === "present" &&
|
|
187
|
+
p.item.newSize !== undefined &&
|
|
188
|
+
p.item.newSize < p.existing.size / 2) {
|
|
189
|
+
lines.push(`${pad}${t.shrink}`);
|
|
190
|
+
}
|
|
191
|
+
for (const w of [...(p.item.warnings ?? []), ...(spec.itemWarnings?.(p) ?? [])]) {
|
|
192
|
+
lines.push(`${pad}${w}`);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
lines.push("----");
|
|
196
|
+
if (external) {
|
|
197
|
+
if (spec.crossSource)
|
|
198
|
+
lines.push(t.crossSource);
|
|
199
|
+
if (prepared.some((p) => p.shared))
|
|
200
|
+
lines.push(t.shared);
|
|
201
|
+
}
|
|
202
|
+
if (askChoice) {
|
|
203
|
+
lines.push(t.choices(offerOverwrite, example));
|
|
204
|
+
if (!offerOverwrite)
|
|
205
|
+
lines.push(t.noOverwrite);
|
|
206
|
+
if (offerOverwrite && spec.tempMayRemain)
|
|
207
|
+
lines.push(t.tempMayRemain);
|
|
208
|
+
}
|
|
209
|
+
const question = { message: lines.join("\n") };
|
|
210
|
+
if (askChoice) {
|
|
211
|
+
question.choices = offerOverwrite ? ["cancel", "rename", "overwrite"] : ["cancel", "rename"];
|
|
212
|
+
question.choiceDescription = t.choiceDescription(offerOverwrite);
|
|
213
|
+
}
|
|
214
|
+
if (external)
|
|
215
|
+
question.confirmDescription = t.confirmDescription(t.approveExternal);
|
|
216
|
+
return question;
|
|
217
|
+
}
|
|
218
|
+
function existingSuffix(lang, p) {
|
|
219
|
+
const t = texts(lang);
|
|
220
|
+
if (p.existing.kind === "present") {
|
|
221
|
+
return `(${t.existing} ${formatSize(p.existing.size)}, ${formatTime(p.existing.modified)})`;
|
|
222
|
+
}
|
|
223
|
+
if (p.existing.kind === "unknown")
|
|
224
|
+
return `(${t.unknownExisting})`;
|
|
225
|
+
return `(${t.newItem})`;
|
|
226
|
+
}
|
|
227
|
+
// ---- The flow -----------------------------------------------------------------
|
|
228
|
+
export async function runWriteFlow(deps, spec, call) {
|
|
229
|
+
const { config, elicitor } = deps;
|
|
230
|
+
const canAsk = elicitor.supported();
|
|
231
|
+
let confirmations = 0;
|
|
232
|
+
let decidedBy = null;
|
|
233
|
+
for (;;) {
|
|
234
|
+
// Steps 4-5: inspect and decide. Nothing is written.
|
|
235
|
+
const inspector = new Inspector(deps.client, deps.facts, { signal: call.signal });
|
|
236
|
+
const prepared = await prepareAll(spec, inspector);
|
|
237
|
+
spec.precheck?.(prepared);
|
|
238
|
+
const conflicts = prepared.filter((p) => p.existing.kind !== "absent" && (spec.classify?.(p) ?? "conflict") === "conflict");
|
|
239
|
+
const external = spec.crossSource || prepared.some((p) => p.shared);
|
|
240
|
+
const lossy = conflicts.length > 0 && spec.onConflict !== "rename";
|
|
241
|
+
const needsConfirm = lossy || external;
|
|
242
|
+
const offerOverwrite = conflicts.length > 0 && conflicts.every((p) => overwritable(spec, p));
|
|
243
|
+
if (needsConfirm && spec.items.length > MAX_CONFIRM_ITEMS) {
|
|
244
|
+
const reasons = [];
|
|
245
|
+
if (lossy)
|
|
246
|
+
reasons.push("overwrite");
|
|
247
|
+
if (spec.crossSource)
|
|
248
|
+
reasons.push("cross_source");
|
|
249
|
+
if (prepared.some((p) => p.shared))
|
|
250
|
+
reasons.push("shared_destination");
|
|
251
|
+
throw new ToolError("too_many_items", `Operations that need the user's confirmation are limited to ${MAX_CONFIRM_ITEMS} items. Split the call. With onConflict "rename" and no conflicts or external writes, up to 100 items are allowed.`, { details: { max: MAX_CONFIRM_ITEMS, count: spec.items.length, reasons } });
|
|
252
|
+
}
|
|
253
|
+
const suggestions = new Map();
|
|
254
|
+
for (const p of conflicts) {
|
|
255
|
+
suggestions.set(p, await freeName(deps, inspector, p, spec.renameStyle(p), new Set(), false));
|
|
256
|
+
}
|
|
257
|
+
let resolution;
|
|
258
|
+
if (!needsConfirm) {
|
|
259
|
+
resolution = conflicts.length > 0 ? "rename" : undefined;
|
|
260
|
+
decidedBy = conflicts.length > 0 ? "argument" : decidedBy;
|
|
261
|
+
}
|
|
262
|
+
else if (canAsk) {
|
|
263
|
+
if (confirmations >= 2)
|
|
264
|
+
throw conflictError(deps, spec, conflicts, suggestions, "changed_before_send");
|
|
265
|
+
confirmations++;
|
|
266
|
+
const firstSuggestion = conflicts.map((p) => suggestions.get(p)).find((s) => s !== undefined);
|
|
267
|
+
const question = buildQuestion(config.lang, spec, prepared, conflicts, lossy, offerOverwrite, external, firstSuggestion ? baseName(firstSuggestion) : "name(1).ext");
|
|
268
|
+
const answer = await withProgress(call, "Waiting for the user's confirmation", () => askUser(elicitor, question, {
|
|
269
|
+
timeout: config.confirmTimeoutMs,
|
|
270
|
+
signal: call.signal,
|
|
271
|
+
relatedRequestId: call.requestId,
|
|
272
|
+
}));
|
|
273
|
+
if (!answer.ok) {
|
|
274
|
+
if (answer.aborted)
|
|
275
|
+
throw new ToolError("cancelled", "The tool call was cancelled.");
|
|
276
|
+
return {
|
|
277
|
+
status: "cancelled",
|
|
278
|
+
cancelReason: answer.reason,
|
|
279
|
+
message: cancelMessage(answer.reason),
|
|
280
|
+
conflicts: conflicts.map((p) => cancelledConflict(p)),
|
|
281
|
+
decidedBy: "user",
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
resolution = lossy ? answer.choice : conflicts.length > 0 ? "rename" : undefined;
|
|
285
|
+
decidedBy = "user";
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
// No elicitation (design §6.2.6, §6.2.7, §6.2.8).
|
|
289
|
+
const reasons = [];
|
|
290
|
+
const strict = config.confirmPolicy === "strict";
|
|
291
|
+
if (external && strict) {
|
|
292
|
+
if (spec.crossSource)
|
|
293
|
+
reasons.push("cross_source");
|
|
294
|
+
if (prepared.some((p) => p.shared))
|
|
295
|
+
reasons.push("shared_destination");
|
|
296
|
+
}
|
|
297
|
+
if (conflicts.length > 0) {
|
|
298
|
+
if (spec.onConflict === "ask") {
|
|
299
|
+
if (reasons.length === 0)
|
|
300
|
+
throw conflictError(deps, spec, conflicts, suggestions, "exists");
|
|
301
|
+
}
|
|
302
|
+
else if (spec.onConflict === "overwrite") {
|
|
303
|
+
if (strict)
|
|
304
|
+
reasons.push("overwrite");
|
|
305
|
+
else if (!offerOverwrite)
|
|
306
|
+
throw conflictError(deps, spec, conflicts, suggestions, "exists");
|
|
307
|
+
else
|
|
308
|
+
resolution = "overwrite";
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (reasons.length > 0) {
|
|
312
|
+
throw new ToolError("confirmation_required", "This needs the user's confirmation, but the client does not support it (elicitation), and FILEBROWSER_CONFIRM_POLICY is strict. Nothing was done. Tell the user; do not retry the same call." +
|
|
313
|
+
(reasons.includes("overwrite")
|
|
314
|
+
? ' Saving under a new name (onConflict: "rename") is possible.'
|
|
315
|
+
: ""), {
|
|
316
|
+
details: {
|
|
317
|
+
reason: reasons,
|
|
318
|
+
alternatives: reasons.includes("overwrite") ? ["rename"] : [],
|
|
319
|
+
},
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
if (conflicts.length > 0 && resolution === undefined)
|
|
323
|
+
resolution = "rename";
|
|
324
|
+
decidedBy = external ? "policy" : conflicts.length > 0 ? "argument" : null;
|
|
325
|
+
if (!strict && (resolution === "overwrite" || external)) {
|
|
326
|
+
// trust-client without a prompt: two steps, bound to this state (design §6.2.7).
|
|
327
|
+
decidedBy = "policy";
|
|
328
|
+
const overwritten = new Set(resolution === "overwrite" ? conflicts : []);
|
|
329
|
+
const plan = prepared
|
|
330
|
+
.filter((p) => external || overwritten.has(p))
|
|
331
|
+
.map((p) => ({
|
|
332
|
+
action: overwritten.has(p) ? "overwrite" : "write",
|
|
333
|
+
...(p.item.from !== undefined
|
|
334
|
+
? { fromSource: p.item.fromSource ?? p.item.toSource, from: p.item.from }
|
|
335
|
+
: {}),
|
|
336
|
+
toSource: p.item.toSource,
|
|
337
|
+
to: p.dest,
|
|
338
|
+
existing: existingInfo(p),
|
|
339
|
+
...(spec.crossSource ? { crossSource: true } : {}),
|
|
340
|
+
...(p.shared ? { sharedDestination: true } : {}),
|
|
341
|
+
}));
|
|
342
|
+
const state = prepared.map((p) => [p.item.toSource, p.dest, p.shared, existingInfo(p)]);
|
|
343
|
+
requireApproval(deps.approvals, spec.tool, spec.approval, state, plan);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// Step 6: recheck and execute inside the lock.
|
|
347
|
+
const releases = [];
|
|
348
|
+
try {
|
|
349
|
+
const outcome = await deps.lock.run(call.signal, async () => {
|
|
350
|
+
const fresh = new Inspector(deps.client, deps.facts, {});
|
|
351
|
+
const recheck = await prepareAll(spec, fresh);
|
|
352
|
+
if (!sameState(prepared, recheck))
|
|
353
|
+
return "changed";
|
|
354
|
+
const finals = [];
|
|
355
|
+
const taken = new Set();
|
|
356
|
+
for (const p of recheck) {
|
|
357
|
+
const isConflict = p.existing.kind !== "absent" && (spec.classify?.(p) ?? "conflict") === "conflict";
|
|
358
|
+
if (!isConflict) {
|
|
359
|
+
finals.push({
|
|
360
|
+
...p,
|
|
361
|
+
finalTo: p.dest,
|
|
362
|
+
resolution: p.existing.kind === "absent" ? "new" : "existing_ok",
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
else if (resolution === "overwrite") {
|
|
366
|
+
finals.push({ ...p, finalTo: p.dest, resolution: "overwrite" });
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
const name = await freeName(deps, fresh, p, spec.renameStyle(p), taken, true);
|
|
370
|
+
if (name === undefined)
|
|
371
|
+
throw conflictError(deps, spec, [p], suggestions, "no_free_name");
|
|
372
|
+
taken.add(foldName(name));
|
|
373
|
+
releases.push(deps.lock.reserve(p.item.toSource, name));
|
|
374
|
+
finals.push({ ...p, finalTo: name, resolution: "rename" });
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
const run = makeRunCtx(deps, spec.tool, call);
|
|
378
|
+
try {
|
|
379
|
+
const result = await withProgress(call, "Working on FileBrowser", () => spec.execute(finals, run));
|
|
380
|
+
return { finals, result, run };
|
|
381
|
+
}
|
|
382
|
+
catch (err) {
|
|
383
|
+
throw withWriteDetails(err, run);
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
if (outcome === "changed") {
|
|
387
|
+
if (canAsk && decidedBy === "user")
|
|
388
|
+
continue; // ask once more (max 2)
|
|
389
|
+
throw conflictError(deps, spec, conflicts, suggestions, "changed_before_send");
|
|
390
|
+
}
|
|
391
|
+
return {
|
|
392
|
+
status: "completed",
|
|
393
|
+
result: outcome.result,
|
|
394
|
+
conflicts: outcome.finals
|
|
395
|
+
.filter((f) => f.resolution === "overwrite" || f.resolution === "rename")
|
|
396
|
+
.map((f) => {
|
|
397
|
+
const c = {
|
|
398
|
+
to: f.dest,
|
|
399
|
+
resolution: f.resolution === "overwrite" ? "overwritten" : "renamed",
|
|
400
|
+
};
|
|
401
|
+
if (f.item.from !== undefined)
|
|
402
|
+
c.from = f.item.from;
|
|
403
|
+
if (f.resolution === "rename")
|
|
404
|
+
c.renamedTo = f.finalTo;
|
|
405
|
+
return c;
|
|
406
|
+
}),
|
|
407
|
+
decidedBy,
|
|
408
|
+
createdFolders: outcome.run.createdFolders,
|
|
409
|
+
leftovers: outcome.run.leftovers,
|
|
410
|
+
finals: outcome.finals,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
finally {
|
|
414
|
+
for (const release of releases)
|
|
415
|
+
release();
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
function cancelledConflict(p) {
|
|
420
|
+
const c = { to: p.dest, resolution: "cancelled" };
|
|
421
|
+
if (p.item.from !== undefined)
|
|
422
|
+
c.from = p.item.from;
|
|
423
|
+
return c;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Add what was already created or left behind to a write error (design §5.6: write
|
|
427
|
+
* errors may carry leftovers and createdFolders), so the LLM can tell the user.
|
|
428
|
+
*/
|
|
429
|
+
export function withWriteDetails(err, run) {
|
|
430
|
+
if (!(err instanceof ToolError))
|
|
431
|
+
return err;
|
|
432
|
+
if (run.leftovers.length === 0 && run.createdFolders.length === 0)
|
|
433
|
+
return err;
|
|
434
|
+
const details = { ...(err.details ?? {}) };
|
|
435
|
+
if (run.leftovers.length > 0)
|
|
436
|
+
details.leftovers = run.leftovers;
|
|
437
|
+
if (run.createdFolders.length > 0)
|
|
438
|
+
details.createdFolders = run.createdFolders;
|
|
439
|
+
const init = { details };
|
|
440
|
+
if (err.status !== undefined)
|
|
441
|
+
init.status = err.status;
|
|
442
|
+
if (err.source !== undefined)
|
|
443
|
+
init.source = err.source;
|
|
444
|
+
if (err.path !== undefined)
|
|
445
|
+
init.path = err.path;
|
|
446
|
+
return new ToolError(err.kind, err.message, init);
|
|
447
|
+
}
|
|
448
|
+
export function makeRunCtx(deps, tool, call) {
|
|
449
|
+
const run = {
|
|
450
|
+
createdFolders: [],
|
|
451
|
+
leftovers: [],
|
|
452
|
+
signal: call.signal,
|
|
453
|
+
async createParents(source, folders) {
|
|
454
|
+
for (const folder of folders) {
|
|
455
|
+
try {
|
|
456
|
+
await run.send([{ toSource: source, to: folder }], [], (signal) => deps.client.createFolder(source, folder, { signal }));
|
|
457
|
+
run.createdFolders.push(folder);
|
|
458
|
+
}
|
|
459
|
+
catch (err) {
|
|
460
|
+
if (!(err instanceof ToolError) || err.kind !== "already_exists")
|
|
461
|
+
throw err;
|
|
462
|
+
const probe = await new Inspector(deps.client, deps.facts, {}).probe(source, folder);
|
|
463
|
+
if (probe.kind !== "present" || probe.type !== "directory") {
|
|
464
|
+
throw new ToolError("conflict", "A parent folder could not be created because something else appeared there.", {
|
|
465
|
+
source,
|
|
466
|
+
path: folder,
|
|
467
|
+
details: { reason: "changed_before_send", conflicts: [], allowedResolutions: [] },
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
},
|
|
473
|
+
async send(ops, temps, fn) {
|
|
474
|
+
try {
|
|
475
|
+
return await fn(call.signal);
|
|
476
|
+
}
|
|
477
|
+
catch (err) {
|
|
478
|
+
if (!(err instanceof ToolError))
|
|
479
|
+
throw err;
|
|
480
|
+
if (!["timeout", "cancelled", "network_error"].includes(err.kind) || certainlyNotSent(err))
|
|
481
|
+
throw err;
|
|
482
|
+
deps.recovery.record(tool, ops, temps, err.message);
|
|
483
|
+
throw new ToolError("timeout", "The request was sent but its result is unknown. The server keeps working after a disconnect, so it has probably completed. Check the state (fb_list_dir, fb_get_info) before the next operation.", {
|
|
484
|
+
details: {
|
|
485
|
+
plannedOperations: ops,
|
|
486
|
+
sent: true,
|
|
487
|
+
phase: temps.length ? "temp_created" : "sent",
|
|
488
|
+
leftovers: run.leftovers,
|
|
489
|
+
createdFolders: run.createdFolders,
|
|
490
|
+
cause: err.kind,
|
|
491
|
+
},
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
},
|
|
495
|
+
};
|
|
496
|
+
return run;
|
|
497
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Entry point: load settings, run the startup checks, then serve MCP over stdio.
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { ConfigError, effectiveFlags, loadConfig } from "./config.js";
|
|
5
|
+
import { FatalStartupError } from "./core/state.js";
|
|
6
|
+
import { createLogger, redirectConsoleToStderr } from "./log.js";
|
|
7
|
+
import { buildServer } from "./server.js";
|
|
8
|
+
import { VERSION } from "./version.js";
|
|
9
|
+
/** Startup notice and warnings (design §5.5.1). Settings only: no URL, token, source or path. */
|
|
10
|
+
export function startupMessages(config) {
|
|
11
|
+
const flags = effectiveFlags(config);
|
|
12
|
+
const notice = `filebrowser-quantum-mcp ${VERSION}: mode=${flags.writes ? "read-write" : "read-only"} ` +
|
|
13
|
+
`delete=${flags.delete ? "on" : "off"} share=${flags.share ? "on" : "off"} ` +
|
|
14
|
+
`confirm=${config.confirmPolicy} prompts=${config.elicitation}. Provided "as is" without warranty; keep backups of data this server can reach.`;
|
|
15
|
+
const warnings = [];
|
|
16
|
+
if (flags.delete) {
|
|
17
|
+
warnings.push("Delete tool enabled. FileBrowser has no trash: deletions cannot be undone.");
|
|
18
|
+
}
|
|
19
|
+
if (flags.share) {
|
|
20
|
+
warnings.push("Share link tools enabled. Anyone with a created link can open it without logging in.");
|
|
21
|
+
}
|
|
22
|
+
if (config.allowFolderShare) {
|
|
23
|
+
warnings.push("Folder sharing enabled. Every file inside a shared folder, hidden files included, becomes public. Archives and symlinks to folders can also be shared.");
|
|
24
|
+
}
|
|
25
|
+
return [notice, ...warnings, ...config.warnings];
|
|
26
|
+
}
|
|
27
|
+
async function main() {
|
|
28
|
+
redirectConsoleToStderr();
|
|
29
|
+
let config;
|
|
30
|
+
try {
|
|
31
|
+
config = loadConfig(process.env);
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
if (err instanceof ConfigError) {
|
|
35
|
+
process.stderr.write(`[filebrowser-quantum-mcp] ERROR ${err.message}\n`);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
}
|
|
38
|
+
throw err;
|
|
39
|
+
}
|
|
40
|
+
const log = createLogger(config.logLevel);
|
|
41
|
+
for (const line of config.dangers)
|
|
42
|
+
log.error(line);
|
|
43
|
+
for (const line of startupMessages(config))
|
|
44
|
+
log.warn(line);
|
|
45
|
+
const fatal = (err) => {
|
|
46
|
+
log.error(err.message);
|
|
47
|
+
process.exit(1);
|
|
48
|
+
};
|
|
49
|
+
const { server, state, lock } = buildServer(config, log, fatal);
|
|
50
|
+
try {
|
|
51
|
+
await state.initialize();
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
if (err instanceof FatalStartupError)
|
|
55
|
+
fatal(err);
|
|
56
|
+
throw err;
|
|
57
|
+
}
|
|
58
|
+
const transport = new StdioServerTransport();
|
|
59
|
+
let closing = false;
|
|
60
|
+
const shutdown = async (reason) => {
|
|
61
|
+
if (closing)
|
|
62
|
+
return;
|
|
63
|
+
closing = true;
|
|
64
|
+
log.info(`shutting down (${reason})`);
|
|
65
|
+
// Closing the server aborts in-flight requests (their AbortSignals fire). A write
|
|
66
|
+
// that was already sent (for example a temporary-name replacement) is not aborted:
|
|
67
|
+
// wait for it, up to FILEBROWSER_LONG_TIMEOUT_MS (design §6.2.5).
|
|
68
|
+
await server.close().catch(() => { });
|
|
69
|
+
if (!(await lock.drain(config.longTimeoutMs))) {
|
|
70
|
+
log.warn("Exiting while a write is still running on FileBrowser. Check its state before the next operation.");
|
|
71
|
+
}
|
|
72
|
+
process.exit(0);
|
|
73
|
+
};
|
|
74
|
+
process.stdin.on("end", () => void shutdown("stdin closed"));
|
|
75
|
+
process.stdin.on("close", () => void shutdown("stdin closed"));
|
|
76
|
+
process.on("SIGINT", () => void shutdown("SIGINT"));
|
|
77
|
+
process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
|
78
|
+
await server.connect(transport);
|
|
79
|
+
}
|
|
80
|
+
main().catch((err) => {
|
|
81
|
+
process.stderr.write(`[filebrowser-quantum-mcp] ERROR ${err instanceof Error ? err.message : String(err)}\n`);
|
|
82
|
+
process.exit(1);
|
|
83
|
+
});
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Logger that writes to stderr only. stdout is reserved for JSON-RPC (design §5.5).
|
|
2
|
+
import { format } from "node:util";
|
|
3
|
+
const ORDER = { error: 0, warn: 1, info: 2, debug: 3 };
|
|
4
|
+
export function createLogger(level, write = defaultWrite) {
|
|
5
|
+
const threshold = ORDER[level];
|
|
6
|
+
const emit = (lvl, message) => {
|
|
7
|
+
if (ORDER[lvl] <= threshold) {
|
|
8
|
+
write(`[filebrowser-quantum-mcp] ${lvl.toUpperCase()} ${message}\n`);
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
return {
|
|
12
|
+
error: (m) => emit("error", m),
|
|
13
|
+
warn: (m) => emit("warn", m),
|
|
14
|
+
info: (m) => emit("info", m),
|
|
15
|
+
debug: (m) => emit("debug", m),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function defaultWrite(line) {
|
|
19
|
+
process.stderr.write(line);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Send console.log / info / debug to stderr so that dependencies cannot
|
|
23
|
+
* corrupt the stdio JSON-RPC stream.
|
|
24
|
+
*/
|
|
25
|
+
export function redirectConsoleToStderr() {
|
|
26
|
+
const toStderr = (...args) => {
|
|
27
|
+
process.stderr.write(`${format(...args)}\n`);
|
|
28
|
+
};
|
|
29
|
+
console.log = toStderr;
|
|
30
|
+
console.info = toStderr;
|
|
31
|
+
console.debug = toStderr;
|
|
32
|
+
}
|