obsidian-sync-mcp 0.10.0 → 0.12.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
@@ -3,12 +3,20 @@
3
3
  if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
4
4
  import {
5
5
  applyIndexChange,
6
+ parsePathNormalization,
6
7
  pruneGhosts
7
- } from "./chunk-GSVMRHWP.js";
8
+ } from "./chunk-AK3JXN67.js";
8
9
  import {
10
+ AttachmentExistsError,
11
+ AttachmentMoveIncompleteError,
12
+ AttachmentTooLargeError,
13
+ attachmentExtension,
14
+ isValidAttachmentPath,
9
15
  isValidNotePath,
10
- parseFrontmatterAndLinks
11
- } from "./chunk-VR63UUCB.js";
16
+ parseAttachmentExtensions,
17
+ parseFrontmatterAndLinks,
18
+ validateAttachmentPath
19
+ } from "./chunk-XZ4HUASL.js";
12
20
 
13
21
  // src/main.ts
14
22
  import { FastMCP } from "fastmcp";
@@ -458,6 +466,8 @@ var SearchIndex = class {
458
466
  content = /* @__PURE__ */ new Map();
459
467
  /** Frontmatter `title:` per path, when present — searched together with the path. */
460
468
  titles = /* @__PURE__ */ new Map();
469
+ /** Binary attachments (path -> size and mtime). Metadata only: their bytes are never read for the index. */
470
+ attachments = /* @__PURE__ */ new Map();
461
471
  saving = false;
462
472
  _since = "";
463
473
  /** When `since` last advanced from a completed catch-up or a watcher change (ms), null before the first. */
@@ -493,8 +503,12 @@ var SearchIndex = class {
493
503
  this.backlinks.get(key).add(path);
494
504
  }
495
505
  }
506
+ for (const [path, v] of Object.entries(data.attachments ?? {})) {
507
+ const [size, mtime] = v;
508
+ this.attachments.set(path, { size, mtime });
509
+ }
496
510
  if (data.since) this._since = data.since;
497
- console.log(`Search metadata loaded from disk (${this.knownPaths.size} notes, since: ${this._since ? "yes" : "none"}).`);
511
+ console.log(`Search metadata loaded from disk (${this.knownPaths.size} notes, ${this.attachments.size} attachments, since: ${this._since ? "yes" : "none"}).`);
498
512
  return this.knownPaths.size > 0;
499
513
  } catch {
500
514
  return false;
@@ -510,6 +524,7 @@ var SearchIndex = class {
510
524
  mtimes: Object.fromEntries(this.mtimes),
511
525
  tags: Object.fromEntries(this.tags),
512
526
  links: Object.fromEntries(this.links),
527
+ attachments: Object.fromEntries([...this.attachments].map(([p, a]) => [p, [a.size, a.mtime]])),
513
528
  since: this._since
514
529
  });
515
530
  if (this.passphrase) {
@@ -517,7 +532,8 @@ var SearchIndex = class {
517
532
  }
518
533
  await writeFile2(this.persistPath, data, { encoding: "utf-8", mode: 384 });
519
534
  await chmod2(this.persistPath, 384);
520
- console.log(`Search index saved to disk (${this.knownPaths.size} notes${this.passphrase ? ", encrypted" : ""}).`);
535
+ const att = this.attachments.size > 0 ? `, ${this.attachments.size} attachments` : "";
536
+ console.log(`Search index saved to disk (${this.knownPaths.size} notes${att}${this.passphrase ? ", encrypted" : ""}).`);
521
537
  } catch (err) {
522
538
  console.error("Failed to save search index:", err);
523
539
  } finally {
@@ -687,10 +703,55 @@ var SearchIndex = class {
687
703
  }
688
704
  return [...counts.entries()].map(([tag, count]) => ({ tag, count })).sort((a, b) => b.count - a.count);
689
705
  }
706
+ /** Record or update an attachment's size and mtime. */
707
+ updateAttachment(path, size, mtime) {
708
+ this.attachments.set(path, { size, mtime });
709
+ }
710
+ removeAttachment(path) {
711
+ this.attachments.delete(path);
712
+ }
713
+ /** Replace every attachment entry (local mode's startup scan). */
714
+ replaceAttachments(entries) {
715
+ this.attachments.clear();
716
+ for (const e of entries) this.attachments.set(e.path, { size: e.size, mtime: e.mtime });
717
+ }
718
+ clearAttachments() {
719
+ this.attachments.clear();
720
+ }
721
+ get attachmentCount() {
722
+ return this.attachments.size;
723
+ }
724
+ /** Indexed attachments, optionally under a folder, sorted by path. */
725
+ listAttachments(folder) {
726
+ const prefix = folder && !folder.endsWith("/") ? folder + "/" : folder;
727
+ return [...this.attachments].filter(([p]) => !prefix || p.startsWith(prefix)).map(([path, a]) => ({ path, size: a.size, mtime: a.mtime })).sort((a, b) => a.path.localeCompare(b.path));
728
+ }
729
+ /**
730
+ * Notes that embed or link each attachment, keyed by lowercased file name.
731
+ * Matched by name rather than full path because Obsidian resolves
732
+ * `![[shot.png]]` by name and relative markdown links vary; an ambiguous
733
+ * name therefore errs towards "referenced", the safe side when the answer
734
+ * decides what to clean up. Build once and look up many.
735
+ */
736
+ attachmentReferenceMap() {
737
+ const byName = /* @__PURE__ */ new Map();
738
+ for (const [target, sources] of this.backlinks) {
739
+ const name = target.slice(target.lastIndexOf("/") + 1);
740
+ if (!byName.has(name)) byName.set(name, /* @__PURE__ */ new Set());
741
+ for (const s of sources) byName.get(name).add(s);
742
+ }
743
+ return byName;
744
+ }
745
+ /** Notes that embed or link the attachment at `path` (see attachmentReferenceMap). */
746
+ getAttachmentReferences(path, refs = this.attachmentReferenceMap()) {
747
+ const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
748
+ return [...refs.get(name) ?? []].sort();
749
+ }
690
750
  /** Clear all index data (for full rebuild after DB nuke). */
