obsidian-sync-mcp 0.12.1 → 0.13.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.
package/dist/main.js CHANGED
@@ -10,18 +10,21 @@ import {
10
10
  AttachmentExistsError,
11
11
  AttachmentMoveIncompleteError,
12
12
  AttachmentTooLargeError,
13
+ NoteExistsError,
14
+ NoteNotFoundError,
15
+ PARSER_VERSION,
13
16
  attachmentExtension,
14
17
  isValidAttachmentPath,
15
18
  isValidNotePath,
16
19
  parseAttachmentExtensions,
17
20
  parseFrontmatterAndLinks,
18
21
  validateAttachmentPath
19
- } from "./chunk-XZ4HUASL.js";
22
+ } from "./chunk-IQ2E4UFT.js";
20
23
 
21
24
  // src/main.ts
22
25
  import { FastMCP } from "fastmcp";
23
26
  import { join } from "path";
24
- import { createHash as createHash2 } from "crypto";
27
+ import { createHash as createHash3 } from "crypto";
25
28
  import { watch, readFileSync, statSync } from "fs";
26
29
  import { stat } from "fs/promises";
27
30
  import { setGlobalLogFunction, LEVEL_INFO } from "octagonal-wheels/common/logger";
@@ -432,7 +435,7 @@ function renderPasswordPage(code, csrf, redirectHost, clientName, error) {
432
435
  // src/search.ts
433
436
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, chmod as chmod2 } from "fs/promises";
434
437
  import { dirname as dirname2 } from "path";
