obsidian-sync-mcp 0.7.3 → 0.8.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/README.md CHANGED
@@ -206,6 +206,7 @@ Set `BASE_URL` to the tunnel URL when using authentication.
206
206
  | `list_folders` | List all folders in the vault with note counts — use to discover folder names |
207
207
  | `list_tags` | List all tags in the vault with counts — use to discover tags before filtering |
208
208
  | `list_notes` | List notes with timestamps. Filter by folder, name, tag, or date. Sort by name or modified. |
209
+ | `search_notes` | Search note text for terms (OR, case-insensitive substrings); paths and frontmatter titles are searched first. Filter by folder, tag, or date. Returns paths with one context line each, never the note body, after a status line that states which CouchDB sequence the index is caught up with. |
209
210
  | `delete_note` | Delete a note |
210
211
  | `move_note` | Move or rename a note — works across folders, creates destination folders automatically |
211
212
  | `get_note_metadata` | Get frontmatter, tags, outgoing links, backlinks, size, and timestamps — navigate the knowledge graph |
@@ -257,6 +258,7 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
257
258
  | `MCP_ALLOWED_HOSTS` | Optional | — | Comma-separated extra `Host` values accepted in no-auth mode (e.g. `192.168.1.5,mybox.local`). No-auth mode rejects any other Host to block browser DNS-rebinding; localhost is always allowed. Ignored when `MCP_AUTH_TOKEN` is set. |
258
259
  | `DATA_DIR` | Optional | `~/.obsidian-mcp` | Directory for persisted data (metadata index, auth tokens) |
259
260
  | `LOG_LEVEL` | Optional | — | Set to `debug` for verbose logging (library logs, change feed, index sync) |
261
+ | `DISPLAY_TIMEZONE` | Optional | server's zone | IANA time zone for the human-readable half of the server time in `search_notes` status lines (UTC is always printed beside it), e.g. `Europe/Berlin`. An invalid zone falls back to UTC with a warning at startup |
260
262
  | `MCP_REFRESH_DAYS` | Optional | `14` | Days before auth session expires |
261
263
  | `READ_ONLY` | Optional | `false` | Set to `true` to disable all write tools (`write_note`, `edit_note`, `delete_note`, `move_note`). Only read tools are exposed via MCP, and the vault backend rejects writes as well. Useful when sharing the server with multiple AI clients and write access should be opt-in. This protects the vault from MCP clients; it is not a database-level guarantee. To make CouchDB itself refuse writes, use CouchDB-side controls, such as a `validate_doc_update` function that rejects the server's CouchDB user. |
262
264
  | `WRITE_FOLDERS` | Optional | — | Comma-separated list of vault-relative folders where writes are allowed (e.g. `MCP,Inbox`). When set, the whole vault stays readable but `write_note`, `edit_note`, `delete_note`, and `move_note` refuse paths outside these folders (`move_note` requires both source and destination to be writable). Enforced server-side, unlike `MCP_INSTRUCTIONS`. Matching is case-sensitive and folder-boundary-aware (`MCP` matches `MCP/note.md` but not `MCP-private/note.md`). Ignored when `READ_ONLY=true`; unset means the whole vault is writable. |
@@ -14,9 +14,20 @@ function applyIndexChange(index, path, content, mtime) {
14
14
  index.remove(path);
15
15
  }
16
16
  }
17
+ function pruneGhosts(index, preexisting, seen) {
18
+ const removed = [];
19
+ for (const p of preexisting) {
20
+ if (!seen.has(p)) {
21
+ index.remove(p);
22
+ removed.push(p);
23
+ }
24
+ }
25
+ return removed;
26
+ }
17
27
 
18
28
  export {
19
29
  deriveContent,
20
- applyIndexChange
30
+ applyIndexChange,
31
+ pruneGhosts
21
32
  };