691
751
  clear() {
692
752
  const paths = Array.from(this.knownPaths);
693
753
  for (const p of paths) this.remove(p);
754
+ this.attachments.clear();
694
755
  this._since = "";
695
756
  this._state = "building";
696
757
  }
@@ -764,11 +825,16 @@ function readOnlyVault(inner) {
764
825
  getMetadata: (path) => inner.getMetadata(path),
765
826
  listNotes: (folder) => inner.listNotes(folder),
766
827
  listNotesWithMtime: (folder) => inner.listNotesWithMtime(folder),
828
+ getAttachmentInfo: (path) => inner.getAttachmentInfo(path),
829
+ listAttachments: inner.listAttachments?.bind(inner),
767
830
  watchChanges: inner.watchChanges?.bind(inner),
768
831
  catchUp: inner.catchUp?.bind(inner),
769
832
  writeNote: deny,
770
833
  deleteNote: deny,
771
- moveNote: deny
834
+ moveNote: deny,
835
+ writeAttachment: deny,
836
+ deleteAttachment: deny,
837
+ moveAttachment: deny
772
838
  };
773
839
  }
774
840
 
@@ -1301,6 +1367,396 @@ Backlinks: ${backlinks.join(", ")}`);
1301
1367
  });
1302
1368
  }
1303
1369
 
1370
+ // src/attachment-tools.ts
1371
+ import { z as z2 } from "zod";
1372
+
1373
+ // src/uploads.ts
1374
+ import { randomBytes as randomBytes3 } from "crypto";
1375
+ var UPLOAD_ROUTE_PREFIX = "/attachments/upload/";
1376
+ var UploadRegistry = class {
1377
+ handles = /* @__PURE__ */ new Map();
1378
+ /** Handles taken whose body is still being read or written; see take and release. */
1379
+ inFlight = 0;
1380
+ ttlMs;
1381
+ maxPending;
1382
+ now;
1383
+ constructor(opts = {}) {
1384
+ this.ttlMs = opts.ttlMs ?? 10 * 60 * 1e3;
1385
+ this.maxPending = opts.maxPending ?? 100;
1386
+ this.now = opts.now ?? Date.now;
1387
+ }
1388
+ get pending() {
1389
+ this.prune();
1390
+ return this.handles.size;
1391
+ }
1392
+ create(spec) {
1393
+ this.prune();
1394
+ if (this.handles.size + this.inFlight >= this.maxPending) {
1395
+ throw new Error(`Too many pending uploads (${this.maxPending}). Use or let expire the existing upload URLs first.`);
1396
+ }
1397
+ const handle = {
1398
+ ...spec,
1399
+ token: randomBytes3(32).toString("base64url"),
1400
+ expiresAt: this.now() + this.ttlMs
1401
+ };
1402
+ this.handles.set(handle.token, handle);
1403
+ return handle;
1404
+ }
1405
+ /** Return the handle without using it up, or null when unknown or expired. */
1406
+ peek(token) {
1407
+ const handle = this.handles.get(token);
1408
+ return handle && handle.expiresAt > this.now() ? handle : null;
1409
+ }
1410
+ /**
1411
+ * Remove and return the handle (single use), or null when unknown or
1412
+ * expired. A returned handle stays counted against the cap until release().
1413
+ */
1414
+ take(token) {
1415
+ const handle = this.handles.get(token);
1416
+ if (!handle) return null;
1417
+ this.handles.delete(token);
1418
+ if (handle.expiresAt <= this.now()) return null;
1419
+ this.inFlight++;
1420
+ return handle;
1421
+ }
1422
+ /** Free the slot of a handle returned by take, once its upload has finished. */
1423
+ release() {
1424
+ if (this.inFlight > 0) this.inFlight--;
1425
+ }
1426
+ prune() {
1427
+ const now = this.now();
1428
+ for (const [token, handle] of this.handles) {
1429
+ if (handle.expiresAt <= now) this.handles.delete(token);
1430
+ }
1431
+ }
1432
+ };
1433
+ var BodyTooLargeError = class extends Error {
1434
+ constructor(limit) {
1435
+ super(`Upload exceeds the limit of ${limit} bytes`);
1436
+ }
1437
+ };
1438
+ async function readBodyLimited(body, limit) {
1439
+ if (!body) return new Uint8Array(0);
1440
+ const reader = body.getReader();
1441
+ const parts = [];
1442
+ let total = 0;
1443
+ try {
1444
+ for (; ; ) {
1445
+ const { done, value } = await reader.read();
1446
+ if (done) break;
1447
+ total += value.byteLength;
1448
+ if (total > limit) {
1449
+ await reader.cancel().catch(() => {
1450
+ });
1451
+ throw new BodyTooLargeError(limit);
1452
+ }
1453
+ parts.push(value);
1454
+ }
1455
+ } finally {
1456
+ reader.releaseLock();
1457
+ }
1458
+ const out = new Uint8Array(total);
1459
+ let offset = 0;
1460
+ for (const part of parts) {
1461
+ out.set(part, offset);
1462
+ offset += part.byteLength;
1463
+ }
1464
+ return out;
1465
+ }
1466
+ function mountAttachmentUpload(app, { registry, vault: vault2, onWritten, onError }) {
1467
+ const handler = async (c) => {
1468
+ const token = c.req.param("token") ?? "";
1469
+ const unknown = () => c.json({ error: "Unknown, used or expired upload URL. Call create_attachment_upload again." }, 404);
1470
+ const peeked = registry.peek(token);
1471
+ if (!peeked) return unknown();
1472
+ const declared = Number(c.req.header("content-length"));
1473
+ if (Number.isFinite(declared) && declared > peeked.maxBytes) {
1474
+ return c.json({ error: `Upload exceeds the limit of ${peeked.maxBytes} bytes` }, 413);
1475
+ }
1476
+ const handle = registry.take(token);
1477
+ if (!handle) return unknown();
1478
+ try {
1479
+ let data;
1480
+ try {
1481
+ data = await readBodyLimited(c.req.raw.body, handle.maxBytes);
1482
+ } catch (err) {
1483
+ if (err instanceof BodyTooLargeError) return c.json({ error: err.message }, 413);
1484
+ return c.json({ error: "Failed to read the upload body" }, 400);
1485
+ }
1486
+ if (data.byteLength === 0) {
1487
+ return c.json({ error: "Empty upload body. Send the raw file bytes, e.g. curl --data-binary @file" }, 400);
1488
+ }
1489
+ if (handle.expectedSize !== void 0 && data.byteLength !== handle.expectedSize) {
1490
+ return c.json({ error: `Upload is ${data.byteLength} bytes but ${handle.expectedSize} were declared` }, 400);
1491
+ }
1492
+ try {
1493
+ const ok = await vault2.writeAttachment(handle.path, data, { overwrite: handle.overwrite });
1494
+ if (!ok) return c.json({ error: `Failed to write attachment: ${handle.path}` }, 500);
1495
+ } catch (err) {
1496
+ if (err instanceof AttachmentExistsError) {
1497
+ return c.json({ error: `Attachment already exists: ${handle.path}` }, 409);
1498
+ }
1499
+ onError?.(handle.path, err);
1500
+ return c.json({ error: `Failed to write attachment: ${handle.path}` }, 500);
1501
+ }
1502
+ onWritten?.(handle.path, data.byteLength);
1503
+ return c.json({ path: handle.path, size: data.byteLength, embed: `![[${handle.path}]]` }, 201);
1504
+ } finally {
1505
+ registry.release();
1506
+ }
1507
+ };
1508
+ app.put(`${UPLOAD_ROUTE_PREFIX}:token`, handler);
1509
+ }
1510
+
1511
+ // src/attachment-tools.ts
1512
+ var LIST_ATTACHMENTS_DEFAULT_LIMIT = 100;
1513
+ var ATTACHMENT_WRITE_TOOLS = ["create_attachment_upload", "write_attachment", "delete_attachment", "move_attachment"];
1514
+ function estimateBase64Tokens(bytes) {
1515
+ return Math.ceil(Math.ceil(bytes / 3) * 4 / 3.3);
1516
+ }
1517
+ function formatTokens(n) {
1518
+ return n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n);
1519
+ }
1520
+ function formatBytes(n) {
1521
+ if (n < 1024) return `${n} B`;
1522
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 10 * 1024 ? 1 : 0)} KB`;
1523
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
1524
+ }
1525
+ function decodeBase64Strict(input) {
1526
+ let s = input.trim();
1527
+ const dataUrl = s.match(/^data:[^,]*;base64,/i);
1528
+ if (dataUrl) s = s.slice(dataUrl[0].length);
1529
+ s = s.replace(/\s+/g, "");
1530
+ if (s.length % 4 === 1 || !/^[A-Za-z0-9+/_-]*={0,2}$/.test(s)) {
1531
+ throw new Error("content_base64 is not valid base64");
1532
+ }
1533
+ return new Uint8Array(Buffer.from(s, "base64"));
1534
+ }
1535
+ function registerAttachmentTools(server2, opts) {
1536
+ const { vault: vault2, searchIndex: searchIndex2, vaultName, readOnly, writeFolders, allowedExtensions, maxBytes, base64MaxBytes, registry } = opts;
1537
+ const baseUrl = opts.baseUrl.replace(/\/+$/, "");
1538
+ const extList = [...allowedExtensions].sort().join(", ");
1539
+ const writeScopeNote = writeFolders ? ` Writes are only allowed inside: ${writeFolders.map((f) => f + "/").join(", ")}.` : "";
1540
+ const embedNote = " Add it to a note with an embed such as ![[path]] (edit_note).";
1541
+ const checkPath = (path) => {
1542
+ try {
1543
+ validateAttachmentPath(path, allowedExtensions);
1544
+ return null;
1545
+ } catch (err) {
1546
+ return err.message;
1547
+ }
1548
+ };
1549
+ const checkWritable = (path) => checkPath(path) ?? (isPathWritable(path, writeFolders) ? null : `Write access denied: '${path}' is outside the writable folders (${writeFolders.map((f) => f + "/").join(", ")}).`);
1550
+ server2.addTool({
1551
+ name: "get_attachment_metadata",
1552
+ description: `Get size and timestamps of an attachment (${extList}) and the notes that embed or link it.`,
1553
+ parameters: z2.object({
1554
+ path: z2.string().describe("Vault-relative attachment path, e.g. 'Attachments/screenshot.png'")
1555
+ }),
1556
+ execute: async ({ path }) => {
1557
+ const invalid = checkPath(path);
1558
+ if (invalid) return invalid;
1559
+ const info = await vault2.getAttachmentInfo(path);
1560
+ if (!info) return `Attachment not found: ${path}`;
1561
+ const lines = [
1562
+ `**${path}**`,
1563
+ `Size: ${info.size} bytes (${formatBytes(info.size)})`,
1564
+ `Created: ${new Date(info.ctime).toISOString()}`,
1565
+ `Modified: ${new Date(info.mtime).toISOString()}`,
1566
+ `Embed: ![[${path}]]`
1567
+ ];
1568
+ const backlinks = searchIndex2.getAttachmentReferences(path);
1569
+ if (backlinks.length > 0) lines.push(`
1570
+ Embedded or linked in: ${backlinks.join(", ")}`);
1571
+ lines.push(`
1572
+ [Open in Obsidian](${makeDeepLink(vaultName, path)})`);
1573
+ return lines.join("\n");
1574
+ }
1575
+ });
1576
+ server2.addTool({
1577
+ name: "list_attachments",
1578
+ description: `List attachments (${extList}) with size, modification time and how many notes embed or link each. Use it to see where the vault keeps attachments and how they are named before adding one, to find an existing file to embed, or with unreferenced=true to find files no note uses any more. Returns up to 100 by default.`,
1579
+ parameters: z2.object({
1580
+ folder: z2.string().optional().describe("Only attachments under this folder, e.g. 'Attachments'."),
1581
+ name: z2.string().optional().describe("Case-insensitive substring of the path, e.g. 'screenshot'."),
1582
+ extension: z2.string().optional().describe("Only this file type, e.g. 'png' or 'pdf'."),
1583
+ unreferenced: z2.boolean().optional().describe("Only attachments that no note embeds or links (by file name, so a name used anywhere counts as referenced)."),
1584
+ sort_by: z2.enum(["name", "modified", "size"]).optional().describe("'name' (default), 'modified' (newest first) or 'size' (largest first)."),
1585
+ limit: z2.coerce.number().int().positive().optional().describe(`Max entries, default ${LIST_ATTACHMENTS_DEFAULT_LIMIT}.`)
1586
+ }),
1587
+ execute: async ({ folder, name, extension, unreferenced, sort_by, limit }) => {
1588
+ const refs = searchIndex2.attachmentReferenceMap();
1589
+ let items = searchIndex2.listAttachments(folder).filter((a) => allowedExtensions.has(attachmentExtension(a.path))).map((a) => ({ ...a, refs: searchIndex2.getAttachmentReferences(a.path, refs) }));
1590
+ const total = items.length;
1591
+ const filters = [];
1592
+ if (name) {
1593
+ const lower = name.toLowerCase();
1594
+ items = items.filter((a) => a.path.toLowerCase().includes(lower));
1595
+ filters.push(`name="${name}"`);
1596
+ }
1597
+ if (extension) {
1598
+ const ext = extension.toLowerCase().replace(/^\./, "");
1599
+ items = items.filter((a) => attachmentExtension(a.path) === ext);
1600
+ filters.push(`extension="${ext}"`);
1601
+ }
1602
+ if (unreferenced) {
1603
+ items = items.filter((a) => a.refs.length === 0);
1604
+ filters.push("unreferenced");
1605
+ }
1606
+ if (sort_by === "modified") items.sort((a, b) => b.mtime - a.mtime);
1607
+ if (sort_by === "size") items.sort((a, b) => b.size - a.size);
1608
+ const scope = folder ? ` in ${folder.replace(/\/+$/, "")}/` : "";
1609
+ const building = searchIndex2.state === "ready" ? "" : " The index is still being built, so this list may be incomplete.";
1610
+ if (items.length === 0) {
1611
+ const why = filters.length ? ` match ${filters.join(", ")}` : "";
1612
+ return `No attachments${scope}${why}. ${total} attachments${scope} in the index.${building}`;
1613
+ }
1614
+ const cap = limit ?? LIST_ATTACHMENTS_DEFAULT_LIMIT;
1615
+ const shown = items.slice(0, cap);
1616
+ const header = `${items.length} attachment${items.length === 1 ? "" : "s"}${scope}` + (filters.length ? ` matching ${filters.join(", ")} (of ${total})` : "") + `, ${formatBytes(items.reduce((n, a) => n + a.size, 0))} in total` + (shown.length < items.length ? `, showing the first ${shown.length}` : "") + `.${building}`;
1617
+ const lines = shown.map((a) => {
1618
+ const date = a.mtime ? new Date(a.mtime).toISOString().slice(0, 16) : "";
1619
+ const used = a.refs.length === 0 ? "unreferenced" : a.refs.length === 1 ? `in ${a.refs[0]}` : `in ${a.refs.length} notes`;
1620
+ return `- ${date} ${formatBytes(a.size)} [${a.path}](${makeDeepLink(vaultName, a.path)}) \u2014 ${used}`;
1621
+ });
1622
+ return [header, ...lines].join("\n");
1623
+ }
1624
+ });
1625
+ if (readOnly) return;
1626
+ server2.addTool({
1627
+ name: "create_attachment_upload",
1628
+ description: `Preferred way to add an image, PDF, audio or video file (${extList}) to the vault, up to ${formatBytes(maxBytes)}. Returns a one-time URL; send the raw file bytes to it with HTTP PUT, e.g. \`curl -fsS -X PUT --data-binary @file.png '<url>'\` (no other auth needed). Use this whenever you can run a command or make an HTTP request (shell, code execution, a script): it takes milliseconds at any size, while write_attachment spends output tokens on every byte. The URL works once and expires after ${Math.round(registry.ttlMs / 6e4)} minutes.` + embedNote + writeScopeNote,
1629
+ parameters: z2.object({
1630
+ path: z2.string().describe("Vault-relative destination path, e.g. 'Attachments/screenshot.png'. The extension decides how Obsidian shows the file."),
1631
+ size: z2.coerce.number().int().positive().optional().describe("Exact file size in bytes, if known. The upload is rejected when it differs, which catches truncated uploads."),
1632
+ overwrite: z2.boolean().optional().describe("Replace an existing file at path. Default false.")
1633
+ }),
1634
+ execute: async ({ path, size, overwrite }) => {
1635
+ const denied = checkWritable(path);
1636
+ if (denied) return denied;
1637
+ if (size !== void 0 && size > maxBytes) {
1638
+ return `File is ${formatBytes(size)}, over the upload limit of ${formatBytes(maxBytes)}.`;
1639
+ }
1640
+ if (!overwrite && await vault2.getAttachmentInfo(path)) {
1641
+ return `Attachment already exists: ${path}. Pass overwrite=true to replace it, or choose another path.`;
1642
+ }
1643
+ let handle;
1644
+ try {
1645
+ handle = registry.create({ path, overwrite: !!overwrite, expectedSize: size, maxBytes });
1646
+ } catch (err) {
1647
+ return err.message;
1648
+ }
1649
+ const url = `${baseUrl}${UPLOAD_ROUTE_PREFIX}${handle.token}`;
1650
+ return [
1651
+ `Upload URL for ${path} (single use, expires ${new Date(handle.expiresAt).toISOString()}, max ${formatBytes(size ?? maxBytes)}):`,
1652
+ url,
1653
+ "",
1654
+ "Send the raw bytes with PUT, for example:",
1655
+ `curl -fsS -X PUT --data-binary @/path/to/local/file '${url}'`,
1656
+ "",
1657
+ `A 201 response with JSON {"path", "size", "embed"} means the file is saved. Then embed it in a note with: ![[${path}]]`
1658
+ ].join("\n");
1659
+ }
1660
+ });
1661
+ const base64MaxChars = Math.ceil(base64MaxBytes / 3) * 4 + 1024;
1662
+ server2.addTool({
1663
+ name: "write_attachment",
1664
+ description: `Fallback for clients that cannot make HTTP requests: save a tiny attachment (${extList}) from base64, up to ${formatBytes(base64MaxBytes)}. A file at that limit is about ${formatTokens(estimateBase64Tokens(base64MaxBytes))} output tokens, minutes of generation, and one wrong character corrupts it. If you can run curl or any HTTP client, or the file exists on a disk you can read, use create_attachment_upload instead.` + embedNote + writeScopeNote,
1665
+ parameters: z2.object({
1666
+ path: z2.string().describe("Vault-relative destination path, e.g. 'Attachments/diagram.png'"),
1667
+ content_base64: z2.string().max(base64MaxChars).describe("File content as base64 (a data: URL is accepted too)"),
1668
+ overwrite: z2.boolean().optional().describe("Replace an existing file at path. Default false.")
1669
+ }),
1670
+ execute: async ({ path, content_base64, overwrite }) => {
1671
+ const denied = checkWritable(path);
1672
+ if (denied) return denied;
1673
+ let data;
1674
+ try {
1675
+ data = decodeBase64Strict(content_base64);
1676
+ } catch (err) {
1677
+ return err.message;
1678
+ }
1679
+ if (data.byteLength === 0) return "content_base64 is empty.";
1680
+ if (data.byteLength > base64MaxBytes) {
1681
+ return `File is ${formatBytes(data.byteLength)}, over the inline limit of ${formatBytes(base64MaxBytes)}. Use create_attachment_upload instead.`;
1682
+ }
1683
+ let ok;
1684
+ try {
1685
+ ok = await vault2.writeAttachment(path, data, { overwrite: !!overwrite });
1686
+ } catch (err) {
1687
+ if (err instanceof AttachmentExistsError) {
1688
+ return `Attachment already exists: ${path}. Pass overwrite=true to replace it, or choose another path.`;
1689
+ }
1690
+ throw err;
1691
+ }
1692
+ if (!ok) return `Failed to write attachment: ${path}`;
1693
+ searchIndex2.updateAttachment(path, data.byteLength, Date.now());
1694
+ return `Attachment saved: ${path} (${formatBytes(data.byteLength)})
1695
+ Embed: ![[${path}]]
1696
+ [Open in Obsidian](${makeDeepLink(vaultName, path)})`;
1697
+ }
1698
+ });
1699
+ server2.addTool({
1700
+ name: "delete_attachment",
1701
+ description: "Delete an attachment from the vault. Notes that embed it are not changed." + writeScopeNote,
1702
+ parameters: z2.object({
1703
+ path: z2.string().describe("Vault-relative attachment path to delete")
1704
+ }),
1705
+ execute: async ({ path }) => {
1706
+ const denied = checkWritable(path);
1707
+ if (denied) return denied;
1708
+ if (!await vault2.getAttachmentInfo(path)) return `Attachment not found: ${path}`;
1709
+ const ok = await vault2.deleteAttachment(path);
1710
+ if (!ok) return `Failed to delete: ${path}`;
1711
+ searchIndex2.removeAttachment(path);
1712
+ const backlinks = searchIndex2.getAttachmentReferences(path);
1713
+ return backlinks.length > 0 ? `Deleted: ${path}
1714
+ These notes still embed or link it: ${backlinks.join(", ")}` : `Deleted: ${path}`;
1715
+ }
1716
+ });
1717
+ server2.addTool({
1718
+ name: "move_attachment",
1719
+ description: "Move or rename an attachment. Embeds in notes are not updated; edit them afterwards if needed." + writeScopeNote,
1720
+ parameters: z2.object({
1721
+ from: z2.string().describe("Current path, e.g. 'Attachments/old.png'"),
1722
+ to: z2.string().describe("New path, e.g. 'Attachments/2026/new.png'"),
1723
+ overwrite: z2.boolean().optional().describe("Replace an existing file at the destination. Default false.")
1724
+ }),
1725
+ execute: async ({ from, to, overwrite }) => {
1726
+ const denied = checkWritable(from) ?? checkWritable(to);
1727
+ if (denied) return denied;
1728
+ const source = await vault2.getAttachmentInfo(from);
1729
+ if (!source) return `Attachment not found: ${from}`;
1730
+ let ok;
1731
+ try {
1732
+ ok = await vault2.moveAttachment(from, to, { overwrite: !!overwrite, maxBytes });
1733
+ } catch (err) {
1734
+ if (err instanceof AttachmentExistsError) {
1735
+ return `Attachment already exists: ${to}. Pass overwrite=true to replace it.`;
1736
+ }
1737
+ if (err instanceof AttachmentTooLargeError) {
1738
+ const size = Number.isFinite(err.size) ? `${formatBytes(err.size)}, over` : "of unknown size, so it may be over";
1739
+ return `Attachment is ${size} the ${formatBytes(maxBytes)} limit for moving it here. Move it in Obsidian instead.`;
1740
+ }
1741
+ if (err instanceof AttachmentMoveIncompleteError) {
1742
+ searchIndex2.updateAttachment(to, source.size, Date.now());
1743
+ return `Copied ${from} to ${to}, but could not delete ${from}. Both exist now; delete it with delete_attachment if needed.`;
1744
+ }
1745
+ throw err;
1746
+ }
1747
+ if (!ok) return `Failed to move: ${from} \u2192 ${to}`;
1748
+ searchIndex2.removeAttachment(from);
1749
+ searchIndex2.updateAttachment(to, source.size, Date.now());
1750
+ const backlinks = searchIndex2.getAttachmentReferences(from);
1751
+ const note = backlinks.length > 0 ? `
1752
+ These notes still embed the old path: ${backlinks.join(", ")}` : "";
1753
+ return `Moved: ${from} \u2192 ${to}
1754
+ Embed: ![[${to}]]${note}
1755
+ [Open in Obsidian](${makeDeepLink(vaultName, to)})`;
1756
+ }
1757
+ });
1758
+ }
1759
+
1304
1760
  // src/redact.ts