435
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, scryptSync } from "crypto";
438
+ import { createCipheriv, createDecipheriv, createHash as createHash2, randomBytes as randomBytes2, scryptSync } from "crypto";
436
439
  function encrypt(text, passphrase) {
437
440
  const salt = randomBytes2(16);
438
441
  const key = scryptSync(passphrase, salt, 32);
@@ -466,6 +469,11 @@ var SearchIndex = class {
466
469
  content = /* @__PURE__ */ new Map();
467
470
  /** Frontmatter `title:` per path, when present — searched together with the path. */
468
471
  titles = /* @__PURE__ */ new Map();
472
+ /**
473
+ * Hash of the text each note's tags, links and title were parsed from.
474
+ * Persisted, so the startup rebuild skips parsing notes that haven't changed.
475
+ */
476
+ hashes = /* @__PURE__ */ new Map();
469
477
  /** Binary attachments (path -> size and mtime). Metadata only: their bytes are never read for the index. */
470
478
  attachments = /* @__PURE__ */ new Map();
471
479
  saving = false;
@@ -503,6 +511,10 @@ var SearchIndex = class {
503
511
  this.backlinks.get(key).add(path);
504
512
  }
505
513
  }
514
+ if (data.parser === PARSER_VERSION) {
515
+ for (const [path, h] of Object.entries(data.hashes ?? {})) this.hashes.set(path, h);
516
+ for (const [path, t] of Object.entries(data.titles ?? {})) this.titles.set(path, t);
517
+ }
506
518
  for (const [path, v] of Object.entries(data.attachments ?? {})) {
507
519
  const [size, mtime] = v;
508
520
  this.attachments.set(path, { size, mtime });
@@ -524,6 +536,9 @@ var SearchIndex = class {
524
536
  mtimes: Object.fromEntries(this.mtimes),
525
537
  tags: Object.fromEntries(this.tags),
526
538
  links: Object.fromEntries(this.links),
539
+ parser: PARSER_VERSION,
540
+ hashes: Object.fromEntries(this.hashes),
541
+ titles: Object.fromEntries(this.titles),
527
542
  attachments: Object.fromEntries([...this.attachments].map(([p, a]) => [p, [a.size, a.mtime]])),
528
543
  since: this._since
529
544
  });
@@ -545,17 +560,24 @@ var SearchIndex = class {
545
560
  * catch-up both write here without coordinating, so a write whose mtime is
546
561
  * not newer than the one recorded for text already held is skipped: a
547
562
  * stale copy can never replace a newer one. Mtimes loaded from disk carry
548
- * no text, so the startup rebuild still fills them in.
563
+ * no text, so the startup rebuild still fills them in; when the text's
564
+ * hash matches the one saved, the saved tags, links and title are kept
565
+ * and the note isn't parsed again.
549
566
  */
550
567
  update(path, content, mtime) {
551
568
  if (mtime !== void 0 && this.content.has(path) && mtime <= (this.mtimes.get(path) ?? -Infinity)) return;
552
- if (this.knownPaths.has(path)) {
553
- this.clearBacklinks(path);
554
- }
569
+ const hash = createHash2("sha1").update(content).digest("base64");
570
+ const unchanged = this.knownPaths.has(path) && this.hashes.get(path) === hash;
555
571
  this.knownPaths.add(path);
556
572
  if (mtime !== void 0) this.mtimes.set(path, mtime);
557
573
  this.content.set(path, content);
574
+ if (unchanged) return;
575
+ this.clearBacklinks(path);
576
+ this.hashes.delete(path);
558
577
  const parsed = parseFrontmatterAndLinks(content);
578
+ if (parsed.frontmatterError) {
579
+ console.warn(`Frontmatter of ${path} is not valid YAML, so its properties and tags are ignored: ${parsed.frontmatterError}`);
580
+ }
559
581
  const title = parsed.frontmatter["title"];
560
582
  if (typeof title === "string" && title.trim().length > 0) {
561
583
  this.titles.set(path, title.trim());
@@ -577,6 +599,7 @@ var SearchIndex = class {
577
599
  } else {
578
600
  this.links.delete(path);
579
601
  }
602
+ this.hashes.set(path, hash);
580
603
  }
581
604
  /** Remove a note from the index. */
582
605
  remove(path) {
@@ -586,6 +609,7 @@ var SearchIndex = class {
586
609
  this.tags.delete(path);
587
610
  this.content.delete(path);
588
611
  this.titles.delete(path);
612
+ this.hashes.delete(path);
589
613
  this.clearBacklinks(path);
590
614
  }
591
615
  }
@@ -850,16 +874,114 @@ function makeDeepLink(vaultName, notePath) {
850
874
  }
851
875
 
852
876
  // src/write-scope.ts
877
+ var WRITE_ACTIONS = ["create", "update", "delete"];
878
+ var ALL = new Set(WRITE_ACTIONS);
879
+ var NONE = /* @__PURE__ */ new Set();
853
880
  function parseWriteFolders(raw) {
854
881
  if (raw === void 0) return null;
855
- const folders = raw.split(",").map((f) => f.trim().replace(/^\/+|\/+$/g, "")).filter(Boolean);
856
- return folders.length > 0 ? folders : null;
882
+ const rules = [];
883
+ const seen = /* @__PURE__ */ new Map();
884
+ for (const entry of raw.split(",").map((e) => e.trim()).filter(Boolean)) {
885
+ const colon = entry.lastIndexOf(":");
886
+ const rawFolder = colon === -1 ? entry : entry.slice(0, colon);
887
+ const folder = rawFolder.trim().replace(/^\/+|\/+$/g, "");
888
+ if (folder === "" && rawFolder.trim() === "") {
889
+ throw new Error(`WRITE_FOLDERS: '${entry}' has no folder. Use '/' for the vault root.`);
890
+ }
891
+ const shape = folderShapeProblem(folder);
892
+ if (shape) throw new Error(`WRITE_FOLDERS: '${entry}' ${shape}.`);
893
+ let allow = ALL;
894
+ if (colon !== -1) {
895
+ const perms = entry.slice(colon + 1).split("+").map((p) => p.trim());
896
+ for (const p of perms) {
897
+ if (!WRITE_ACTIONS.includes(p)) {
898
+ throw new Error(
899
+ `WRITE_FOLDERS: unknown permission '${p}' in '${entry}'. Use ${WRITE_ACTIONS.join(", ")}, joined with '+' (e.g. '${rawFolder.trim()}:create+update').`
900
+ );
901
+ }
902
+ }
903
+ allow = new Set(perms);
904
+ }
905
+ const key = fold(folder);
906
+ const earlier = seen.get(key);
907
+ if (earlier !== void 0) {
908
+ const why = earlier === folder ? "" : ` (also as '${earlier}'; folder names are compared ignoring case)`;
909
+ throw new Error(`WRITE_FOLDERS: '${folder || "/"}' is listed more than once${why}.`);
910
+ }
911
+ seen.set(key, folder);
912
+ rules.push({ folder, allow });
913
+ }
914
+ return rules.length > 0 ? rules : null;
857
915
  }
858
- function isPathWritable(path, writeFolders) {
859
- if (writeFolders === null) return true;
860
- const normalized = path.replace(/^\/+/, "");
861
- if (normalized.split(/[/\\]/).includes("..")) return false;
862
- return writeFolders.some((folder) => normalized.startsWith(folder + "/"));
916
+ function folderShapeProblem(folder) {
917
+ if (folder.includes("\\")) return "uses a backslash; separate folders with '/'";
918
+ const segments = folder === "" ? [] : folder.split("/");
919
+ if (segments.some((s) => s === "" || s === "." || s === "..")) return "has an empty, '.' or '..' folder segment";
920
+ return null;
921
+ }
922
+ function normalizePath(path) {
923
+ const normalized = path.replace(/\\/g, "/").replace(/\/{2,}/g, "/").replace(/^\//, "");
924
+ const segments = normalized.split("/");
925
+ if (segments.includes("..")) return null;
926
+ return segments.filter((s) => s !== ".").join("/");
927
+ }
928
+ function contains(folder, path) {
929
+ return folder === "" || path.startsWith(folder + "/");
930
+ }
931
+ function mostSpecific(rules, path, key) {
932
+ const p = key(path);
933
+ let best = null;
934
+ for (const rule of rules) {
935
+ if (contains(key(rule.folder), p) && (!best || rule.folder.length > best.folder.length)) best = rule;
936
+ }
937
+ return best;
938
+ }
939
+ function fold(s) {
940
+ return s.normalize("NFC").toUpperCase().toLowerCase().split("/").map((seg) => seg.replace(/[. ]+$/, "")).join("/");
941
+ }
942
+ function resolve(path, scope) {
943
+ if (scope === null) return { allow: ALL, rules: [] };
944
+ const normalized = normalizePath(path);
945
+ if (normalized === null) return { allow: NONE, rules: [] };
946
+ const exact = mostSpecific(scope, normalized, (s) => s);
947
+ const folded = mostSpecific(scope, normalized, fold);
948
+ if (!folded) return { allow: NONE, rules: [] };
949
+ if (!exact) return { allow: NONE, rules: [folded] };
950
+ if (exact === folded) return { allow: exact.allow, rules: [exact] };
951
+ const allow = new Set([...exact.allow].filter((a) => folded.allow.has(a)));
952
+ return { allow, rules: folded.folder.length > exact.folder.length ? [folded, exact] : [exact, folded] };
953
+ }
954
+ function allowedActions(path, scope) {
955
+ return resolve(path, scope).allow;
956
+ }
957
+ function writeScopeWarnings(scope) {
958
+ if (scope === null) return [];
959
+ return scope.filter((r) => r.allow.size === ALL.size && WRITE_ACTIONS.includes(r.folder)).map((r) => `WRITE_FOLDERS: '${r.folder}' is read as a fully writable folder named '${r.folder}/'. To combine permissions, join them with '+' (e.g. 'Raw:create+${r.folder}').`);
960
+ }
961
+ var folderLabel = (folder) => folder === "" ? "/" : folder + "/";
962
+ function describeFolders(scope) {
963
+ return scope.map((r) => {
964
+ const label = folderLabel(r.folder);
965
+ if (r.allow.size === ALL.size) return label;
966
+ return `${label} (${WRITE_ACTIONS.filter((a) => r.allow.has(a)).join("+")} only)`;
967
+ }).join(", ");
968
+ }
969
+ function describeWriteScope(scope) {
970
+ if (scope === null) return "";
971
+ const limited = scope.some((r) => r.allow.size < ALL.size);
972
+ const legend = limited ? " create = add new files, update = change existing files, delete = delete or move files away; the most specific folder applies." : "";
973
+ return ` Writes are only allowed inside: ${describeFolders(scope)}.${legend}`;
974
+ }
975
+ var VERB = { create: "created", update: "changed", delete: "deleted or moved" };
976
+ function checkWrite(path, action, scope) {
977
+ const { allow, rules } = resolve(path, scope);
978
+ if (allow.has(action)) return null;
979
+ const rule = rules.find((r) => !r.allow.has(action));
980
+ if (!rule) {
981
+ return `Write access denied: '${path}' is outside the writable folders (${describeFolders(scope ?? [])}).`;
982
+ }
983
+ const allowed = WRITE_ACTIONS.filter((a) => rule.allow.has(a)).join("+");
984
+ return `Write access denied: ${folderLabel(rule.folder)} allows only ${allowed}, so '${path}' can't be ${VERB[action]}.`;
863
985
  }
864
986
 
865
987
  // src/list-format.ts
@@ -867,7 +989,7 @@ var MAX_NAMED_FOLDERS = 10;
867
989
  function plural(n, word) {
868
990
  return `${n} ${word}${n === 1 ? "" : "s"}`;
869
991
  }
870
- function folderLabel(folder) {
992
+ function folderLabel2(folder) {
871
993
  return folder.endsWith("/") ? folder : folder + "/";
872
994
  }
873
995
  function countByFolder(paths) {
@@ -883,7 +1005,7 @@ function describeOmitted(omitted) {
883
1005
  const groups = countByFolder(omitted);
884
1006
  const named = groups.slice(0, MAX_NAMED_FOLDERS);
885
1007
  const rest = groups.slice(MAX_NAMED_FOLDERS);
886
- const parts = named.map((g) => `${g.folder === "(root)" ? "(root)" : folderLabel(g.folder)} (${g.count})`);
1008
+ const parts = named.map((g) => `${g.folder === "(root)" ? "(root)" : folderLabel2(g.folder)} (${g.count})`);
887
1009
  let text = `Omitted ${omitted.length}: ${parts.join(", ")}`;
888
1010
  if (rest.length > 0) {
889
1011
  const restNotes = rest.reduce((sum, g) => sum + g.count, 0);
@@ -914,14 +1036,14 @@ function describeNoMatch(s) {
914
1036
  return `Vault is empty.${indexNote}`;
915
1037
  }
916
1038
  const count = describeScopeCount(s);
917
- const scope = (s.folder ? ` in folder "${folderLabel(s.folder)}"` : "") + (count ? ` (${count})` : "");
1039
+ const scope = (s.folder ? ` in folder "${folderLabel2(s.folder)}"` : "") + (count ? ` (${count})` : "");
918
1040
  return `No notes match ${s.filters.join(", ")}${scope}.${indexNote}`;
919
1041
  }
920
1042
  function describeListing(s) {
921
1043
  const truncated = s.matched > s.shown;
922
1044
  const verb = truncated ? "matching" : s.matched === 1 ? "matches" : "match";
923
1045
  const filterClause = s.filters.length > 0 ? ` ${verb} ${s.filters.join(", ")}` : "";
924
- const folderClause = s.folder ? ` in folder "${folderLabel(s.folder)}"` : "";
1046
+ const folderClause = s.folder ? ` in folder "${folderLabel2(s.folder)}"` : "";
925
1047
  const scopeParts = [];
926
1048
  const count = s.filters.length > 0 || s.folder ? describeScopeCount(s) : "";
927
1049
  if (count) scopeParts.push(count);
@@ -1030,10 +1152,9 @@ function registerTools(server2, vault2, searchIndex2, vaultName, readOnly = fals
1030
1152
  if (readOnly) {
1031
1153
  console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(", ")}).`);
1032
1154
  } else if (writeFolders) {
1033
- console.log(`WRITE_FOLDERS: writes restricted to ${writeFolders.map((f) => f + "/").join(", ")}.`);
1155
+ console.log(`WRITE_FOLDERS: writes restricted to ${describeFolders(writeFolders)}.`);
1034
1156
  }
1035
- const writeScopeNote = writeFolders ? ` Writes are only allowed inside: ${writeFolders.map((f) => f + "/").join(", ")}.` : "";
1036
- const denyWrite = (path) => `Write access denied: '${path}' is outside the writable folders (${writeFolders.map((f) => f + "/").join(", ")}).`;
1157
+ const writeScopeNote = describeWriteScope(writeFolders);
1037
1158
  const _addTool = server2.addTool.bind(server2);
1038
1159
  server2.addTool = (tool) => {
1039
1160
  const original = tool.execute;
@@ -1074,8 +1195,21 @@ ${content}`;
1074
1195
  content: z.string().describe("Full markdown content for the note")
1075
1196
  }),
1076
1197
  execute: async ({ path, content }) => {
1077
- if (!isPathWritable(path, writeFolders)) return denyWrite(path);
1078
- const ok = await vault2.writeNote(path, content);
1198
+ const allow = allowedActions(path, writeFolders);
1199
+ const canCreate = allow.has("create");
1200
+ const canUpdate = allow.has("update");
1201
+ if (!canCreate && !canUpdate) return checkWrite(path, "create", writeFolders);
1202
+ const mode = canCreate && canUpdate ? "upsert" : canCreate ? "create" : "update";
1203
+ let ok;
1204
+ try {
1205
+ ok = await vault2.writeNote(path, content, { mode });
1206
+ } catch (err) {
1207
+ if (err instanceof NoteExistsError) {
1208
+ return `${checkWrite(path, "update", writeFolders)} The note already exists; choose a new path.`;
1209
+ }
1210
+ if (err instanceof NoteNotFoundError) return checkWrite(path, "create", writeFolders);
1211
+ throw err;
1212
+ }
1079
1213
  if (!ok) {
1080
1214
  return `Failed to write note: ${path}`;
1081
1215
  }
@@ -1245,7 +1379,8 @@ ${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;
1245
1379
  old_text: z.string().optional().describe("Required for replace operation. Exact text to find and replace. Must match exactly once.")
1246
1380
  }),
1247
1381
  execute: async ({ path, content: newContent, operation, old_text }) => {
1248
- if (!isPathWritable(path, writeFolders)) return denyWrite(path);
1382
+ const denied = checkWrite(path, "update", writeFolders);
1383
+ if (denied) return denied;
1249
1384
  const existing = await vault2.readNote(path);
1250
1385
  if (existing === null) {
1251
1386
  return `Note not found: ${path}`;
@@ -1275,7 +1410,13 @@ ${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;
1275
1410
  } else {
1276
1411
  updated = existing.endsWith("\n") ? existing + newContent : existing + "\n" + newContent;
1277
1412
  }
1278
- const ok = await vault2.writeNote(path, updated);
1413
+ let ok;
1414
+ try {
1415
+ ok = await vault2.writeNote(path, updated, { mode: "update" });
1416
+ } catch (err) {
1417
+ if (err instanceof NoteNotFoundError) return `Note not found: ${path}`;
1418
+ throw err;
1419
+ }
1279
1420
  if (!ok) {
1280
1421
  return `Failed to edit note: ${path}`;
1281
1422
  }
@@ -1292,7 +1433,8 @@ ${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;
1292
1433
  path: z.string().describe("Vault-relative path to the note to delete")
1293
1434
  }),
1294
1435
  execute: async ({ path }) => {
1295
- if (!isPathWritable(path, writeFolders)) return denyWrite(path);
1436
+ const denied = checkWrite(path, "delete", writeFolders);
1437
+ if (denied) return denied;
1296
1438
  const existing = await vault2.readNote(path);
1297
1439
  if (existing === null) return `Note not found: ${path}`;
1298
1440
  const ok = await vault2.deleteNote(path);
@@ -1302,16 +1444,22 @@ ${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;
1302
1444
  });
1303
1445
  if (!readOnly) server2.addTool({
1304
1446
  name: "move_note",
1305
- description: "Move or rename a note. Use this to rename a note within the same folder, move it to a different folder, or both at once. Creates destination folders automatically." + writeScopeNote,
1447
+ description: "Move or rename a note. Use this to rename a note within the same folder, move it to a different folder, or both at once. Creates destination folders automatically. Never replaces an existing note at the destination." + writeScopeNote,
1306
1448
  parameters: z.object({
1307
1449
  from: z.string().describe("Current path, e.g. 'daily/old-name.md'"),
1308
1450
  to: z.string().describe("New path, e.g. 'projects/new-name.md'")
1309
1451
  }),
1310
1452
  execute: async ({ from, to }) => {
1311
- if (!isPathWritable(from, writeFolders)) return denyWrite(from);
1312
- if (!isPathWritable(to, writeFolders)) return denyWrite(to);
1453
+ const denied = checkWrite(from, "delete", writeFolders) ?? checkWrite(to, "create", writeFolders);
1454
+ if (denied) return denied;
1313
1455
  const content = await vault2.readNote(from);
1314
- const ok = await vault2.moveNote(from, to);
1456
+ let ok;
1457
+ try {
1458
+ ok = await vault2.moveNote(from, to);
1459
+ } catch (err) {
1460
+ if (err instanceof NoteExistsError) return `A note already exists at ${to}. Choose another path.`;
1461
+ throw err;
1462
+ }
1315
1463
  if (!ok) {
1316
1464
  return `Failed to move: ${from} \u2192 ${to}`;
1317
1465
  }
@@ -1340,6 +1488,10 @@ ${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;
1340
1488
  `Created: ${new Date(meta.ctime).toISOString()}`,
1341
1489
  `Modified: ${new Date(meta.mtime).toISOString()}`
1342
1490
  ];
1491
+ if (meta.frontmatterError) {
1492
+ lines.push(`
1493
+ Frontmatter: not read, it isn't valid YAML (${meta.frontmatterError})`);
1494
+ }
1343
1495
  if (Object.keys(meta.frontmatter).length > 0) {
1344
1496
  lines.push(`
1345
1497
  Frontmatter:`);
@@ -1536,7 +1688,7 @@ function registerAttachmentTools(server2, opts) {
1536
1688
  const { vault: vault2, searchIndex: searchIndex2, vaultName, readOnly, writeFolders, allowedExtensions, maxBytes, base64MaxBytes, registry } = opts;
1537
1689
  const baseUrl = opts.baseUrl.replace(/\/+$/, "");
1538
1690
  const extList = [...allowedExtensions].sort().join(", ");
1539
- const writeScopeNote = writeFolders ? ` Writes are only allowed inside: ${writeFolders.map((f) => f + "/").join(", ")}.` : "";
1691
+ const writeScopeNote = describeWriteScope(writeFolders);
1540
1692
  const embedNote = " Add it to a note with an embed such as ![[path]] (edit_note).";
1541
1693
  const checkPath = (path) => {
1542
1694
  try {
@@ -1546,7 +1698,9 @@ function registerAttachmentTools(server2, opts) {
1546
1698
  return err.message;
1547
1699
  }
1548
1700
  };
1549
- const checkWritable = (path) => checkPath(path) ?? (isPathWritable(path, writeFolders) ? null : `Write access denied: '${path}' is outside the writable folders (${writeFolders.map((f) => f + "/").join(", ")}).`);
1701
+ const checkWritable = (path, ...actions) => checkPath(path) ?? actions.map((a) => checkWrite(path, a, writeFolders)).find((m) => m !== null) ?? null;
1702
+ const writeActions = (overwrite) => overwrite ? ["create", "update"] : ["create"];
1703
+ const exists = (path) => `Attachment already exists: ${path}. ` + (allowedActions(path, writeFolders).has("update") ? "Pass overwrite=true to replace it, or choose another path." : "Choose another path.");
1550
1704
  server2.addTool({
1551
1705
  name: "get_attachment_metadata",
1552
1706
  description: `Get size and timestamps of an attachment (${extList}) and the notes that embed or link it.`,
@@ -1632,14 +1786,12 @@ Embedded or linked in: ${backlinks.join(", ")}`);
1632
1786
  overwrite: z2.boolean().optional().describe("Replace an existing file at path. Default false.")
1633
1787
  }),
1634
1788
  execute: async ({ path, size, overwrite }) => {
1635
- const denied = checkWritable(path);
1789
+ const denied = checkWritable(path, ...writeActions(overwrite));
1636
1790
  if (denied) return denied;
1637
1791
  if (size !== void 0 && size > maxBytes) {
1638
1792
  return `File is ${formatBytes(size)}, over the upload limit of ${formatBytes(maxBytes)}.`;
1639
1793
  }
1640
- if (!overwrite && await vault2.getAttachmentInfo(path)) {
1641
- return `Attachment already exists: ${path}. Pass overwrite=true to replace it, or choose another path.`;
1642
- }
1794
+ if (!overwrite && await vault2.getAttachmentInfo(path)) return exists(path);
1643
1795
  let handle;
1644
1796
  try {
1645
1797
  handle = registry.create({ path, overwrite: !!overwrite, expectedSize: size, maxBytes });
@@ -1668,7 +1820,7 @@ Embedded or linked in: ${backlinks.join(", ")}`);
1668
1820
  overwrite: z2.boolean().optional().describe("Replace an existing file at path. Default false.")
1669
1821
  }),
1670
1822
  execute: async ({ path, content_base64, overwrite }) => {
1671
- const denied = checkWritable(path);
1823
+ const denied = checkWritable(path, ...writeActions(overwrite));
1672
1824
  if (denied) return denied;
1673
1825
  let data;
1674
1826
  try {
@@ -1684,9 +1836,7 @@ Embedded or linked in: ${backlinks.join(", ")}`);
1684
1836
  try {
1685
1837
  ok = await vault2.writeAttachment(path, data, { overwrite: !!overwrite });
1686
1838
  } catch (err) {
1687
- if (err instanceof AttachmentExistsError) {
1688
- return `Attachment already exists: ${path}. Pass overwrite=true to replace it, or choose another path.`;
1689
- }
1839
+ if (err instanceof AttachmentExistsError) return exists(path);
1690
1840
  throw err;
1691
1841
  }
1692
1842
  if (!ok) return `Failed to write attachment: ${path}`;
@@ -1703,7 +1853,7 @@ Embed: ![[${path}]]
1703
1853
  path: z2.string().describe("Vault-relative attachment path to delete")
1704
1854
  }),
1705
1855
  execute: async ({ path }) => {
1706
- const denied = checkWritable(path);
1856
+ const denied = checkWritable(path, "delete");
1707
1857
  if (denied) return denied;
1708
1858
  if (!await vault2.getAttachmentInfo(path)) return `Attachment not found: ${path}`;
1709
1859
  const ok = await vault2.deleteAttachment(path);
@@ -1723,7 +1873,7 @@ These notes still embed or link it: ${backlinks.join(", ")}` : `Deleted: ${path}
1723
1873
  overwrite: z2.boolean().optional().describe("Replace an existing file at the destination. Default false.")
1724
1874
  }),
1725
1875
  execute: async ({ from, to, overwrite }) => {
1726
- const denied = checkWritable(from) ?? checkWritable(to);
1876
+ const denied = checkWritable(from, "delete") ?? checkWritable(to, ...writeActions(overwrite));
1727
1877
  if (denied) return denied;
1728
1878
  const source = await vault2.getAttachmentInfo(from);
1729
1879
  if (!source) return `Attachment not found: ${from}`;
@@ -1731,9 +1881,7 @@ These notes still embed or link it: ${backlinks.join(", ")}` : `Deleted: ${path}
1731
1881
  try {
1732
1882
  ok = await vault2.moveAttachment(from, to, { overwrite: !!overwrite, maxBytes });
1733
1883
  } catch (err) {
1734
- if (err instanceof AttachmentExistsError) {
1735
- return `Attachment already exists: ${to}. Pass overwrite=true to replace it.`;
1736
- }
1884
+ if (err instanceof AttachmentExistsError) return exists(to);
1737
1885
  if (err instanceof AttachmentTooLargeError) {
1738
1886
  const size = Number.isFinite(err.size) ? `${formatBytes(err.size)}, over` : "of unknown size, so it may be over";
1739
1887
  return `Attachment is ${size} the ${formatBytes(maxBytes)} limit for moving it here. Move it in Obsidian instead.`;
@@ -1785,6 +1933,39 @@ function describeLogMessage(message, verbose = false) {
1785
1933
  return redactCredentials(inspect(message));
1786
1934
  }
1787
1935
 
1936
+ // src/http-charset.ts
1937
+ import { ServerResponse } from "http";
1938
+ var NEEDS_CHARSET = /^\s*(?:application\/json|text\/event-stream)\s*(?:;|$)/i;
1939
+ function withUtf8(type) {
1940
+ return NEEDS_CHARSET.test(type) && !/;\s*charset=/i.test(type) ? `${type}; charset=utf-8` : type;
1941
+ }
1942
+ var INSTALLED = /* @__PURE__ */ Symbol.for("obsidian-sync-mcp.utf8-charset");
1943
+ function declareUtf8Charset() {
1944
+ const proto = ServerResponse.prototype;
1945
+ if (proto[INSTALLED]) return;
1946
+ proto[INSTALLED] = true;
1947
+ const writeHead = proto.writeHead;
1948
+ proto.writeHead = function(...args) {
1949
+ const set = this.getHeader("content-type");
1950
+ if (typeof set === "string") this.setHeader("content-type", withUtf8(set));
1951
+ const at = typeof args[1] === "string" ? 2 : 1;
1952
+ args[at] = withUtf8Headers(args[at]);
1953
+ return writeHead.apply(this, args);
1954
+ };
1955
+ }
1956
+ function withUtf8Headers(headers) {
1957
+ const isContentType = (name) => typeof name === "string" && name.toLowerCase() === "content-type";
1958
+ if (Array.isArray(headers)) {
1959
+ return headers.map((value, i) => i % 2 === 1 && isContentType(headers[i - 1]) && typeof value === "string" ? withUtf8(value) : value);
1960
+ }
1961
+ if (headers && typeof headers === "object") {
1962
+ return Object.fromEntries(
1963
+ Object.entries(headers).map(([name, value]) => [name, isContentType(name) && typeof value === "string" ? withUtf8(value) : value])
1964
+ );
1965
+ }
1966
+ return headers;
1967
+ }
1968
+
1788
1969
  // src/main.ts
1789
1970
  var debugLogging2 = process.env.LOG_LEVEL === "debug";
1790
1971
  setGlobalLogFunction((message, level = LEVEL_INFO) => {
@@ -1810,7 +1991,14 @@ var PORT = parseInt(process.env.PORT ?? "8787");
1810
1991
  var BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;
1811
1992
  var AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;
1812
1993
  var READ_ONLY = process.env.READ_ONLY === "true";
1813
- var WRITE_FOLDERS = parseWriteFolders(process.env.WRITE_FOLDERS);
1994
+ var WRITE_FOLDERS;
1995
+ try {
1996
+ WRITE_FOLDERS = parseWriteFolders(process.env.WRITE_FOLDERS);
1997
+ } catch (err) {
1998
+ console.error(err.message);
1999
+ process.exit(1);
2000
+ }
2001
+ for (const warning of writeScopeWarnings(WRITE_FOLDERS)) console.warn(warning);
1814
2002
  var ATTACHMENTS_ENABLED = process.env.ATTACHMENTS_ENABLED === "true";
1815
2003
  function parsePositiveInt(name, fallback) {
1816
2004
  const raw = process.env[name];
@@ -1855,15 +2043,15 @@ if (MCP_INSTRUCTIONS_FILE) {
1855
2043
  }
1856
2044
  var vault;
1857
2045
  if (VAULT_PATH) {
1858
- const { LocalVault } = await import("./vault-local-MF65KDVB.js");
1859
- vault = new LocalVault(VAULT_PATH);
2046
+ const { LocalVault } = await import("./vault-local-VOGFWQI2.js");
2047
+ vault = new LocalVault(VAULT_PATH, { refuseSymlinkWrites: WRITE_FOLDERS !== null });
1860
2048
  console.log(`Local mode: ${VAULT_PATH}`);
1861
2049
  } else if (COUCHDB_URL) {
1862
2050
  if (!COUCHDB_PASSWORD) {
1863
2051
  console.error("COUCHDB_PASSWORD is required in remote mode.");
1864
2052
  process.exit(1);
1865
2053
  }
1866
- const { Vault } = await import("./vault-AV7JZZT2.js");
2054
+ const { Vault } = await import("./vault-MLW7WLXO.js");
1867
2055
  let pathNormalization;
1868
2056
  try {
1869
2057
  pathNormalization = parsePathNormalization(COUCHDB_PATH_NORMALIZATION);
@@ -1896,7 +2084,7 @@ try {
1896
2084
  console.log("Vault ready.");
1897
2085
  if (READ_ONLY) vault = readOnlyVault(vault);
1898
2086
  var baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? "/tmp", ".obsidian-mcp");
1899
- var vaultId = createHash2("sha256").update(VAULT_NAME).digest("hex").slice(0, 12);
2087
+ var vaultId = createHash3("sha256").update(VAULT_NAME).digest("hex").slice(0, 12);
1900
2088
  var dataDir = join(baseDataDir, vaultId);
1901
2089
  var indexPath = join(dataDir, "search-index.json");
1902
2090
  var searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);
@@ -2081,7 +2269,7 @@ var ATTACHMENT_INSTRUCTIONS = ATTACHMENTS_ENABLED ? " Images, PDFs, audio and vi
2081
2269
  var BASE_INSTRUCTIONS = "Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes." + ATTACHMENT_INSTRUCTIONS + " Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.";
2082
2270
  var serverOptions = {
2083
2271
  name: "obsidian-sync-mcp",
2084
- version: "0.12.1",
2272
+ version: "0.13.0",
2085
2273
  instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
2086
2274
 
2087
2275
  ${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
@@ -2175,11 +2363,12 @@ setInterval(async () => {
2175
2363
  await auth.saveTokens();
2176
2364
  }
2177
2365
  }, 5 * 60 * 1e3).unref();
2366
+ declareUtf8Charset();
2178
2367
  server.start({
2179
2368
  transportType: "httpStream",
2180
2369
  httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
2181
2370
  });
2182
- console.log(`obsidian-sync-mcp v${"0.12.1"} listening on port ${PORT}`);
2371
+ console.log(`obsidian-sync-mcp v${"0.13.0"} listening on port ${PORT}`);
2183
2372
  process.on("unhandledRejection", (err) => {
2184
2373
  console.error(`Unhandled rejection: ${describeError(err, debugLogging2)}`);
2185
2374
  });