22
- //# sourceMappingURL=chunk-SGLPTZJA.js.map
33
+ //# sourceMappingURL=chunk-GSVMRHWP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index-sync.ts"],"sourcesContent":["/**\n * Shared search-index sync helpers.\n *\n * Kept dependency-free (no livesync-commonlib imports) so the delete-vs-empty\n * routing is unit-testable in isolation.\n */\n\nexport interface IndexTarget {\n update(path: string, content: string, mtime?: number): void;\n remove(path: string): void;\n}\n\n/**\n * Derive index content from a LiveSync change doc.\n *\n * Returns `null` ONLY when the note is deleted. An existing note with no body\n * yields `\"\"` so a zero-byte note stays distinguishable from a deletion —\n * without this, a note that serializes with no `data` array would look deleted.\n */\nexport function deriveContent(doc: { deleted?: boolean; data?: unknown }): string | null {\n if (doc.deleted) return null;\n return \"data\" in doc && Array.isArray(doc.data) ? doc.data.join(\"\") : \"\";\n}\n\n/**\n * Route a change into the index: `null` content removes (the note was deleted),\n * any string — including `\"\"` — upserts. Using `content !== null` (rather than a\n * truthiness check) keeps zero-byte notes indexed instead of dropping them\n * (issues #5 / #6).\n */\nexport function applyIndexChange(index: IndexTarget, path: string, content: string | null, mtime?: number): void {\n if (content !== null) {\n index.update(path, content, mtime);\n } else {\n index.remove(path);\n }\n}\n"],"mappings":";;;;;AAmBO,SAAS,cAAc,KAA2D;AACrF,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,UAAU,OAAO,MAAM,QAAQ,IAAI,IAAI,IAAI,IAAI,KAAK,KAAK,EAAE,IAAI;AAC1E;AAQO,SAAS,iBAAiB,OAAoB,MAAc,SAAwB,OAAsB;AAC7G,MAAI,YAAY,MAAM;AAClB,UAAM,OAAO,MAAM,SAAS,KAAK;AAAA,EACrC,OAAO;AACH,UAAM,OAAO,IAAI;AAAA,EACrB;AACJ;","names":[]}
1
+ {"version":3,"sources":["../src/index-sync.ts"],"sourcesContent":["/**\n * Shared search-index sync helpers.\n *\n * Kept dependency-free (no livesync-commonlib imports) so the delete-vs-empty\n * routing is unit-testable in isolation.\n */\n\nexport interface IndexTarget {\n update(path: string, content: string, mtime?: number): void;\n remove(path: string): void;\n}\n\n/**\n * Derive index content from a LiveSync change doc.\n *\n * Returns `null` ONLY when the note is deleted. An existing note with no body\n * yields `\"\"` so a zero-byte note stays distinguishable from a deletion —\n * without this, a note that serializes with no `data` array would look deleted.\n */\nexport function deriveContent(doc: { deleted?: boolean; data?: unknown }): string | null {\n if (doc.deleted) return null;\n return \"data\" in doc && Array.isArray(doc.data) ? doc.data.join(\"\") : \"\";\n}\n\n/**\n * Route a change into the index: `null` content removes (the note was deleted),\n * any string — including `\"\"` — upserts. Using `content !== null` (rather than a\n * truthiness check) keeps zero-byte notes indexed instead of dropping them\n * (issues #5 / #6).\n */\nexport function applyIndexChange(index: IndexTarget, path: string, content: string | null, mtime?: number): void {\n if (content !== null) {\n index.update(path, content, mtime);\n } else {\n index.remove(path);\n }\n}\n\n/**\n * After a completed from-zero catch-up, remove index entries for notes that\n * vanished while the server was down (e.g. a remote \"Rebuild database\" that\n * left no tombstones to replay). Only paths present before the pass\n * (`preexisting`) that the pass did not re-deliver (`seen`) are dropped:\n * restricting the prune to pre-existing paths means an entry the live watcher\n * adds mid-pass is never pruned. Returns the removed paths.\n */\nexport function pruneGhosts(\n index: Pick<IndexTarget, \"remove\">,\n preexisting: Iterable<string>,\n seen: ReadonlySet<string>,\n): string[] {\n const removed: string[] = [];\n for (const p of preexisting) {\n if (!seen.has(p)) {\n index.remove(p);\n removed.push(p);\n }\n }\n return removed;\n}\n"],"mappings":";;;;;AAmBO,SAAS,cAAc,KAA2D;AACrF,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,UAAU,OAAO,MAAM,QAAQ,IAAI,IAAI,IAAI,IAAI,KAAK,KAAK,EAAE,IAAI;AAC1E;AAQO,SAAS,iBAAiB,OAAoB,MAAc,SAAwB,OAAsB;AAC7G,MAAI,YAAY,MAAM;AAClB,UAAM,OAAO,MAAM,SAAS,KAAK;AAAA,EACrC,OAAO;AACH,UAAM,OAAO,IAAI;AAAA,EACrB;AACJ;AAUO,SAAS,YACZ,OACA,aACA,MACQ;AACR,QAAM,UAAoB,CAAC;AAC3B,aAAW,KAAK,aAAa;AACzB,QAAI,CAAC,KAAK,IAAI,CAAC,GAAG;AACd,YAAM,OAAO,CAAC;AACd,cAAQ,KAAK,CAAC;AAAA,IAClB;AAAA,EACJ;AACA,SAAO;AACX;","names":[]}
package/dist/main.js CHANGED
@@ -2,8 +2,9 @@
2
2
  // Node polyfills for livesync-commonlib browser globals