1305
1761
  import { inspect } from "util";
1306
1762
  function redactCredentials(text) {
@@ -1348,12 +1804,34 @@ var COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || void 0;
1348
1804
  var COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === "true";
1349
1805
  var COUCHDB_ID_DERIVATION_KEY = process.env.COUCHDB_ID_DERIVATION_KEY || void 0;
1350
1806
  var COUCHDB_CASE_SENSITIVE = process.env.COUCHDB_CASE_SENSITIVE === "true";
1807
+ var COUCHDB_PATH_NORMALIZATION = process.env.COUCHDB_PATH_NORMALIZATION;
1351
1808
  var VAULT_NAME = process.env.VAULT_NAME ?? "MyVault";
1352
1809
  var PORT = parseInt(process.env.PORT ?? "8787");
1353
1810
  var BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;
1354
1811
  var AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;
1355
1812
  var READ_ONLY = process.env.READ_ONLY === "true";
1356
1813
  var WRITE_FOLDERS = parseWriteFolders(process.env.WRITE_FOLDERS);
1814
+ var ATTACHMENTS_ENABLED = process.env.ATTACHMENTS_ENABLED === "true";
1815
+ function parsePositiveInt(name, fallback) {
1816
+ const raw = process.env[name];
1817
+ if (raw === void 0 || raw.trim() === "") return fallback;
1818
+ const n = Number(raw);
1819
+ if (!Number.isInteger(n) || n <= 0) {
1820
+ console.error(`${name} must be a positive integer, got '${raw}'.`);
1821
+ process.exit(1);
1822
+ }
1823
+ return n;
1824
+ }
1825
+ var ATTACHMENT_MAX_BYTES = parsePositiveInt("ATTACHMENT_MAX_BYTES", 20 * 1024 * 1024);
1826
+ var ATTACHMENT_INLINE_MAX_BYTES = parsePositiveInt("ATTACHMENT_INLINE_MAX_BYTES", 32 * 1024);
1827
+ var ATTACHMENT_UPLOAD_TTL_SECONDS = parsePositiveInt("ATTACHMENT_UPLOAD_TTL_SECONDS", 600);
1828
+ var ATTACHMENT_EXTENSIONS;
1829
+ try {
1830
+ ATTACHMENT_EXTENSIONS = parseAttachmentExtensions(process.env.ATTACHMENT_EXTENSIONS);
1831
+ } catch (err) {
1832
+ console.error(err.message);
1833
+ process.exit(1);
1834
+ }
1357
1835
  var MCP_INSTRUCTIONS_FILE = process.env.MCP_INSTRUCTIONS_FILE?.trim() || void 0;
1358
1836
  var MCP_INSTRUCTIONS_ENV = process.env.MCP_INSTRUCTIONS?.trim() || void 0;
1359
1837
  var MCP_EXTRA_INSTRUCTIONS;
@@ -1377,7 +1855,7 @@ if (MCP_INSTRUCTIONS_FILE) {
1377
1855
  }
1378
1856
  var vault;
1379
1857
  if (VAULT_PATH) {
1380
- const { LocalVault } = await import("./vault-local-OURGENR5.js");
1858
+ const { LocalVault } = await import("./vault-local-MF65KDVB.js");
1381
1859
  vault = new LocalVault(VAULT_PATH);
1382
1860
  console.log(`Local mode: ${VAULT_PATH}`);
1383
1861
  } else if (COUCHDB_URL) {
@@ -1385,7 +1863,14 @@ if (VAULT_PATH) {
1385
1863
  console.error("COUCHDB_PASSWORD is required in remote mode.");
1386
1864
  process.exit(1);
1387
1865
  }
1388
- const { Vault } = await import("./vault-6H64Y46A.js");
1866
+ const { Vault } = await import("./vault-XZDTCOVA.js");
1867
+ let pathNormalization;
1868
+ try {
1869
+ pathNormalization = parsePathNormalization(COUCHDB_PATH_NORMALIZATION);
1870
+ } catch (err) {
1871
+ console.error(err.message);
1872
+ process.exit(1);
1873
+ }
1389
1874
  vault = new Vault({
1390
1875
  couchdbUrl: COUCHDB_URL,
1391
1876
  couchdbUser: COUCHDB_USER,
@@ -1394,7 +1879,8 @@ if (VAULT_PATH) {
1394
1879
  passphrase: COUCHDB_PASSPHRASE,
1395
1880
  obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,
1396
1881
  idDerivationKey: COUCHDB_ID_DERIVATION_KEY,
1397
- caseSensitive: COUCHDB_CASE_SENSITIVE
1882
+ caseSensitive: COUCHDB_CASE_SENSITIVE,
1883
+ pathNormalization
1398
1884
  });
1399
1885
  console.log(`Remote mode: ${redactCredentials(COUCHDB_URL)}`);
1400
1886
  } else {
@@ -1422,6 +1908,11 @@ if (searchIndex.size > 0 && searchIndex.contentCount < searchIndex.size) {
1422
1908
  console.log(`Persisted metadata for ${searchIndex.size} notes has no text; re-reading note bodies from the start so search_notes covers every note (metadata stays serveable meanwhile).`);
1423
1909
  searchIndex.since = "0";
1424
1910
  }
1911
+ if (!ATTACHMENTS_ENABLED) searchIndex.clearAttachments();
1912
+ var onAttachmentChange = ATTACHMENTS_ENABLED ? (path, info) => {
1913
+ if (info) searchIndex.updateAttachment(path, info.size, info.mtime);
1914
+ else searchIndex.removeAttachment(path);
1915
+ } : void 0;
1425
1916
  async function rebuildIndex() {
1426
1917
  const start = performance.now();
1427
1918
  if (COUCHDB_URL && vault.catchUp) {
@@ -1430,6 +1921,14 @@ async function rebuildIndex() {
1430
1921
  let changes = 0;
1431
1922
  const preexisting = new Set(searchIndex.listPaths());
1432
1923
  const seen = /* @__PURE__ */ new Set();
1924
+ const preexistingAttachments = new Set(searchIndex.listAttachments().map((a) => a.path));
1925
+ const seenAttachments = /* @__PURE__ */ new Set();
1926
+ const countingAttachment = onAttachmentChange ? (path, info) => {
1927
+ changes++;
1928
+ if (info) seenAttachments.add(path);
1929
+ else seenAttachments.delete(path);
1930
+ onAttachmentChange(path, info);
1931
+ } : void 0;
1433
1932
  let fromZero = since === "0";
1434
1933
  const onBatch = async (batchSince, processed) => {
1435
1934
  searchIndex.since = batchSince;
@@ -1444,19 +1943,23 @@ async function rebuildIndex() {
1444
1943
  applyIndexChange(searchIndex, path, content, mtime);
1445
1944
  };
1446
1945
  try {
1447
- const newSince = await vault.catchUp(since, countingCallback, onBatch);
1946
+ const newSince = await vault.catchUp(since, countingCallback, onBatch, void 0, countingAttachment);
1448
1947
  searchIndex.since = newSince;
1449
1948
  searchIndex.lastSyncAt = Date.now();
1450
1949
  } catch (err) {
1451
1950
  console.warn(`Catch-up failed (${describeError(err, debugLogging2)}), re-reading from the start...`);
1452
1951
  changes = 0;
1453
1952
  seen.clear();
1953
+ seenAttachments.clear();
1454
1954
  fromZero = true;
1455
- const newSince = await vault.catchUp("0", countingCallback, onBatch);
1955
+ const newSince = await vault.catchUp("0", countingCallback, onBatch, void 0, countingAttachment);
1456
1956
  searchIndex.since = newSince;
1457
1957
  searchIndex.lastSyncAt = Date.now();
1458
1958
  }
1459
- if (fromZero) pruneGhosts(searchIndex, preexisting, seen);
1959
+ if (fromZero) {
1960
+ pruneGhosts(searchIndex, preexisting, seen);
1961
+ if (countingAttachment) pruneGhosts({ remove: (p) => searchIndex.removeAttachment(p) }, preexistingAttachments, seenAttachments);
1962
+ }
1460
1963
  if (changes > 0) {
1461
1964
  console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1e3).toFixed(1)}s (${searchIndex.size} notes).`);
1462
1965
  } else {
@@ -1481,6 +1984,10 @@ async function rebuildIndex() {
1481
1984
  }
1482
1985
  console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1e3).toFixed(1)}s`);
1483
1986
  }
1987
+ if (ATTACHMENTS_ENABLED && vault.listAttachments) {
1988
+ searchIndex.replaceAttachments(await vault.listAttachments());
1989
+ console.log(`Attachment index built: ${searchIndex.attachmentCount} attachments.`);
1990
+ }
1484
1991
  }
1485
1992
  await searchIndex.saveToDisk();
1486
1993
  searchIndex.state = "ready";
@@ -1501,7 +2008,8 @@ async function syncBeforeSearch() {
1501
2008
  searchIndex.since || "0",
1502
2009
  (path, content, mtime) => applyIndexChange(searchIndex, path, content, mtime),
1503
2010
  void 0,
1504
- stats
2011
+ stats,
2012
+ onAttachmentChange
1505
2013
  );
1506
2014
  searchIndex.since = newSince;
1507
2015
  searchIndex.lastSyncAt = Date.now();
@@ -1519,8 +2027,15 @@ var fsWatcher = null;
1519
2027
  if (VAULT_PATH) {
1520
2028
  const pending = /* @__PURE__ */ new Map();
1521
2029
  fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {
1522
- if (!filename || !filename.endsWith(".md")) return;
1523
- const notePath = filename.replace(/\\/g, "/");
2030
+ if (!filename) return;
2031
+ const changedPath = filename.replace(/\\/g, "/");
2032
+ if (ATTACHMENTS_ENABLED && isValidAttachmentPath(changedPath)) {
2033
+ if (pending.has(changedPath)) clearTimeout(pending.get(changedPath));
2034
+ pending.set(changedPath, setTimeout(() => handleAttachmentChange(changedPath), 100));
2035
+ return;
2036
+ }
2037
+ if (!filename.endsWith(".md")) return;
2038
+ const notePath = changedPath;
1524
2039
  if (notePath.startsWith(".obsidian/") || notePath.includes("/.obsidian/")) return;
1525
2040
  if (pending.has(notePath)) clearTimeout(pending.get(notePath));
1526
2041
  pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));
@@ -1539,6 +2054,16 @@ if (VAULT_PATH) {
1539
2054
  searchIndex.remove(notePath);
1540
2055
  }
1541
2056
  }
2057
+ async function handleAttachmentChange(path) {
2058
+ pending.delete(path);
2059
+ try {
2060
+ const info = await vault.getAttachmentInfo(path);
2061
+ if (info) searchIndex.updateAttachment(path, info.size, info.mtime);
2062
+ else searchIndex.removeAttachment(path);
2063
+ } catch {
2064
+ searchIndex.removeAttachment(path);
2065
+ }
2066
+ }
1542
2067
  console.log("Watching vault for external changes.");
1543
2068
  }
1544
2069
  function startCouchDbWatcher() {
@@ -1549,13 +2074,14 @@ function startCouchDbWatcher() {
1549
2074
  searchIndex.since = String(seq);
1550
2075
  searchIndex.lastSyncAt = Date.now();
1551
2076
  }
1552
- });
2077
+ }, onAttachmentChange);
1553
2078
  console.log("Watching CouchDB for LiveSync changes.");
