@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,65 @@
1
+ // Escaping for paths shown on confirmation screens (design §5.7). Display only:
2
+ // never apply this to paths sent to the server.
3
+ const ESCAPED = /[\p{C}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}‘-‟"←-⇿]/u;
4
+ const SPACE_SEPARATOR = /\p{Zs}/u;
5
+ const MAX_DISPLAY = 120;
6
+ function escapeToken(ch) {
7
+ if (ch === "\\")
8
+ return "\\\\";
9
+ if (ch === '"')
10
+ return '\\"';
11
+ if (ESCAPED.test(ch) || (SPACE_SEPARATOR.test(ch) && ch !== " ")) {
12
+ const hex = (ch.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0");
13
+ return `\\u{${hex}}`;
14
+ }
15
+ return ch;
16
+ }
17
+ /** Escape one path into tokens (one per code point) so shortening never splits an escape. */
18
+ function tokens(path) {
19
+ return Array.from(path, escapeToken);
20
+ }
21
+ function shorten(parts) {
22
+ const text = (segs) => segs.map((seg) => seg.join("")).join("/");
23
+ const full = text(parts);
24
+ if (full.length <= MAX_DISPLAY)
25
+ return full;
26
+ // parts[0] is the empty piece before the leading "/". Keep the first folder and the
27
+ // last segment (file name and extension); replace everything between with "…".
28
+ const segments = parts.slice(1);
29
+ const last = segments[segments.length - 1] ?? [];
30
+ const kept = segments.length >= 3 ? [[], segments[0] ?? [], ["…"]] : parts.slice(0, -1);
31
+ const prefix = `${text(kept)}/`;
32
+ if (prefix.length + last.join("").length <= MAX_DISPLAY)
33
+ return prefix + last.join("");
34
+ // Still too long: cut the middle of the last segment, keeping both ends.
35
+ const keep = Math.max(10, MAX_DISPLAY - prefix.length - 1);
36
+ const head = last.slice(0, Math.ceil(keep / 2));
37
+ const tail = last.slice(last.length - Math.floor(keep / 2));
38
+ return `${prefix}${head.join("")}…${tail.join("")}`;
39
+ }
40
+ /** A source name escaped and quoted for display (design §5.7). */
41
+ export function displaySource(source) {
42
+ return `"${tokens(source).join("")}"`;
43
+ }
44
+ /** `source:"path"` with both parts escaped, quoted, and shortened when long. */
45
+ export function displayPath(source, path) {
46
+ const parts = path.split("/").map(tokens);
47
+ return `${tokens(source).join("")}:"${shorten(parts)}"`;
48
+ }
49
+ export function formatSize(bytes) {
50
+ if (bytes < 1024)
51
+ return `${bytes} B`;
52
+ const units = ["KB", "MB", "GB", "TB"];
53
+ let value = bytes / 1024;
54
+ let unit = 0;
55
+ while (value >= 1024 && unit < units.length - 1) {
56
+ value /= 1024;
57
+ unit++;
58
+ }
59
+ return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
60
+ }
61
+ /** "2026-11-29 10:00 UTC" */
62
+ export function formatTime(iso) {
63
+ const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(iso);
64
+ return m ? `${m[1]} ${m[2]} UTC` : iso;
65
+ }
@@ -0,0 +1,180 @@
1
+ // Looking before writing (design §5.2, §6.2.2 step 4, §6.2.8): resolve destinations,
2
+ // detect conflicts (including items hidden from listings) and shared locations.
3
+ // Nothing here writes.
4
+ import { ToolError } from "../client/errors.js";
5
+ import { checkNewName, foldName, invalidName } from "./names.js";
6
+ import { joinPath } from "./paths.js";
7
+ import { ownShares } from "./shares.js";
8
+ export function parentOf(path) {
9
+ const i = path.lastIndexOf("/");
10
+ return i <= 0 ? "/" : path.slice(0, i);
11
+ }
12
+ export function baseName(path) {
13
+ return path.slice(path.lastIndexOf("/") + 1);
14
+ }
15
+ /** A per-call view of the server. A fresh instance (no cache) is used for rechecks. */
16
+ export class Inspector {
17
+ client;
18
+ facts;
19
+ opts;
20
+ listings = new Map();
21
+ probes = new Map();
22
+ shares;
23
+ constructor(client, facts, opts) {
24
+ this.client = client;
25
+ this.facts = facts;
26
+ this.opts = opts;
27
+ }
28
+ /** Direct GET. Failures that say nothing about existence (timeouts, ...) abort the call. */
29
+ probe(source, path) {
30
+ const key = JSON.stringify([source, path]);
31
+ let p = this.probes.get(key);
32
+ if (!p) {
33
+ p = this.doProbe(source, path);
34
+ this.probes.set(key, p);
35
+ }
36
+ return p;
37
+ }
38
+ async doProbe(source, path) {
39
+ try {
40
+ const res = await this.client.getResource(source, path, this.opts);
41
+ const probe = {
42
+ kind: "present",
43
+ type: res.type,
44
+ size: res.size,
45
+ modified: res.modified,
46
+ };
47
+ if (res.type === "directory") {
48
+ probe.childCount = (res.files?.length ?? 0) + (res.folders?.length ?? 0);
49
+ }
50
+ return probe;
51
+ }
52
+ catch (err) {
53
+ if (!(err instanceof ToolError))
54
+ throw err;
55
+ if (err.kind === "not_found")
56
+ return { kind: "absent" };
57
+ if (err.kind === "permission_denied") {
58
+ return err.status === undefined
59
+ ? { kind: "unknown" }
60
+ : { kind: "unknown", status: err.status };
61
+ }
62
+ throw err;
63
+ }
64
+ }
65
+ /** Names in a folder (files and folders), or null if it is not a folder. */
66
+ list(source, path) {
67
+ const key = JSON.stringify([source, path]);
68
+ let p = this.listings.get(key);
69
+ if (!p) {
70
+ p = this.client.getResource(source, path, this.opts).then((res) => res.type === "directory"
71
+ ? [...(res.folders ?? []), ...(res.files ?? [])].map((e) => e.name)
72
+ : null, (err) => {
73
+ if (err instanceof ToolError && err.kind === "not_found")
74
+ return null;
75
+ throw err;
76
+ });
77
+ this.listings.set(key, p);
78
+ }
79
+ return p;
80
+ }
81
+ /**
82
+ * Resolve a destination path segment by segment (design §5.2): existing segments are
83
+ * kept byte-for-byte; the first missing segment and everything after it are new, so
84
+ * they are NFC-normalized and checked against the OS rules and for case-only clashes.
85
+ */
86
+ async resolve(source, rawPath) {
87
+ const segments = rawPath.split("/").filter((s) => s !== "");
88
+ if (segments.length === 0) {
89
+ throw new ToolError("invalid_argument", "The destination cannot be the root of the source.");
90
+ }
91
+ let prefix = "/";
92
+ const out = [];
93
+ const missing = [];
94
+ let isNew = false;
95
+ for (const [i, raw] of segments.entries()) {
96
+ const last = i === segments.length - 1;
97
+ if (!isNew) {
98
+ const names = (await this.list(source, prefix)) ?? [];
99
+ const nfc = raw.normalize("NFC");
100
+ const existingName = names.includes(raw) ? raw : names.includes(nfc) ? nfc : undefined;
101
+ let exists = existingName !== undefined;
102
+ let name = existingName ?? raw;
103
+ if (!exists) {
104
+ // Not listed: hidden or excluded items are only found by a direct GET.
105
+ const direct = await this.probe(source, joinPath(prefix, raw));
106
+ if (direct.kind !== "absent") {
107
+ exists = true;
108
+ name = raw;
109
+ }
110
+ }
111
+ if (exists) {
112
+ const here = joinPath(prefix, name);
113
+ if (!last) {
114
+ const p = await this.probe(source, here);
115
+ if (p.kind !== "present" || p.type !== "directory") {
116
+ throw new ToolError("invalid_argument", p.kind === "present"
117
+ ? "A parent of the destination is a file, not a folder."
118
+ : "A parent of the destination exists but cannot be inspected.", { source, path: here });
119
+ }
120
+ }
121
+ out.push(name);
122
+ prefix = here;
123
+ continue;
124
+ }
125
+ isNew = true;
126
+ // Case-only (or normalization-only) clash with a different existing name.
127
+ const folded = foldName(nfc);
128
+ const clash = names.find((n) => foldName(n) === folded);
129
+ if (clash !== undefined)
130
+ throw invalidName(nfc, "case_conflict", `Existing: "${clash}".`);
131
+ }
132
+ const name = raw.normalize("NFC");
133
+ const rule = checkNewName(name);
134
+ if (rule)
135
+ throw invalidName(name, rule);
136
+ out.push(name);
137
+ prefix = joinPath(prefix, name);
138
+ if (!last)
139
+ missing.push(prefix);
140
+ }
141
+ return { path: prefix, missing };
142
+ }
143
+ /**
144
+ * Own share paths in a source, made relative to the user's scope (design §6.2.8).
145
+ * Empty when the token cannot list shares (warned at startup).
146
+ */
147
+ async sharedPaths(source) {
148
+ if (!this.facts.tokenCanShare)
149
+ return [];
150
+ if (!this.shares) {
151
+ this.shares = this.client.listShares(this.opts).then((list) => {
152
+ const bySource = new Map();
153
+ for (const share of ownShares(list, this.facts)) {
154
+ bySource.set(share.source, [...(bySource.get(share.source) ?? []), share.path]);
155
+ }
156
+ return bySource;
157
+ });
158
+ }
159
+ return (await this.shares).get(source) ?? [];
160
+ }
161
+ async isShared(source, path) {
162
+ for (const shared of await this.sharedPaths(source)) {
163
+ if (shared === "/" || path === shared || path.startsWith(`${shared}/`))
164
+ return true;
165
+ }
166
+ return false;
167
+ }
168
+ }
169
+ /** Equality of two probes for the recheck before sending (design §6.2.10). */
170
+ export function sameProbe(a, b) {
171
+ if (a.kind !== b.kind)
172
+ return false;
173
+ if (a.kind === "present" && b.kind === "present") {
174
+ return (a.type === b.type &&
175
+ a.size === b.size &&
176
+ a.modified === b.modified &&
177
+ a.childCount === b.childCount);
178
+ }
179
+ return true;
180
+ }
@@ -0,0 +1,54 @@
1
+ // Process-wide serialization of "recheck + execute" for writes, and reservation of
2
+ // alternative names (design §6.2.2 step 6, §6.2.9).
3
+ import { ToolError } from "../client/errors.js";
4
+ export class WriteLock {
5
+ tail = Promise.resolve();
6
+ reserved = new Set();
7
+ /**
8
+ * Run fn while holding the lock. If the signal aborts while waiting, fn is not run.
9
+ * Note: fn must not wait for user confirmation (design §6.2.2).
10
+ */
11
+ async run(signal, fn) {
12
+ let release;
13
+ const mine = new Promise((resolve) => {
14
+ release = resolve;
15
+ });
16
+ const previous = this.tail;
17
+ this.tail = previous.then(() => mine);
18
+ try {
19
+ await previous;
20
+ if (signal?.aborted) {
21
+ throw new ToolError("cancelled", "The request was cancelled before anything was sent.");
22
+ }
23
+ return await fn();
24
+ }
25
+ finally {
26
+ release();
27
+ }
28
+ }
29
+ /** Wait for the running and queued writes, at most `timeoutMs` (used at shutdown). */
30
+ async drain(timeoutMs) {
31
+ let timer;
32
+ const timeout = new Promise((resolve) => {
33
+ timer = setTimeout(() => resolve(false), timeoutMs);
34
+ });
35
+ const done = this.tail.then(() => true);
36
+ try {
37
+ return await Promise.race([done, timeout]);
38
+ }
39
+ finally {
40
+ clearTimeout(timer);
41
+ }
42
+ }
43
+ isReserved(source, path) {
44
+ return this.reserved.has(key(source, path));
45
+ }
46
+ reserve(source, path) {
47
+ const k = key(source, path);
48
+ this.reserved.add(k);
49
+ return () => this.reserved.delete(k);
50
+ }
51
+ }
52
+ function key(source, path) {
53
+ return JSON.stringify([source, path.normalize("NFC").toLowerCase()]);
54
+ }
@@ -0,0 +1,131 @@
1
+ // Fixed texts for confirmation screens and results (design §6.2.4, §6.2.11).
2
+ // Built only from these templates and escaped paths: never from text the LLM supplied.
3
+ const VERB = {
4
+ en: {
5
+ write: "Write file",
6
+ create_folder: "Create folder",
7
+ move: "Move",
8
+ copy: "Copy",
9
+ rename: "Rename",
10
+ archive: "Create archive",
11
+ unarchive: "Extract archive",
12
+ },
13
+ ja: {
14
+ write: "ファイルの書き込み",
15
+ create_folder: "フォルダの作成",
16
+ move: "移動",
17
+ copy: "コピー",
18
+ rename: "名前の変更",
19
+ archive: "アーカイブの作成",
20
+ unarchive: "アーカイブの展開",
21
+ },
22
+ };
23
+ const T = {
24
+ en: {
25
+ conflictHead: (n, files, folders) => `Something with the same name already exists at the destination. ${n} item(s) (files ${files}, folders ${folders})`,
26
+ externalHead: "This operation needs your approval.",
27
+ sources: (from, to) => from ? `From source: ${from} / To source: ${to}` : `Source: ${to}`,
28
+ from: "From",
29
+ to: "To",
30
+ existing: "existing",
31
+ unknownExisting: "exists but cannot be inspected",
32
+ newItem: "new",
33
+ newContent: (size) => `New content: ${size}`,
34
+ shrink: "Warning: the new content is less than half the size of the existing one; most of the existing content will be lost. (On sources that report disk usage as size, this warning may not appear.)",
35
+ notFullyRead: "Warning: this file has not been read in full by the assistant.",
36
+ tempMayRemain: "If replacing fails, a temporary file may be left behind (no delete permission to clean it up).",
37
+ crossSource: "Writes to a different source.",
38
+ shared: "Writes into a folder or file that has a share link: the new content may become public.",
39
+ choices: (overwrite, example) => `cancel = do nothing / rename = save under a new name (e.g. ${example})${overwrite ? " / overwrite = replace the existing item" : ""}`,
40
+ choiceDescription: (overwrite) => `cancel: do nothing. rename: save under a new name.${overwrite ? " overwrite: replace the existing item." : ""}`,
41
+ confirmDescription: (what) => `Approve: ${what}`,
42
+ approveExternal: "write to another source / a shared location",
43
+ noOverwrite: "Overwriting is not offered for this operation.",
44
+ },
45
+ ja: {
46
+ conflictHead: (n, files, folders) => `移動先・作成先に同じ名前のものがあります。${n} 件(ファイル ${files}、フォルダ ${folders})`,
47
+ externalHead: "この操作には承認が必要です。",
48
+ sources: (from, to) => from ? `移動元のソース: ${from} / 移動先のソース: ${to}` : `ソース: ${to}`,
49
+ from: "移動元",
50
+ to: "移動先",
51
+ existing: "既存",
52
+ unknownExisting: "存在するが中身を確かめられない",
53
+ newItem: "新しいもの",
54
+ newContent: (size) => `新しい内容: ${size}`,
55
+ shrink: "警告: 新しい内容が既存の半分未満の大きさです。既存の内容の大部分が失われます(サイズがディスク使用量のソースでは、この警告が出ないことがあります)。",
56
+ notFullyRead: "警告: このファイルは全体が読まれていません。",
57
+ tempMayRemain: "置き換えに失敗したとき、一時ファイルが残ることがあります(削除の権限がないため)。",
58
+ crossSource: "別のソースへ書き込みます。",
59
+ shared: "共有リンクのあるフォルダ・ファイルへ書き込みます。新しい内容が公開される可能性があります。",
60
+ choices: (overwrite, example) => `cancel = 何もしない / rename = 名前を変えて保存する(例: ${example})${overwrite ? " / overwrite = 既存のものを置き換える" : ""}`,
61
+ choiceDescription: (overwrite) => `cancel: 何もしない。rename: 名前を変えて保存する。${overwrite ? "overwrite: 既存のものを置き換える。" : ""}`,
62
+ confirmDescription: (what) => `承認する: ${what}`,
63
+ approveExternal: "別のソース・共有中の場所への書き込み",
64
+ noOverwrite: "この操作では上書きを選べません。",
65
+ },
66
+ };
67
+ const DELETE = {
68
+ en: {
69
+ head: (n, files, folders) => `[Delete] Permanently delete ${n} item(s) (files ${files}, folders ${folders})`,
70
+ file: "file",
71
+ folder: (children) => `folder, ${children} item(s) directly inside`,
72
+ warning: "Everything inside is deleted too, including files not shown in listings (hidden files and others). FileBrowser has no trash: this cannot be undone.",
73
+ tempNote: "This is a temporary file made by the MCP server. It may hold new content: check it before deleting.",
74
+ confirm: (n) => `Approve: permanently delete ${n} item(s)`,
75
+ },
76
+ ja: {
77
+ head: (n, files, folders) => `[削除] 次の ${n} 件を完全に削除します(ファイル ${files}、フォルダ ${folders})`,
78
+ file: "ファイル",
79
+ folder: (children) => `フォルダ、直下 ${children} 件`,
80
+ warning: "一覧に出ないファイル(隠しファイルなど)も含めて中身ごと消えます。FileBrowser にゴミ箱はなく、元に戻せません。",
81
+ tempNote: "MCP が作った一時ファイルです。新しい内容が入っていることがあるので、中身を確かめてから消してください。",
82
+ confirm: (n) => `承認する: ${n} 件を完全に削除する`,
83
+ },
84
+ };
85
+ export function deleteTexts(lang) {
86
+ return DELETE[lang];
87
+ }
88
+ const SHARE = {
89
+ en: {
90
+ head: "[Share link] This makes the following item viewable from outside FileBrowser by anyone with the link.",
91
+ file: "file",
92
+ folder: "folder",
93
+ expires: (when) => `Expires: ${when}`,
94
+ password: (yes) => `Password: ${yes ? "yes" : "none"}`,
95
+ downloads: (limit) => `Download limit: ${limit ?? "none"}`,
96
+ folderWarning: "Hidden files inside the folder can also be fetched by anyone who knows their path.",
97
+ confirm: "Approve: create a public share link",
98
+ },
99
+ ja: {
100
+ head: "[共有リンク] この操作は、次の項目をリンクを知っている誰でも FileBrowser の外から見られるようにします。",
101
+ file: "ファイル",
102
+ folder: "フォルダ",
103
+ expires: (when) => `有効期限: ${when}`,
104
+ password: (yes) => `パスワード: ${yes ? "あり" : "なし"}`,
105
+ downloads: (limit) => `ダウンロード回数の上限: ${limit ?? "なし"}`,
106
+ folderWarning: "フォルダの中の隠しファイルも、パスを知っていれば誰でも取得できます。",
107
+ confirm: "承認する: 公開の共有リンクを作る",
108
+ },
109
+ };
110
+ export function shareTexts(lang) {
111
+ return SHARE[lang];
112
+ }
113
+ export function texts(lang) {
114
+ return T[lang];
115
+ }
116
+ export function verbLabel(lang, verb) {
117
+ return VERB[lang][verb];
118
+ }
119
+ /** Result text for a cancellation. English only: it is read by the LLM. */
120
+ export function cancelMessage(reason) {
121
+ switch (reason) {
122
+ case "declined":
123
+ case "dismissed":
124
+ case "unconfirmed":
125
+ return "The user cancelled. Nothing was changed. Do not retry with different arguments on your own.";
126
+ case "timeout":
127
+ return "The confirmation timed out. Nothing was changed. Ask the user whether to show the confirmation again.";
128
+ default:
129
+ return "The confirmation screen did not work. Nothing was changed.";
130
+ }
131
+ }
@@ -0,0 +1,114 @@
1
+ // Rules for names the MCP server creates (design §5.2), alternative names (§6.2.9)
2
+ // and temporary names (§6.2.5).
3
+ import { randomBytes } from "node:crypto";
4
+ import { ToolError } from "../client/errors.js";
5
+ const MAX_NAME_BYTES = 255;
6
+ const FORBIDDEN = new Set(["<", ">", ":", '"', "/", "\\", "|", "?", "*"]);
7
+ const RESERVED = new Set([
8
+ "CON",
9
+ "PRN",
10
+ "AUX",
11
+ "NUL",
12
+ ...Array.from({ length: 10 }, (_, i) => `COM${i}`),
13
+ ...Array.from({ length: 10 }, (_, i) => `LPT${i}`),
14
+ "COM¹",
15
+ "COM²",
16
+ "COM³",
17
+ "LPT¹",
18
+ "LPT²",
19
+ "LPT³",
20
+ ]);
21
+ // Characters that can fake how a name looks (bidi controls, zero-width, tags, private use,
22
+ // unassigned, line/paragraph separators, ignorable code points).
23
+ const INVISIBLE = /[\p{Cf}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u;
24
+ const SPACE_SEPARATOR = /\p{Zs}/u;
25
+ const RULE_TEXT = {
26
+ empty: "The name is empty.",
27
+ dot_name: '"." and ".." are not allowed as names (they mean the current and parent folder on every OS).',
28
+ forbidden_character: 'The name contains a character that Windows does not allow (< > : " / \\ | ? *). ":" is also a separator in the macOS Finder.',
29
+ control_character: "The name contains a control character (U+0000-U+001F or U+007F, such as a line break or tab). Windows does not allow them.",
30
+ invisible_character: "The name contains an invisible or formatting character (for example a bidirectional control or zero-width character) or an unusual space, which can make a name look like something else.",
31
+ reserved_name: "The name is a Windows device name (CON, PRN, AUX, NUL, COM0-9, LPT0-9), with or without an extension. Windows cannot use it.",
32
+ trailing_space_or_dot: "The name ends with a space or a dot. Windows removes them silently.",
33
+ too_long: `The name is longer than ${MAX_NAME_BYTES} bytes in UTF-8, the limit on Linux file systems.`,
34
+ case_conflict: "A name that differs only in upper/lower case (or Unicode normalization) already exists in this folder. Windows and macOS treat them as the same name, so syncing would clash.",
35
+ };
36
+ export function invalidName(segment, rule, extra = "") {
37
+ return new ToolError("invalid_name", `${RULE_TEXT[rule]}${extra ? ` ${extra}` : ""}`, {
38
+ details: { segment, rule },
39
+ });
40
+ }
41
+ /** Return the first rule a new name breaks, or undefined (the name must already be NFC). */
42
+ export function checkNewName(name) {
43
+ if (name === "")
44
+ return "empty";
45
+ if (name === "." || name === "..")
46
+ return "dot_name";
47
+ for (const ch of name) {
48
+ const cp = ch.codePointAt(0) ?? 0;
49
+ if (FORBIDDEN.has(ch))
50
+ return "forbidden_character";
51
+ if (cp <= 0x1f || cp === 0x7f)
52
+ return "control_character";
53
+ }
54
+ for (const ch of name) {
55
+ const cp = ch.codePointAt(0) ?? 0;
56
+ if (cp >= 0x80 && cp <= 0x9f)
57
+ return "control_character";
58
+ if (INVISIBLE.test(ch))
59
+ return "invisible_character";
60
+ if (SPACE_SEPARATOR.test(ch) && ch !== " " && ch !== " ")
61
+ return "invisible_character";
62
+ }
63
+ if (/[ .]$/.test(name))
64
+ return "trailing_space_or_dot";
65
+ const base = (name.split(".")[0] ?? "").toUpperCase();
66
+ if (RESERVED.has(base))
67
+ return "reserved_name";
68
+ if (Buffer.byteLength(name, "utf8") > MAX_NAME_BYTES)
69
+ return "too_long";
70
+ return undefined;
71
+ }
72
+ export function assertNewName(name) {
73
+ const rule = checkNewName(name);
74
+ if (rule)
75
+ throw invalidName(name, rule);
76
+ }
77
+ /** Key for "same name on a case-insensitive, normalizing file system". */
78
+ export function foldName(name) {
79
+ return name.normalize("NFC").toLowerCase().normalize("NFC");
80
+ }
81
+ const DOUBLE_EXTENSIONS = [".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst"];
82
+ /** Split "report.txt" -> ["report", ".txt"]; ".env" -> [".env", ""]; "a.tar.gz" -> ["a", ".tar.gz"]. */
83
+ export function splitExtension(name) {
84
+ const lower = name.toLowerCase();
85
+ for (const ext of DOUBLE_EXTENSIONS) {
86
+ if (lower.endsWith(ext) && name.length > ext.length) {
87
+ return [name.slice(0, -ext.length), name.slice(-ext.length)];
88
+ }
89
+ }
90
+ const dot = name.lastIndexOf(".");
91
+ if (dot <= 0)
92
+ return [name, ""];
93
+ return [name.slice(0, dot), name.slice(dot)];
94
+ }
95
+ /** Candidates name(1).ext, name(2).ext, ... continuing an existing "(N)" (design §6.2.9). */
96
+ export function* alternativeNames(name, style) {
97
+ const [stem, ext] = style === "folder" ? [name, ""] : splitExtension(name);
98
+ const numbered = /^(.*)\((\d+)\)$/.exec(stem);
99
+ const base = numbered ? (numbered[1] ?? "") : stem;
100
+ const start = numbered ? Number(numbered[2]) + 1 : 1;
101
+ for (let n = start; n <= 1000; n++)
102
+ yield `${base}(${n})${ext}`;
103
+ }
104
+ /** "<stem>.mcp-tmp-<16 hex><ext>" kept within 255 bytes (design §6.2.5). */
105
+ export function temporaryName(name) {
106
+ const [stem, ext] = splitExtension(name);
107
+ const marker = `.mcp-tmp-${randomBytes(8).toString("hex")}`;
108
+ let head = stem;
109
+ while (Buffer.byteLength(`${head}${marker}${ext}`, "utf8") > MAX_NAME_BYTES && head.length > 1) {
110
+ head = Array.from(head).slice(0, -1).join("");
111
+ }
112
+ return `${head}${marker}${ext}`;
113
+ }
114
+ export const TEMP_MARKER = ".mcp-tmp-";
@@ -0,0 +1,41 @@
1
+ // Path validation and normalization for every path argument (design §5.2).
2
+ // Rules for *new* names (OS restrictions) live in names.ts and are applied only by write tools.
3
+ import { ToolError } from "../client/errors.js";
4
+ export const MAX_PATH_BYTES = 4096;
5
+ /**
6
+ * Normalize a path inside a source:
7
+ * - add a leading "/", collapse "//", drop a trailing "/" (except for the root)
8
+ * - reject "." and ".." segments, NUL, and "\" (the server treats "\" as a separator)
9
+ * Control characters other than NUL are allowed so that existing odd names stay reachable.
10
+ */
11
+ export function normalizePath(input, argName = "path") {
12
+ if (input.includes("\u0000")) {
13
+ throw new ToolError("invalid_argument", `${argName} must not contain NUL characters.`);
14
+ }
15
+ if (input.includes("\\")) {
16
+ throw new ToolError("invalid_argument", `${argName} must not contain "\\". FileBrowser treats it as a folder separator; use "/".`);
17
+ }
18
+ if (Buffer.byteLength(input, "utf8") > MAX_PATH_BYTES) {
19
+ throw new ToolError("invalid_argument", `${argName} is longer than ${MAX_PATH_BYTES} bytes.`);
20
+ }
21
+ const segments = input.split("/").filter((s) => s !== "");
22
+ for (const segment of segments) {
23
+ if (segment === "." || segment === "..") {
24
+ throw new ToolError("invalid_argument", `${argName} must not contain "." or ".." segments. Use an absolute path inside the source.`);
25
+ }
26
+ }
27
+ return `/${segments.join("/")}`;
28
+ }
29
+ /** Join a folder path and a child name (both already normalized / plain). */
30
+ export function joinPath(parent, name) {
31
+ return parent === "/" ? `/${name}` : `${parent}/${name}`;
32
+ }
33
+ /**
34
+ * Turn a path returned by the server into an absolute path inside the source.
35
+ * Search results have no leading "/", are relative to the scope, and end in "/"
36
+ * for folders (design §5.2, verified).
37
+ */
38
+ export function toAbsolutePath(serverPath, scope = "/") {
39
+ const relative = serverPath.replace(/^\/+|\/+$/g, "");
40
+ return relative === "" ? scope : joinPath(scope, relative);
41
+ }
@@ -0,0 +1,39 @@
1
+ // Records how much of each file version was read from the start (design §6.3 fb_read_file).
2
+ // fb_write_file uses it to warn before overwriting a file that was not read in full.
3
+ const TTL_MS = 60 * 60 * 1000;
4
+ export class ReadTracker {
5
+ now;
6
+ entries = new Map();
7
+ constructor(now = Date.now) {
8
+ this.now = now;
9
+ }
10
+ record(source, path, modified, start, end, reachedEnd) {
11
+ this.prune();
12
+ const key = keyOf(source, path, modified);
13
+ const entry = this.entries.get(key) ?? { readUpTo: 0, full: false, at: 0 };
14
+ if (start <= entry.readUpTo) {
15
+ entry.readUpTo = Math.max(entry.readUpTo, end);
16
+ if (reachedEnd)
17
+ entry.full = true;
18
+ }
19
+ entry.at = this.now();
20
+ // Re-insert so that the Map's order is the order of `at` (prune can stop early).
21
+ this.entries.delete(key);
22
+ this.entries.set(key, entry);
23
+ }
24
+ isFullyRead(source, path, modified) {
25
+ this.prune();
26
+ return this.entries.get(keyOf(source, path, modified))?.full === true;
27
+ }
28
+ prune() {
29
+ const limit = this.now() - TTL_MS;
30
+ for (const [key, entry] of this.entries) {
31
+ if (entry.at >= limit)
32
+ break;
33
+ this.entries.delete(key);
34
+ }
35
+ }
36
+ }
37
+ function keyOf(source, path, modified) {
38
+ return JSON.stringify([source, path, modified]);
39
+ }