3
3
  if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
4
4
  import {
5
- applyIndexChange
6
- } from "./chunk-SGLPTZJA.js";
5
+ applyIndexChange,
6
+ pruneGhosts
7
+ } from "./chunk-GSVMRHWP.js";
7
8
  import {
8
9
  isValidNotePath,
9
10
  parseFrontmatterAndLinks
@@ -440,6 +441,12 @@ function decrypt(data, passphrase) {
440
441
  decipher.setAuthTag(Buffer.from(tagHex, "hex"));
441
442
  return Buffer.concat([decipher.update(Buffer.from(encryptedHex, "hex")), decipher.final()]).toString("utf-8");
442
443
  }
444
+ function snippetAround(text, idx, len, context = 80) {
445
+ const start = Math.max(0, idx - context);
446
+ const end = Math.min(text.length, idx + len + context);
447
+ const body = text.slice(start, end).replace(/\s+/g, " ").trim();
448
+ return (start > 0 ? "\u2026" : "") + body + (end < text.length ? "\u2026" : "");
449
+ }
443
450
  var SearchIndex = class {
444
451
  _state = "building";
445
452
  mtimes = /* @__PURE__ */ new Map();
@@ -447,8 +454,14 @@ var SearchIndex = class {
447
454
  links = /* @__PURE__ */ new Map();
448
455
  backlinks = /* @__PURE__ */ new Map();
449
456
  knownPaths = /* @__PURE__ */ new Set();
457
+ /** Decrypted note text, in memory only — one copy per note; term matching is case-insensitive via a regex per term. */
458
+ content = /* @__PURE__ */ new Map();
459
+ /** Frontmatter `title:` per path, when present — searched together with the path. */
460
+ titles = /* @__PURE__ */ new Map();
450
461
  saving = false;
451
462
  _since = "";
463
+ /** When `since` last advanced from a completed catch-up or a watcher change (ms), null before the first. */
464
+ _lastSyncAt = null;
452
465
  persistPath;
453
466
  passphrase;
454
467
  constructor(persistPath, passphrase) {
@@ -511,14 +524,28 @@ var SearchIndex = class {
511
524
  this.saving = false;
512
525
  }
513
526
  }
514
- /** Add or update a note in the index. */
527
+ /**
528
+ * Add or update a note in the index. The watcher and the pre-search
529
+ * catch-up both write here without coordinating, so a write whose mtime is
530
+ * not newer than the one recorded for text already held is skipped: a
531
+ * stale copy can never replace a newer one. Mtimes loaded from disk carry
532
+ * no text, so the startup rebuild still fills them in.
533
+ */
515
534
  update(path, content, mtime) {
535
+ if (mtime !== void 0 && this.content.has(path) && mtime <= (this.mtimes.get(path) ?? -Infinity)) return;
516
536
  if (this.knownPaths.has(path)) {
517
537
  this.clearBacklinks(path);
518
538
  }
519
539
  this.knownPaths.add(path);
520
540
  if (mtime !== void 0) this.mtimes.set(path, mtime);
541
+ this.content.set(path, content);
521
542
  const parsed = parseFrontmatterAndLinks(content);
543
+ const title = parsed.frontmatter["title"];
544
+ if (typeof title === "string" && title.trim().length > 0) {
545
+ this.titles.set(path, title.trim());
546
+ } else {
547
+ this.titles.delete(path);
548
+ }
522
549
  if (parsed.tags.length > 0) {
523
550
  this.tags.set(path, parsed.tags);
524
551
  } else {
@@ -541,9 +568,67 @@ var SearchIndex = class {
541
568
  this.knownPaths.delete(path);
542
569
  this.mtimes.delete(path);
543
570
  this.tags.delete(path);
571
+ this.content.delete(path);
572
+ this.titles.delete(path);
544
573
  this.clearBacklinks(path);
545
574
  }
546
575
  }
576
+ /** Decrypted text of a note, or null if the index holds no content for it. */
577
+ getContent(path) {
578
+ return this.content.get(path) ?? null;
579
+ }
580
+ /** Notes whose text is in memory. Below `size` means search cannot see every note. */
581
+ get contentCount() {
582
+ return this.content.size;
583
+ }
584
+ /**
585
+ * Search over path + frontmatter title first, then the in-memory text.
586
+ * Ranked: name hits first, then number of distinct terms matched, then
587
+ * newest first, then path. `limit` defaults to 20.
588
+ */
589
+ search(q) {
590
+ const prefix = q.folder ? q.folder.endsWith("/") ? q.folder : q.folder + "/" : void 0;
591
+ const terms = (q.terms ?? []).filter((t) => t.length > 0).map((t) => ({
592
+ text: t.toLowerCase(),
593
+ // Case-insensitive (Unicode) search over the note text without a lowercased copy of the vault in memory.
594
+ re: new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu")
595
+ }));
596
+ const hits = [];
597
+ for (const [path, entry] of this.content) {
598
+ if (!isValidNotePath(path)) continue;
599
+ if (prefix && !path.startsWith(prefix)) continue;
600
+ if (q.tag && !this.getTags(path).includes(q.tag)) continue;
601
+ const mtime = this.mtimes.get(path) ?? 0;
602
+ if (q.modifiedAfter !== void 0 && mtime < q.modifiedAfter) continue;
603
+ const title = this.titles.get(path);
604
+ const name = title ? `${path} ${title}` : path;
605
+ const nameLower = name.toLowerCase();
606
+ let matched = 0;
607
+ let nameHit = false;
608
+ let anchor = -1;
609
+ let anchorLen = 1;
610
+ {
611
+ for (const t of terms) {
612
+ const inName = nameLower.includes(t.text);
613
+ const i = entry.search(t.re);
614
+ if (!inName && i === -1) continue;
615
+ matched++;
616
+ if (inName) nameHit = true;
617
+ if (i !== -1 && (anchor === -1 || i < anchor)) {
618
+ anchor = i;
619
+ anchorLen = t.text.length;
620
+ }
621
+ }
622
+ if (matched === 0) continue;
623
+ }
624
+ const snippet = anchor === -1 ? "" : snippetAround(entry, anchor, anchorLen);
625
+ hits.push({ path, mtime, matched, nameHit, snippet });
626
+ }
627
+ hits.sort(
628
+ (a, b) => Number(b.nameHit) - Number(a.nameHit) || b.matched - a.matched || b.mtime - a.mtime || a.path.localeCompare(b.path)
629
+ );
630
+ return { hits: hits.slice(0, q.limit ?? 20), total: hits.length };
631
+ }
547
632
  /** Remove all backlink entries where path is the source. */
548
633
  clearBacklinks(path) {
549
634
  const oldLinks = this.links.get(path);
@@ -621,6 +706,12 @@ var SearchIndex = class {
621
706
  set since(value) {
622
707
  this._since = value;
623
708
  }
709
+ get lastSyncAt() {
710
+ return this._lastSyncAt;
711
+ }
712
+ set lastSyncAt(value) {
713
+ this._lastSyncAt = value;
714
+ }
624
715
  get size() {
625
716
  return this.knownPaths.size;
626
717
  }
@@ -779,11 +870,97 @@ function describeListing(s) {
779
870
  return line + describeIndexState(s.index);
780
871
  }
781
872
 
873
+ // src/search-format.ts
874
+ function resolveDisplayZone(raw) {
875
+ const zone = raw?.trim() || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
876
+ try {
877
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
878
+ return zone;
879
+ } catch {
880
+ console.warn(`DISPLAY_TIMEZONE "${zone}" is not a valid IANA time zone; using UTC.`);
881
+ return "UTC";
882
+ }
883
+ }
884
+ var DISPLAY_TIMEZONE = resolveDisplayZone(process.env.DISPLAY_TIMEZONE);
885
+ function formatServerTime(ms, timeZone = DISPLAY_TIMEZONE) {
886
+ const d = new Date(ms);
887
+ const parts = new Intl.DateTimeFormat("sv-SE", {
888
+ timeZone,
889
+ year: "numeric",
890
+ month: "2-digit",
891
+ day: "2-digit",
892
+ hour: "2-digit",
893
+ minute: "2-digit",
894
+ hourCycle: "h23",
895
+ timeZoneName: "short"
896
+ }).formatToParts(d);
897
+ const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
898
+ const utc = d.toISOString().slice(11, 16);
899
+ return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")} ${get("timeZoneName")} (${utc}Z)`;
900
+ }
901
+ function seqPrefix(seq) {
902
+ if (!seq) return "none";
903
+ const dash = seq.indexOf("-");
904
+ return dash === -1 ? seq : seq.slice(0, dash);
905
+ }
906
+ function minutesBetween(from, to) {
907
+ return Math.max(0, Math.round((to - from) / 6e4));
908
+ }
909
+ function plural2(n, word) {
910
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
911
+ }
912
+ function describeSync(s, timeZone = DISPLAY_TIMEZONE) {
913
+ const now = formatServerTime(s.now, timeZone);
914
+ const coverage = `${s.withContent} of ${plural2(s.notes, "note")} with content`;
915
+ if (s.mode === "local") {
916
+ return `Index: local vault, no sequence \u2014 ${now}; ${coverage}.`;
917
+ }
918
+ if (s.state === "building") {
919
+ return `Index: still building (${plural2(s.notes, "note")} so far), not caught up \u2014 ${now}; results may be incomplete.`;
920
+ }
921
+ if (s.state === "failed") {
922
+ return `Index: rebuild failed at startup (see server log), not caught up \u2014 ${now}; results may be incomplete or stale.`;
923
+ }
924
+ if (s.error) {
925
+ const last = s.syncedAt === null ? "never" : `${formatServerTime(s.syncedAt, timeZone)}, ${minutesBetween(s.syncedAt, s.now)} min ago`;
926
+ return `Index: catch-up failed (${s.error}); last caught up with CouchDB seq ${seqPrefix(s.seq)} \u2014 ${last}; results may be stale.`;
927
+ }
928
+ const age = s.syncedAt === null ? 0 : minutesBetween(s.syncedAt, s.now);
929
+ let line = `Index caught up with CouchDB seq ${seqPrefix(s.seq)} \u2014 ${now}, ${age} min; ${coverage}`;
930
+ if (s.unreadable > 0) {
931
+ line += `; ${plural2(s.unreadable, "document")} could not be read`;
932
+ }
933
+ return line + ".";
934
+ }
935
+ function describeQuery(terms) {
936
+ return terms.map((t) => `"${t}"`).join(", ");
937
+ }
938
+ function describeHits(hits, total, query, deepLink) {
939
+ if (total === 0) return `No notes match ${query}.`;
940
+ const shown = hits.length < total ? ` (showing ${hits.length}; narrow with folder, tag or modified_after)` : "";
941
+ const nameHits = hits.filter((h) => h.nameHit).length;
942
+ const byName = nameHits > 0 ? ` ${plural2(nameHits, "hit")} by path or title listed first.` : "";
943
+ const header = `${plural2(total, "note")} ${total === 1 ? "matches" : "match"} ${query}${shown}.${byName} Call read_note on a hit before relying on it.`;
944
+ const lines = hits.map((h) => {
945
+ const date = h.mtime ? new Date(h.mtime).toISOString().slice(0, 16) : "";
946
+ const context = h.nameHit ? h.snippet ? `[path/title] ${h.snippet}` : "[path/title match]" : h.snippet;
947
+ return `- ${date} [${h.path}](${deepLink(h.path)})
948
+ ${context}`;
949
+ });
950
+ return [header, ...lines].join("\n");
951
+ }
952
+
782
953
  // src/tools.ts
783
954
  var debugLogging = process.env.LOG_LEVEL === "debug";
955
+ var SEARCH_MAX_HITS = 20;
956
+ var SEARCH_MAX_TERMS = 20;
957
+ var SEARCH_MAX_TERM_LENGTH = 200;
958
+ function cleanSearchTerms(terms) {
959
+ return (terms ?? []).map((t) => t.trim().slice(0, SEARCH_MAX_TERM_LENGTH)).filter((t) => t.length > 0).slice(0, SEARCH_MAX_TERMS);
960
+ }
784
961
  var WRITE_TOOLS = ["write_note", "edit_note", "delete_note", "move_note"];
785
962
  var READ_NOTE_MAX_RESULT_SIZE_CHARS = 1e5;
786
- function registerTools(server2, vault2, searchIndex2, vaultName, readOnly = false, writeFolders = null) {
963
+ function registerTools(server2, vault2, searchIndex2, vaultName, readOnly = false, writeFolders = null, syncBeforeSearch2) {
787
964
  if (readOnly) {
788
965
  console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(", ")}).`);
789
966
  } else if (writeFolders) {
@@ -910,6 +1087,45 @@ ${content}`;
910
1087
  return [header, ...lines].join("\n");
911
1088
  }
912
1089
  });
1090
+ server2.addTool({
1091
+ name: "search_notes",
1092
+ description: "Search note contents for terms, case-insensitive.\nPaths and frontmatter titles are searched first and such hits rank on top, marked [path/title]; content hits follow. Returns paths with one context line each, never the note body: call read_note on a hit before relying on it. Give `terms` (a note matches when ANY term occurs \u2014 OR, so list synonyms, field names and other-language wordings; a term may contain spaces; ranked by how many terms match) Filters: folder, tag, modified_after. The first line of every response is the index status: the CouchDB sequence the index is caught up with after a catch-up run just before the search, the server time (local zone and UTC), its age in minutes, how many notes carry content, and any documents that could not be read.",
1093
+ parameters: z.object({
1094
+ terms: z.array(z.string().max(SEARCH_MAX_TERM_LENGTH)).max(SEARCH_MAX_TERMS).optional().describe(`Case-insensitive substrings, at most ${SEARCH_MAX_TERMS} of at most ${SEARCH_MAX_TERM_LENGTH} characters each; a note matches when any of them occurs. E.g. ['drag i kanban', 'kanban', 'labels p\xE5 kategori'].`),
1095
+ folder: z.string().optional().describe("Folder to search in, e.g. 'projects'. Omit for the whole vault."),
1096
+ tag: z.string().optional().describe("Only notes carrying this tag, e.g. 'project'."),
1097
+ modified_after: z.string().optional().describe("Only notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'."),
1098
+ limit: z.coerce.number().optional().describe(`Max hits to return, default and maximum ${SEARCH_MAX_HITS}.`)
1099
+ }),
1100
+ execute: async ({ terms, folder, tag, modified_after, limit }) => {
1101
+ const cleanTerms = cleanSearchTerms(terms);
1102
+ if (cleanTerms.length === 0) {
1103
+ return "Give at least one term.";
1104
+ }
1105
+ let modifiedAfter;
1106
+ if (modified_after) {
1107
+ modifiedAfter = new Date(modified_after).getTime();
1108
+ if (isNaN(modifiedAfter)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;
1109
+ }
1110
+ const cap = Math.max(1, Math.min(SEARCH_MAX_HITS, limit ?? SEARCH_MAX_HITS));
1111
+ const sync = syncBeforeSearch2 ? await syncBeforeSearch2() : { unreadable: 0 };
1112
+ const status = {
1113
+ mode: syncBeforeSearch2 ? "couchdb" : "local",
1114
+ state: searchIndex2.state,
1115
+ seq: searchIndex2.since,
1116
+ syncedAt: searchIndex2.lastSyncAt,
1117
+ now: Date.now(),
1118
+ notes: searchIndex2.size,
1119
+ withContent: searchIndex2.contentCount,
1120
+ unreadable: sync.unreadable,
1121
+ error: sync.error
1122
+ };
1123
+ const { hits, total } = searchIndex2.search({ terms: cleanTerms, folder, tag, modifiedAfter, limit: cap });
1124
+ const query = describeQuery(cleanTerms);
1125
+ return `${describeSync(status)}
1126
+ ${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;
1127
+ }
1128
+ });
913
1129
  server2.addTool({
914
1130
  name: "list_folders",
915
1131
  description: "List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.",
@@ -1167,7 +1383,7 @@ if (VAULT_PATH) {
1167
1383
  console.error("COUCHDB_PASSWORD is required in remote mode.");
1168
1384
  process.exit(1);
1169
1385
  }
1170
- const { Vault } = await import("./vault-EJSNMND5.js");
1386
+ const { Vault } = await import("./vault-IAH37QM4.js");
1171
1387
  vault = new Vault({
1172
1388
  couchdbUrl: COUCHDB_URL,
1173
1389
  couchdbUser: COUCHDB_USER,
@@ -1198,38 +1414,45 @@ await searchIndex.loadFromDisk();
1198
1414
  if (debugLogging2) {
1199
1415
  console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || "(none)"}`);
1200
1416
  }
1417
+ if (searchIndex.size > 0 && searchIndex.contentCount < searchIndex.size) {
1418
+ 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).`);
1419
+ searchIndex.since = "0";
1420
+ }
1201
1421
  async function rebuildIndex() {
1202
1422
  const start = performance.now();
1203
1423
  if (COUCHDB_URL && vault.catchUp) {
1204
- const changeCallback = (path, content, mtime) => {
1205
- applyIndexChange(searchIndex, path, content, mtime);
1206
- };
1207
- let since = searchIndex.since || "0";
1424
+ const since = searchIndex.since || "0";
1208
1425
  if (debugLogging2) console.log(`[debug] CouchDB catch-up from since: ${since}`);
1209
1426
  let changes = 0;
1427
+ const preexisting = new Set(searchIndex.listPaths());
1428
+ const seen = /* @__PURE__ */ new Set();
1429
+ let fromZero = since === "0";
1210
1430
  const onBatch = async (batchSince, processed) => {
1211
1431
  searchIndex.since = batchSince;
1212
1432
  await searchIndex.saveToDisk();
1213
1433
  console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);
1214
1434
  };
1435
+ const countingCallback = (path, content, mtime) => {
1436
+ changes++;
1437
+ if (debugLogging2) console.log(`[debug] Change: ${path} ${content !== null ? "(update)" : "(delete)"}`);
1438
+ if (content !== null) seen.add(path);
1439
+ else seen.delete(path);
1440
+ applyIndexChange(searchIndex, path, content, mtime);
1441
+ };
1215
1442
  try {
1216
- const countingCallback = (path, content, mtime) => {
1217
- changes++;
1218
- if (debugLogging2) console.log(`[debug] Change: ${path} ${content !== null ? "(update)" : "(delete)"}`);
1219
- changeCallback(path, content, mtime);
1220
- };
1221
1443
  const newSince = await vault.catchUp(since, countingCallback, onBatch);
1222
1444
  searchIndex.since = newSince;
1445
+ searchIndex.lastSyncAt = Date.now();
1223
1446
  } catch (err) {
1224
- console.warn(`Catch-up failed (${describeError(err, debugLogging2)}), rebuilding index from scratch...`);
1225
- searchIndex.clear();
1447
+ console.warn(`Catch-up failed (${describeError(err, debugLogging2)}), re-reading from the start...`);
1226
1448
  changes = 0;
1227
- const newSince = await vault.catchUp("0", (path, content, mtime) => {
1228
- changes++;
1229
- changeCallback(path, content, mtime);
1230
- }, onBatch);
1449
+ seen.clear();
1450
+ fromZero = true;
1451
+ const newSince = await vault.catchUp("0", countingCallback, onBatch);
1231
1452
  searchIndex.since = newSince;
1453
+ searchIndex.lastSyncAt = Date.now();
1232
1454
  }
1455
+ if (fromZero) pruneGhosts(searchIndex, preexisting, seen);
1233
1456
  if (changes > 0) {
1234
1457
  console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1e3).toFixed(1)}s (${searchIndex.size} notes).`);
1235
1458
  } else {
@@ -1262,6 +1485,30 @@ rebuildIndex().catch((err) => {
1262
1485
  searchIndex.state = "failed";
1263
1486
  console.error(`Index rebuild failed: ${describeError(err, debugLogging2)}`);
1264
1487
  });
1488
+ var syncChain = Promise.resolve();
1489
+ async function syncBeforeSearch() {
1490
+ if (!(COUCHDB_URL && vault.catchUp) || searchIndex.state !== "ready") return { unreadable: 0 };
1491
+ const run = async () => {
1492
+ const stats = { unreadable: 0 };
1493
+ try {
1494
+ const newSince = await vault.catchUp(
1495
+ searchIndex.since || "0",
1496
+ (path, content, mtime) => applyIndexChange(searchIndex, path, content, mtime),
1497
+ void 0,
1498
+ stats
1499
+ );
1500
+ searchIndex.since = newSince;
1501
+ searchIndex.lastSyncAt = Date.now();
1502
+ return { unreadable: stats.unreadable };
1503
+ } catch (err) {
1504
+ console.warn(`Pre-search catch-up failed: ${describeError(err, debugLogging2)}`);
1505
+ return { unreadable: stats.unreadable, error: "CouchDB sync error" };
1506
+ }
1507
+ };
1508
+ const result = syncChain.then(run, run);
1509
+ syncChain = result.catch(() => void 0);
1510
+ return result;
1511
+ }
1265
1512
  var fsWatcher = null;
1266
1513
  if (VAULT_PATH) {
1267
1514
  const pending = /* @__PURE__ */ new Map();
@@ -1291,14 +1538,17 @@ if (VAULT_PATH) {
1291
1538
  vault.watchChanges((path, content, mtime, seq) => {
1292
1539
  if (debugLogging2) console.log(`[debug] CouchDB ${content === null ? "delete" : "change"}: ${path}`);
1293
1540
  applyIndexChange(searchIndex, path, content, mtime);
1294
- if (seq) searchIndex.since = String(seq);
1541
+ if (seq) {
1542
+ searchIndex.since = String(seq);
1543
+ searchIndex.lastSyncAt = Date.now();
1544
+ }
1295
1545
  });
1296
1546
  console.log("Watching CouchDB for LiveSync changes.");
1297
1547
  }
1298
1548
  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.";
1299
1549
  var serverOptions = {
1300
1550
  name: "obsidian-sync-mcp",
1301
- version: "0.7.3",
1551
+ version: "0.8.0",
1302
1552
  instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
1303
1553
 
1304
1554
  ${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
@@ -1343,7 +1593,7 @@ if (AUTH_TOKEN) {
1343
1593
  auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);
1344
1594
  await auth.loadTokens();
1345
1595
  }
1346
- registerTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS);
1596
+ registerTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS, COUCHDB_URL ? syncBeforeSearch : void 0);
1347
1597
  async function shutdown() {
1348
1598
  console.log("Shutting down...");
1349
1599
  if (fsWatcher) fsWatcher.close();
@@ -1365,7 +1615,7 @@ server.start({
1365
1615
  transportType: "httpStream",
1366
1616
  httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
1367
1617
  });
1368
- console.log(`obsidian-sync-mcp v${"0.7.3"} listening on port ${PORT}`);
1618
+ console.log(`obsidian-sync-mcp v${"0.8.0"} listening on port ${PORT}`);
1369
1619
  process.on("unhandledRejection", (err) => {
1370
1620
  console.error(`Unhandled rejection: ${describeError(err, debugLogging2)}`);
1371
1621
  });