1554
2079
  }
1555
- var BASE_INSTRUCTIONS = "Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. 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.";
2080
+ var ATTACHMENT_INSTRUCTIONS = ATTACHMENTS_ENABLED ? " Images, PDFs, audio and video can be stored as attachments: whenever you can make an HTTP request, use create_attachment_upload and PUT the file to the returned URL; write_attachment (base64) is a slow fallback for tiny files only. Then embed the file in a note with ![[path]]." : "";
2081
+ 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.";
1556
2082
  var serverOptions = {
1557
2083
  name: "obsidian-sync-mcp",
1558
- version: "0.10.0",
2084
+ version: "0.12.0",
1559
2085
  instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
1560
2086
 
1561
2087
  ${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
@@ -1601,6 +2127,37 @@ if (AUTH_TOKEN) {
1601
2127
  await auth.loadTokens();
1602
2128
  }
1603
2129
  registerTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS, COUCHDB_URL ? syncBeforeSearch : void 0);
2130
+ if (ATTACHMENTS_ENABLED) {
2131
+ const uploadRegistry = new UploadRegistry({ ttlMs: ATTACHMENT_UPLOAD_TTL_SECONDS * 1e3 });
2132
+ registerAttachmentTools(server, {
2133
+ vault,
2134
+ searchIndex,
2135
+ vaultName: VAULT_NAME,
2136
+ readOnly: READ_ONLY,
2137
+ writeFolders: WRITE_FOLDERS,
2138
+ allowedExtensions: ATTACHMENT_EXTENSIONS,
2139
+ maxBytes: ATTACHMENT_MAX_BYTES,
2140
+ base64MaxBytes: ATTACHMENT_INLINE_MAX_BYTES,
2141
+ registry: uploadRegistry,
2142
+ baseUrl: BASE_URL
2143
+ });
2144
+ if (!READ_ONLY) {
2145
+ mountAttachmentUpload(server.getApp(), {
2146
+ registry: uploadRegistry,
2147
+ vault,
2148
+ onWritten: (path, size) => {
2149
+ searchIndex.updateAttachment(path, size, Date.now());
2150
+ if (debugLogging2) console.log(`[debug] attachment upload: ${path} (${size} bytes)`);
2151
+ },
2152
+ onError: (path, err) => {
2153
+ console.error(`Attachment upload failed${debugLogging2 ? ` (${path})` : ""}: ${describeError(err, debugLogging2)}`);
2154
+ }
2155
+ });
2156
+ }
2157
+ console.log(
2158
+ READ_ONLY ? "Attachments enabled (read-only: get_attachment_metadata only)." : `Attachments enabled: ${ATTACHMENT_WRITE_TOOLS.join(", ")}; uploads up to ${formatBytes(ATTACHMENT_MAX_BYTES)} via ${BASE_URL}/attachments/upload/<token>.`
2159
+ );
2160
+ }
1604
2161
  async function shutdown() {
1605
2162
  console.log("Shutting down...");
1606
2163
  if (fsWatcher) fsWatcher.close();
@@ -1622,7 +2179,7 @@ server.start({
1622
2179
  transportType: "httpStream",
1623
2180
  httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
1624
2181
  });
1625
- console.log(`obsidian-sync-mcp v${"0.10.0"} listening on port ${PORT}`);
2182
+ console.log(`obsidian-sync-mcp v${"0.12.0"} listening on port ${PORT}`);
1626
2183
  process.on("unhandledRejection", (err) => {
1627
2184
  console.error(`Unhandled rejection: ${describeError(err, debugLogging2)}`);
1628
2185
  });