obsidian-sync-mcp 0.7.3 → 0.9.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 +6 -2
- package/dist/{chunk-SGLPTZJA.js → chunk-GSVMRHWP.js} +13 -2
- package/dist/{chunk-SGLPTZJA.js.map → chunk-GSVMRHWP.js.map} +1 -1
- package/dist/main.js +279 -25
- package/dist/main.js.map +1 -1
- package/dist/{vault-EJSNMND5.js → vault-6H64Y46A.js} +2762 -662
- package/dist/vault-6H64Y46A.js.map +1 -0
- package/package.json +2 -2
- package/dist/vault-EJSNMND5.js.map +0 -1
package/README.md
CHANGED
|
@@ -63,7 +63,7 @@ docker run -p 8787:8787 \
|
|
|
63
63
|
ghcr.io/es617/obsidian-sync-mcp:latest
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
-
Set `COUCHDB_PASSPHRASE` if you use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings. Set `BASE_URL` to your public URL (required for OAuth callbacks when agents connect over HTTPS).
|
|
66
|
+
Set `COUCHDB_PASSPHRASE` if you use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings. If the vault was created with LiveSync 1.0.33+ and path obfuscation, also set `COUCHDB_ID_DERIVATION_KEY` to your LiveSync recovery code (`sls-id-v1:...`, from "Show current recovery code") so the server can resolve note paths. Set `BASE_URL` to your public URL (required for OAuth callbacks when agents connect over HTTPS).
|
|
67
67
|
|
|
68
68
|
Your MCP endpoint is `https://your-app.fly.dev/mcp` (Fly.io) or `https://your-server:8787/mcp` (Docker behind HTTPS).
|
|
69
69
|
|
|
@@ -170,7 +170,7 @@ VAULT_NAME=MyVault \
|
|
|
170
170
|
npx obsidian-sync-mcp
|
|
171
171
|
```
|
|
172
172
|
|
|
173
|
-
Omit `COUCHDB_PASSPHRASE` if you don't use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings.
|
|
173
|
+
Omit `COUCHDB_PASSPHRASE` if you don't use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings. If the vault was created with LiveSync 1.0.33+ and path obfuscation, also set `COUCHDB_ID_DERIVATION_KEY` to your LiveSync recovery code (`sls-id-v1:...`) so the server can resolve note paths.
|
|
174
174
|
|
|
175
175
|
**Or with Docker:**
|
|
176
176
|
|
|
@@ -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 |
|
|
@@ -249,6 +250,8 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
|
|
|
249
250
|
| `COUCHDB_DATABASE` | CouchDB mode | `obsidian` | CouchDB database name. The server never creates it: if it doesn't exist, startup fails with an error |
|
|
250
251
|
| `COUCHDB_PASSPHRASE` | CouchDB mode | — | LiveSync E2E encryption passphrase (must match plugin setting) |
|
|
251
252
|
| `COUCHDB_OBFUSCATE_PROPERTIES` | CouchDB mode | `false` | Set to `true` if "Obfuscate Properties" is enabled in LiveSync (obfuscates file paths, sizes, dates in the database). For existing vaults the actual setting is auto-detected at startup; this value only decides the format for a brand-new empty database |
|
|
253
|
+
| `COUCHDB_ID_DERIVATION_KEY` | CouchDB mode | — | LiveSync "independent ID derivation" recovery code (`sls-id-v1:...`). Needed to read and write notes on vaults created with LiveSync 1.0.33+ that use path obfuscation; leave unset for older (passphrase-derived) vaults. Get it from LiveSync's "Show current recovery code" |
|
|
254
|
+
| `COUCHDB_CASE_SENSITIVE` | CouchDB mode | `false` | Set to `true` only if your LiveSync vault has "Handle filenames as case-sensitive" enabled. It must match the vault, or obfuscated document IDs won't resolve (the server fails to start with a clear message). Leave unset otherwise |
|
|
252
255
|
| `VAULT_NAME` | Both | `MyVault` | Vault name (used for deep links and index storage) |
|
|
253
256
|
| `MCP_AUTH_TOKEN` | Optional | — | Password for authentication |
|
|
254
257
|
| `BASE_URL` | Optional | `http://localhost:PORT` | Public URL (for OAuth callbacks when using a tunnel) |
|
|
@@ -257,6 +260,7 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
|
|
|
257
260
|
| `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
261
|
| `DATA_DIR` | Optional | `~/.obsidian-mcp` | Directory for persisted data (metadata index, auth tokens) |
|
|
259
262
|
| `LOG_LEVEL` | Optional | — | Set to `debug` for verbose logging (library logs, change feed, index sync) |
|
|
263
|
+
| `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
264
|
| `MCP_REFRESH_DAYS` | Optional | `14` | Days before auth session expires |
|
|
261
265
|
| `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
266
|
| `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-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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.",
|
|
@@ -1130,6 +1346,8 @@ var COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;
|
|
|
1130
1346
|
var COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? "obsidian";
|
|
1131
1347
|
var COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || void 0;
|
|
1132
1348
|
var COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === "true";
|
|
1349
|
+
var COUCHDB_ID_DERIVATION_KEY = process.env.COUCHDB_ID_DERIVATION_KEY || void 0;
|
|
1350
|
+
var COUCHDB_CASE_SENSITIVE = process.env.COUCHDB_CASE_SENSITIVE === "true";
|
|
1133
1351
|
var VAULT_NAME = process.env.VAULT_NAME ?? "MyVault";
|
|
1134
1352
|
var PORT = parseInt(process.env.PORT ?? "8787");
|
|
1135
1353
|
var BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;
|
|
@@ -1167,14 +1385,16 @@ if (VAULT_PATH) {
|
|
|
1167
1385
|
console.error("COUCHDB_PASSWORD is required in remote mode.");
|
|
1168
1386
|
process.exit(1);
|
|
1169
1387
|
}
|
|
1170
|
-
const { Vault } = await import("./vault-
|
|
1388
|
+
const { Vault } = await import("./vault-6H64Y46A.js");
|
|
1171
1389
|
vault = new Vault({
|
|
1172
1390
|
couchdbUrl: COUCHDB_URL,
|
|
1173
1391
|
couchdbUser: COUCHDB_USER,
|
|
1174
1392
|
couchdbPassword: COUCHDB_PASSWORD,
|
|
1175
1393
|
database: COUCHDB_DATABASE,
|
|
1176
1394
|
passphrase: COUCHDB_PASSPHRASE,
|
|
1177
|
-
obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES
|
|
1395
|
+
obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,
|
|
1396
|
+
idDerivationKey: COUCHDB_ID_DERIVATION_KEY,
|
|
1397
|
+
caseSensitive: COUCHDB_CASE_SENSITIVE
|
|
1178
1398
|
});
|
|
1179
1399
|
console.log(`Remote mode: ${redactCredentials(COUCHDB_URL)}`);
|
|
1180
1400
|
} else {
|
|
@@ -1198,38 +1418,45 @@ await searchIndex.loadFromDisk();
|
|
|
1198
1418
|
if (debugLogging2) {
|
|
1199
1419
|
console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || "(none)"}`);
|
|
1200
1420
|
}
|
|
1421
|
+
if (searchIndex.size > 0 && searchIndex.contentCount < searchIndex.size) {
|
|
1422
|
+
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
|
+
searchIndex.since = "0";
|
|
1424
|
+
}
|
|
1201
1425
|
async function rebuildIndex() {
|
|
1202
1426
|
const start = performance.now();
|
|
1203
1427
|
if (COUCHDB_URL && vault.catchUp) {
|
|
1204
|
-
const
|
|
1205
|
-
applyIndexChange(searchIndex, path, content, mtime);
|
|
1206
|
-
};
|
|
1207
|
-
let since = searchIndex.since || "0";
|
|
1428
|
+
const since = searchIndex.since || "0";
|
|
1208
1429
|
if (debugLogging2) console.log(`[debug] CouchDB catch-up from since: ${since}`);
|
|
1209
1430
|
let changes = 0;
|
|
1431
|
+
const preexisting = new Set(searchIndex.listPaths());
|
|
1432
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1433
|
+
let fromZero = since === "0";
|
|
1210
1434
|
const onBatch = async (batchSince, processed) => {
|
|
1211
1435
|
searchIndex.since = batchSince;
|
|
1212
1436
|
await searchIndex.saveToDisk();
|
|
1213
1437
|
console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);
|
|
1214
1438
|
};
|
|
1439
|
+
const countingCallback = (path, content, mtime) => {
|
|
1440
|
+
changes++;
|
|
1441
|
+
if (debugLogging2) console.log(`[debug] Change: ${path} ${content !== null ? "(update)" : "(delete)"}`);
|
|
1442
|
+
if (content !== null) seen.add(path);
|
|
1443
|
+
else seen.delete(path);
|
|
1444
|
+
applyIndexChange(searchIndex, path, content, mtime);
|
|
1445
|
+
};
|
|
1215
1446
|
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
1447
|
const newSince = await vault.catchUp(since, countingCallback, onBatch);
|
|
1222
1448
|
searchIndex.since = newSince;
|
|
1449
|
+
searchIndex.lastSyncAt = Date.now();
|
|
1223
1450
|
} catch (err) {
|
|
1224
|
-
console.warn(`Catch-up failed (${describeError(err, debugLogging2)}),
|
|
1225
|
-
searchIndex.clear();
|
|
1451
|
+
console.warn(`Catch-up failed (${describeError(err, debugLogging2)}), re-reading from the start...`);
|
|
1226
1452
|
changes = 0;
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
}, onBatch);
|
|
1453
|
+
seen.clear();
|
|
1454
|
+
fromZero = true;
|
|
1455
|
+
const newSince = await vault.catchUp("0", countingCallback, onBatch);
|
|
1231
1456
|
searchIndex.since = newSince;
|
|
1457
|
+
searchIndex.lastSyncAt = Date.now();
|
|
1232
1458
|
}
|
|
1459
|
+
if (fromZero) pruneGhosts(searchIndex, preexisting, seen);
|
|
1233
1460
|
if (changes > 0) {
|
|
1234
1461
|
console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1e3).toFixed(1)}s (${searchIndex.size} notes).`);
|
|
1235
1462
|
} else {
|
|
@@ -1262,6 +1489,30 @@ rebuildIndex().catch((err) => {
|
|
|
1262
1489
|
searchIndex.state = "failed";
|
|
1263
1490
|
console.error(`Index rebuild failed: ${describeError(err, debugLogging2)}`);
|
|
1264
1491
|
});
|
|
1492
|
+
var syncChain = Promise.resolve();
|
|
1493
|
+
async function syncBeforeSearch() {
|
|
1494
|
+
if (!(COUCHDB_URL && vault.catchUp) || searchIndex.state !== "ready") return { unreadable: 0 };
|
|
1495
|
+
const run = async () => {
|
|
1496
|
+
const stats = { unreadable: 0 };
|
|
1497
|
+
try {
|
|
1498
|
+
const newSince = await vault.catchUp(
|
|
1499
|
+
searchIndex.since || "0",
|
|
1500
|
+
(path, content, mtime) => applyIndexChange(searchIndex, path, content, mtime),
|
|
1501
|
+
void 0,
|
|
1502
|
+
stats
|
|
1503
|
+
);
|
|
1504
|
+
searchIndex.since = newSince;
|
|
1505
|
+
searchIndex.lastSyncAt = Date.now();
|
|
1506
|
+
return { unreadable: stats.unreadable };
|
|
1507
|
+
} catch (err) {
|
|
1508
|
+
console.warn(`Pre-search catch-up failed: ${describeError(err, debugLogging2)}`);
|
|
1509
|
+
return { unreadable: stats.unreadable, error: "CouchDB sync error" };
|
|
1510
|
+
}
|
|
1511
|
+
};
|
|
1512
|
+
const result = syncChain.then(run, run);
|
|
1513
|
+
syncChain = result.catch(() => void 0);
|
|
1514
|
+
return result;
|
|
1515
|
+
}
|
|
1265
1516
|
var fsWatcher = null;
|
|
1266
1517
|
if (VAULT_PATH) {
|
|
1267
1518
|
const pending = /* @__PURE__ */ new Map();
|
|
@@ -1291,14 +1542,17 @@ if (VAULT_PATH) {
|
|
|
1291
1542
|
vault.watchChanges((path, content, mtime, seq) => {
|
|
1292
1543
|
if (debugLogging2) console.log(`[debug] CouchDB ${content === null ? "delete" : "change"}: ${path}`);
|
|
1293
1544
|
applyIndexChange(searchIndex, path, content, mtime);
|
|
1294
|
-
if (seq)
|
|
1545
|
+
if (seq) {
|
|
1546
|
+
searchIndex.since = String(seq);
|
|
1547
|
+
searchIndex.lastSyncAt = Date.now();
|
|
1548
|
+
}
|
|
1295
1549
|
});
|
|
1296
1550
|
console.log("Watching CouchDB for LiveSync changes.");
|
|
1297
1551
|
}
|
|
1298
1552
|
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
1553
|
var serverOptions = {
|
|
1300
1554
|
name: "obsidian-sync-mcp",
|
|
1301
|
-
version: "0.
|
|
1555
|
+
version: "0.9.0",
|
|
1302
1556
|
instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
|
|
1303
1557
|
|
|
1304
1558
|
${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
|
|
@@ -1343,7 +1597,7 @@ if (AUTH_TOKEN) {
|
|
|
1343
1597
|
auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);
|
|
1344
1598
|
await auth.loadTokens();
|
|
1345
1599
|
}
|
|
1346
|
-
registerTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS);
|
|
1600
|
+
registerTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS, COUCHDB_URL ? syncBeforeSearch : void 0);
|
|
1347
1601
|
async function shutdown() {
|
|
1348
1602
|
console.log("Shutting down...");
|
|
1349
1603
|
if (fsWatcher) fsWatcher.close();
|
|
@@ -1365,7 +1619,7 @@ server.start({
|
|
|
1365
1619
|
transportType: "httpStream",
|
|
1366
1620
|
httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
|
|
1367
1621
|
});
|
|
1368
|
-
console.log(`obsidian-sync-mcp v${"0.
|
|
1622
|
+
console.log(`obsidian-sync-mcp v${"0.9.0"} listening on port ${PORT}`);
|
|
1369
1623
|
process.on("unhandledRejection", (err) => {
|
|
1370
1624
|
console.error(`Unhandled rejection: ${describeError(err, debugLogging2)}`);
|
|
1371
1625
|
});
|