obsidian-sync-mcp 0.3.0 → 0.4.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
@@ -2,15 +2,17 @@
2
2
  // Node polyfills for livesync-commonlib browser globals
3
3
  if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
4
4
  import {
5
- extractSnippet
6
- } from "./chunk-TFJDIQK4.js";
5
+ extractSnippet,
6
+ parseFrontmatterAndLinks
7
+ } from "./chunk-GK3PAZZJ.js";
7
8
 
8
9
  // src/main.ts
9
10
  import { FastMCP } from "fastmcp";
10
11
  import { join } from "path";
11
12
  import { timingSafeEqual as timingSafeEqual2, createHash as createHash2 } from "crypto";
12
13
  import { watch } from "fs";
13
- import { readFile as readFile3 } from "fs/promises";
14
+ import { stat } from "fs/promises";
15
+ import { setGlobalLogFunction, LEVEL_INFO } from "octagonal-wheels/common/logger";
14
16
 
15
17
  // src/auth.ts
16
18
  import { randomUUID, randomBytes, createHash, timingSafeEqual } from "crypto";
@@ -18,7 +20,7 @@ import { readFile, writeFile, mkdir, chmod } from "fs/promises";
18
20
  import { dirname } from "path";
19
21
  var TOKEN_EXPIRY_MS = 3600 * 1e3;
20
22
  var DEFAULT_REFRESH_DAYS = 14;
21
- var REFRESH_EXPIRY_MS = parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) * 24 * 3600 * 1e3;
23
+ var REFRESH_EXPIRY_MS = (parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) || DEFAULT_REFRESH_DAYS) * 24 * 3600 * 1e3;
22
24
  var MAX_FAILED_BEFORE_LOCKOUT = 5;
23
25
  var BASE_LOCKOUT_MS = 5 * 1e3;
24
26
  var MAX_CLIENTS = 100;
@@ -74,7 +76,12 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
74
76
  if (redirectUris.length === 0) {
75
77
  return c.json({ error: "invalid_client_metadata", error_description: "redirect_uris required" }, 400);
76
78
  }
77
- if (redirectUris.some((u) => typeof u !== "string" || u.length > 2048)) {
79
+ const safeUri = (u) => {
80
+ if (typeof u !== "string" || u.length > 2048) return false;
81
+ const lower = u.toLowerCase();
82
+ return !lower.startsWith("javascript:") && !lower.startsWith("data:") && !lower.startsWith("file:");
83
+ };
84
+ if (redirectUris.some((u) => !safeUri(u))) {
78
85
  return c.json({ error: "invalid_client_metadata", error_description: "invalid redirect_uri" }, 400);
79
86
  }
80
87
  const clientId = randomUUID();
@@ -147,21 +154,25 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
147
154
  if (Date.now() < lockedUntil) {
148
155
  const waitSec = Math.ceil((lockedUntil - Date.now()) / 1e3);
149
156
  console.warn(`Auth: locked out, ${waitSec}s remaining`);
150
- return c.html(renderPasswordPage(code, expectedCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);
157
+ const newCsrf = randomBytes(32).toString("hex");
158
+ csrfTokens.set(code, newCsrf);
159
+ return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);
151
160
  }
152
161
  const a = Buffer.from(submittedPassword);
153
162
  const b = Buffer.from(password);
154
163
  if (a.length !== b.length || !timingSafeEqual(a, b)) {
155
164
  failedAttempts++;
156
165
  console.warn(`Auth: failed attempt ${failedAttempts} total`);
166
+ const newCsrf = randomBytes(32).toString("hex");
167
+ csrfTokens.set(code, newCsrf);
157
168
  if (failedAttempts >= MAX_FAILED_BEFORE_LOCKOUT) {
158
- lockoutCount++;
169
+ lockoutCount = Math.min(lockoutCount + 1, 10);
159
170
  const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);
160
171
  lockedUntil = Date.now() + lockoutMs;
161
172
  console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1e3}s`);
162
- return c.html(renderPasswordPage(code, expectedCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1e3)} seconds.`), 429);
173
+ return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1e3)} seconds.`), 429);
163
174
  }
164
- return c.html(renderPasswordPage(code, expectedCsrf, "Wrong password."), 401);
175
+ return c.html(renderPasswordPage(code, newCsrf, "Wrong password."), 401);
165
176
  }
166
177
  failedAttempts = 0;
167
178
  lockoutCount = 0;
@@ -179,6 +190,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
179
190
  const grantType = body["grant_type"];
180
191
  if (grantType === "authorization_code") {
181
192
  const code = body["code"];
193
+ const clientId = body["client_id"];
182
194
  const codeVerifier = body["code_verifier"];
183
195
  const redirectUri = body["redirect_uri"];
184
196
  const pending = pendingAuths.get(code);
@@ -186,6 +198,9 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
186
198
  if (pending) pendingAuths.delete(code);
187
199
  return c.json({ error: "invalid_grant" }, 400);
188
200
  }
201
+ if (clientId !== pending.clientId) {
202
+ return c.json({ error: "invalid_grant", error_description: "client_id mismatch" }, 400);
203
+ }
189
204
  if (redirectUri !== pending.redirectUri) {
190
205
  return c.json({ error: "invalid_grant", error_description: "redirect_uri mismatch" }, 400);
191
206
  }
@@ -280,6 +295,21 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
280
295
  console.error("Failed to save auth tokens:", err);
281
296
  }
282
297
  },
298
+ cleanup() {
299
+ const now = Date.now();
300
+ for (const [k, r] of tokens) {
301
+ if (r.expiresAt <= now) tokens.delete(k);
302
+ }
303
+ for (const [k, r] of refreshTokens) {
304
+ if (r.refreshExpiresAt <= now) refreshTokens.delete(k);
305
+ }
306
+ const activeClientIds = /* @__PURE__ */ new Set();
307
+ for (const r of tokens.values()) activeClientIds.add(r.clientId);
308
+ for (const r of refreshTokens.values()) activeClientIds.add(r.clientId);
309
+ for (const [k, c] of clients) {
310
+ if (!activeClientIds.has(c.clientId)) clients.delete(k);
311
+ }
312
+ },
283
313
  async loadTokens() {
284
314
  if (!persistPath) return false;
285
315
  try {
@@ -288,14 +318,15 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
288
318
  const now = Date.now();
289
319
  for (const [k, v] of Object.entries(data.tokens ?? {})) {
290
320
  const record = v;
291
- if (record.expiresAt > now) tokens.set(k, record);
321
+ if (record.accessToken && record.refreshToken && record.expiresAt > now) tokens.set(k, record);
292
322
  }
293
323
  for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {
294
324
  const record = v;
295
- if (record.refreshExpiresAt > now) refreshTokens.set(k, record);
325
+ if (record.accessToken && record.refreshToken && record.refreshExpiresAt > now) refreshTokens.set(k, record);
296
326
  }
297
327
  for (const [k, v] of Object.entries(data.clients ?? {})) {
298
- clients.set(k, v);
328
+ const client = v;
329
+ if (client.clientId && client.redirectUris) clients.set(k, client);
299
330
  }
300
331
  console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);
301
332
  return tokens.size > 0;
@@ -320,8 +351,8 @@ function renderPasswordPage(code, csrf, error) {
320
351
  <h1>Obsidian Sync MCP</h1>
321
352
  ${error ? `<p class="error">${error.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>` : "<p>Enter the server password to authorize access to your vault.</p>"}
322
353
  <form method="POST" action="/oauth/approve" autocomplete="on">
323
- <input type="hidden" name="code" value="${code}">
324
- <input type="hidden" name="csrf" value="${csrf}">
354
+ <input type="hidden" name="code" value="${code.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">
355
+ <input type="hidden" name="csrf" value="${csrf.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">
325
356
  <input type="text" name="username" id="username" value="obsidian-sync-mcp" autocomplete="username" style="position:absolute;opacity:0;width:1px;height:1px;pointer-events:none">
326
357
  <input type="password" name="password" id="password" placeholder="Password" autocomplete="current-password" autofocus required>
327
358
  <br><button type="submit">Authorize</button>
@@ -333,66 +364,161 @@ function renderPasswordPage(code, csrf, error) {
333
364
  import FlexSearch from "flexsearch";
334
365
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, chmod as chmod2 } from "fs/promises";
335
366
  import { dirname as dirname2 } from "path";
367
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, scryptSync } from "crypto";
336
368
  var MAX_RESULTS = 50;
369
+ function encrypt(text, passphrase) {
370
+ const salt = randomBytes2(16);
371
+ const key = scryptSync(passphrase, salt, 32);
372
+ const iv = randomBytes2(12);
373
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
374
+ const encrypted = Buffer.concat([cipher.update(text, "utf-8"), cipher.final()]);
375
+ const tag = cipher.getAuthTag();
376
+ return salt.toString("hex") + ":" + iv.toString("hex") + ":" + tag.toString("hex") + ":" + encrypted.toString("hex");
377
+ }
378
+ function decrypt(data, passphrase) {
379
+ const [saltHex, ivHex, tagHex, encryptedHex] = data.split(":");
380
+ const key = scryptSync(passphrase, Buffer.from(saltHex, "hex"), 32);
381
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivHex, "hex"));
382
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
383
+ return Buffer.concat([decipher.update(Buffer.from(encryptedHex, "hex")), decipher.final()]).toString("utf-8");
384
+ }
337
385
  var SearchIndex = class {
338
386
  index;
339
- contents = /* @__PURE__ */ new Map();
340
- // path -> content (for snippet extraction)
387
+ mtimes = /* @__PURE__ */ new Map();
388
+ tags = /* @__PURE__ */ new Map();
389
+ links = /* @__PURE__ */ new Map();
390
+ backlinks = /* @__PURE__ */ new Map();
391
+ knownPaths = /* @__PURE__ */ new Set();
392
+ flexSearchReady = false;
393
+ saving = false;
394
+ _since = "";
341
395
  persistPath;
342
- constructor(persistPath) {
396
+ passphrase;
397
+ constructor(persistPath, passphrase) {
343
398
  this.persistPath = persistPath ?? null;
399
+ this.passphrase = passphrase ?? null;
344
400
  this.index = new FlexSearch.Document({
345
401
  document: { id: "path", index: ["content", "path"] },
346
402
  tokenize: "forward"
347
403
  });
348
404
  }
349
- /** Try to load a persisted index from disk. Returns true if loaded. */
405
+ /** Load full index from disk (metadata + FlexSearch). */
350
406
  async loadFromDisk() {
351
407
  if (!this.persistPath) return false;
352
408
  try {
353
- const data = await readFile2(this.persistPath, "utf-8");
354
- const { contents } = JSON.parse(data);
355
- for (const [path, content] of Object.entries(contents)) {
356
- this.index.add({ path, content });
357
- this.contents.set(path, content);
409
+ let raw = await readFile2(this.persistPath, "utf-8");
410
+ if (this.passphrase) {
411
+ raw = decrypt(raw, this.passphrase);
358
412
  }
359
- console.log(`Search index loaded from disk (${this.contents.size} notes).`);
360
- return true;
413
+ const data = JSON.parse(raw);
414
+ for (const [path, mtime] of Object.entries(data.mtimes ?? {})) {
415
+ this.mtimes.set(path, mtime);
416
+ this.knownPaths.add(path);
417
+ }
418
+ for (const [path, t] of Object.entries(data.tags ?? {})) {
419
+ this.tags.set(path, t);
420
+ }
421
+ for (const [path, l] of Object.entries(data.links ?? {})) {
422
+ const targets = l;
423
+ this.links.set(path, targets);
424
+ for (const target of targets) {
425
+ const key = target.toLowerCase();
426
+ if (!this.backlinks.has(key)) this.backlinks.set(key, /* @__PURE__ */ new Set());
427
+ this.backlinks.get(key).add(path);
428
+ }
429
+ }
430
+ if (data.since) this._since = data.since;
431
+ if (data.flexsearch && data.flexsearch.length > 0) {
432
+ for (const { key, value } of data.flexsearch) {
433
+ this.index.import(key, value);
434
+ }
435
+ this.flexSearchReady = true;
436
+ }
437
+ console.log(`Search index loaded from disk (${this.knownPaths.size} notes${this.flexSearchReady ? "" : ", text index needs rebuild"}).`);
438
+ return this.knownPaths.size > 0;
361
439
  } catch {
362
440
  return false;
363
441
  }
364
442
  }
365
- /** Save the index to disk. */
443
+ /** Save full index to disk (metadata + FlexSearch). Encrypted if passphrase is set. */
366
444
  async saveToDisk() {
367
- if (!this.persistPath) return;
445
+ if (!this.persistPath || this.saving) return;
446
+ this.saving = true;
368
447
  try {
369
448
  await mkdir2(dirname2(this.persistPath), { recursive: true });
370
- const data = JSON.stringify({
371
- contents: Object.fromEntries(this.contents)
449
+ const flexChunks = [];
450
+ this.index.export((key, value) => {
451
+ if (value !== void 0) flexChunks.push({ key, value });
372
452
  });
453
+ let data = JSON.stringify({
454
+ mtimes: Object.fromEntries(this.mtimes),
455
+ tags: Object.fromEntries(this.tags),
456
+ links: Object.fromEntries(this.links),
457
+ flexsearch: flexChunks,
458
+ since: this._since
459
+ });
460
+ if (this.passphrase) {
461
+ data = encrypt(data, this.passphrase);
462
+ }
373
463
  await writeFile2(this.persistPath, data, { encoding: "utf-8", mode: 384 });
374
464
  await chmod2(this.persistPath, 384);
375
- console.log(`Search index saved to disk (${this.contents.size} notes).`);
465
+ console.log(`Search index saved to disk (${this.knownPaths.size} notes${this.passphrase ? ", encrypted" : ""}).`);
376
466
  } catch (err) {
377
467
  console.error("Failed to save search index:", err);
468
+ } finally {
469
+ this.saving = false;
378
470
  }
379
471
  }
380
472
  /** Add or update a note in the index. */
381
- update(path, content) {
382
- if (this.contents.has(path)) {
473
+ update(path, content, mtime) {
474
+ if (this.knownPaths.has(path)) {
383
475
  this.index.remove(path);
476
+ this.clearBacklinks(path);
384
477
  }
385
478
  this.index.add({ path, content });
386
- this.contents.set(path, content);
479
+ this.knownPaths.add(path);
480
+ this.flexSearchReady = true;
481
+ if (mtime !== void 0) this.mtimes.set(path, mtime);
482
+ const parsed = parseFrontmatterAndLinks(content);
483
+ if (parsed.tags.length > 0) {
484
+ this.tags.set(path, parsed.tags);
485
+ } else {
486
+ this.tags.delete(path);
487
+ }
488
+ if (parsed.links.length > 0) {
489
+ this.links.set(path, parsed.links);
490
+ for (const target of parsed.links) {
491
+ const key = target.toLowerCase();
492
+ if (!this.backlinks.has(key)) this.backlinks.set(key, /* @__PURE__ */ new Set());
493
+ this.backlinks.get(key).add(path);
494
+ }
495
+ } else {
496
+ this.links.delete(path);
497
+ }
387
498
  }
388
499
  /** Remove a note from the index. */
389
500
  remove(path) {
390
- if (this.contents.has(path)) {
501
+ if (this.knownPaths.has(path)) {
391
502
  this.index.remove(path);
392
- this.contents.delete(path);
503
+ this.knownPaths.delete(path);
504
+ this.mtimes.delete(path);
505
+ this.tags.delete(path);
506
+ this.clearBacklinks(path);
507
+ }
508
+ }
509
+ /** Remove all backlink entries where path is the source. */
510
+ clearBacklinks(path) {
511
+ const oldLinks = this.links.get(path);
512
+ if (oldLinks) {
513
+ for (const target of oldLinks) {
514
+ const key = target.toLowerCase();
515
+ this.backlinks.get(key)?.delete(path);
516
+ if (this.backlinks.get(key)?.size === 0) this.backlinks.delete(key);
517
+ }
393
518
  }
519
+ this.links.delete(path);
394
520
  }
395
- /** Search for a query. Returns paths with snippets. */
521
+ /** Search for a query. Returns matching paths (caller fetches content for snippets). */
396
522
  search(query) {
397
523
  const results = this.index.search(query, { limit: MAX_RESULTS });
398
524
  const paths = /* @__PURE__ */ new Set();
@@ -403,25 +529,73 @@ var SearchIndex = class {
403
529
  }
404
530
  }
405
531
  }
406
- const output = [];
407
- for (const path of paths) {
408
- if (output.length >= MAX_RESULTS) break;
409
- const content = this.contents.get(path);
410
- if (!content) continue;
411
- output.push({ path, snippet: extractSnippet(content, query) });
412
- }
413
- return output;
532
+ return [...paths].slice(0, MAX_RESULTS);
414
533
  }
415
534
  /** List all indexed paths, optionally filtered by folder prefix. */
416
535
  listPaths(folder) {
417
- const paths = [...this.contents.keys()].filter((p) => p.endsWith(".md"));
418
- if (folder) {
419
- return paths.filter((p) => p.startsWith(folder)).sort();
536
+ return this.listWithMtime(folder).map((n) => n.path);
537
+ }
538
+ /** List all indexed paths with mtimes, optionally filtered by folder prefix. */
539
+ listWithMtime(folder) {
540
+ const prefix = folder && !folder.endsWith("/") ? folder + "/" : folder;
541
+ const entries = [...this.knownPaths].filter((p) => p.endsWith(".md")).filter((p) => !prefix || p.startsWith(prefix)).map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));
542
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
543
+ }
544
+ /** Whether the FlexSearch index needs rebuilding (has metadata but no text index). */
545
+ get needsRebuild() {
546
+ return this.knownPaths.size > 0 && !this.flexSearchReady;
547
+ }
548
+ /** Get mtime for a path. */
549
+ getMtime(path) {
550
+ return this.mtimes.get(path) ?? 0;
551
+ }
552
+ /** Get tags for a path. */
553
+ getTags(path) {
554
+ return this.tags.get(path) ?? [];
555
+ }
556
+ /** Get outgoing links for a path. */
557
+ getLinks(path) {
558
+ return this.links.get(path) ?? [];
559
+ }
560
+ /** Get backlinks for a path (notes that link to it). Case-insensitive, matches by full path or filename. */
561
+ getBacklinks(path) {
562
+ const results = /* @__PURE__ */ new Set();
563
+ const withMd = (path.endsWith(".md") ? path : path + ".md").toLowerCase();
564
+ const withoutMd = (path.endsWith(".md") ? path.slice(0, -3) : path).toLowerCase();
565
+ const nameOnly = withoutMd.includes("/") ? withoutMd.slice(withoutMd.lastIndexOf("/") + 1) : withoutMd;
566
+ for (const target of [withMd, withoutMd, nameOnly]) {
567
+ const sources = this.backlinks.get(target);
568
+ if (sources) {
569
+ for (const s of sources) results.add(s);
570
+ }
420
571
  }
421
- return paths.sort();
572
+ return [...results].sort();
573
+ }
574
+ /** List all tags across the vault with counts. */
575
+ listAllTags() {
576
+ const counts = /* @__PURE__ */ new Map();
577
+ for (const tags of this.tags.values()) {
578
+ for (const t of tags) {
579
+ counts.set(t, (counts.get(t) ?? 0) + 1);
580
+ }
581
+ }
582
+ return [...counts.entries()].map(([tag, count]) => ({ tag, count })).sort((a, b) => b.count - a.count);
583
+ }
584
+ /** Clear all index data (for full rebuild after DB nuke). */
585
+ clear() {
586
+ const paths = Array.from(this.knownPaths);
587
+ for (const p of paths) this.remove(p);
588
+ this._since = "";
589
+ this.flexSearchReady = false;
590
+ }
591
+ get since() {
592
+ return this._since;
593
+ }
594
+ set since(value) {
595
+ this._since = value;
422
596
  }
423
597
  get size() {
424
- return this.contents.size;
598
+ return this.knownPaths.size;
425
599
  }
426
600
  };
427
601
 
@@ -459,7 +633,7 @@ ${content}`;
459
633
  });
460
634
  server2.addTool({
461
635
  name: "write_note",
462
- description: "Write or update a note in the Obsidian vault. Creates the note if it doesn't exist, overwrites if it does.",
636
+ description: "Write or update a note in the Obsidian vault. Creates the note if it doesn't exist. Replaces the entire content if it does \u2014 read first if you need to preserve existing content.",
463
637
  parameters: z.object({
464
638
  path: z.string().describe("Vault-relative path to the note, e.g. 'daily/2026-03-23.md'"),
465
639
  content: z.string().describe("Full markdown content for the note")
@@ -469,7 +643,7 @@ ${content}`;
469
643
  if (!ok) {
470
644
  return `Failed to write note: ${path}`;
471
645
  }
472
- searchIndex2.update(path, content);
646
+ searchIndex2.update(path, content, Date.now());
473
647
  const deepLink = makeDeepLink(vaultName, path);
474
648
  return `Note saved: ${path}
475
649
  [Open in Obsidian](${deepLink})`;
@@ -477,50 +651,177 @@ ${content}`;
477
651
  });
478
652
  server2.addTool({
479
653
  name: "list_notes",
480
- description: "List all markdown notes in the vault, optionally filtered to a folder.",
654
+ description: "List markdown notes in the vault with modification timestamps. Examples: list_notes(sort_by='modified', limit=10) for 10 most recent notes. list_notes(modified_after='2026-03-25', sort_by='modified') for today's changes. list_notes(folder='daily') for a specific folder. list_notes(tag='project') for notes with a specific tag. Returns up to 100 notes by default.",
481
655
  parameters: z.object({
482
- folder: z.string().optional().describe("Folder to filter by, e.g. 'daily/' or 'projects/'. Omit for all notes.")
656
+ folder: z.string().optional().describe("Folder to filter by, e.g. 'daily' or 'projects'. Omit for all notes."),
657
+ tag: z.string().optional().describe("Filter by tag, e.g. 'project' or 'daily'. Use list_tags to discover available tags."),
658
+ sort_by: z.enum(["name", "modified"]).optional().describe("Sort order: 'name' (default) or 'modified' (most recent first)."),
659
+ modified_after: z.string().optional().describe("Only include notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'."),
660
+ limit: z.number().optional().describe("Max number of notes to return. Default 100.")
483
661
  }),
484
- execute: async ({ folder }) => {
485
- let notes = searchIndex2.listPaths(folder);
662
+ execute: async ({ folder, tag, sort_by, modified_after, limit }) => {
663
+ let notes = searchIndex2.listWithMtime(folder);
486
664
  if (notes.length === 0) {
487
- notes = await vault2.listNotes(folder);
665
+ notes = await vault2.listNotesWithMtime(folder);
666
+ }
667
+ if (tag) {
668
+ notes = notes.filter((n) => searchIndex2.getTags(n.path).includes(tag));
669
+ }
670
+ if (modified_after) {
671
+ const cutoff = new Date(modified_after).getTime();
672
+ if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;
673
+ notes = notes.filter((n) => n.mtime >= cutoff);
488
674
  }
489
675
  if (notes.length === 0) {
490
676
  return folder ? `No notes found in folder: ${folder}` : "Vault is empty.";
491
677
  }
678
+ if (sort_by === "modified") {
679
+ notes.sort((a, b) => b.mtime - a.mtime);
680
+ }
681
+ const cap = limit ?? 100;
492
682
  const total = notes.length;
493
- const capped = notes.slice(0, 500);
494
- const lines = capped.map((p) => {
495
- const deepLink = makeDeepLink(vaultName, p);
496
- return `- [${p}](${deepLink})`;
683
+ const capped = notes.slice(0, cap);
684
+ const lines = capped.map((n) => {
685
+ const deepLink = makeDeepLink(vaultName, n.path);
686
+ const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : "";
687
+ return `- ${date} [${n.path}](${deepLink})`;
497
688
  });
498
- if (total > 500) {
689
+ if (total > cap) {
499
690
  lines.push(`
500
- ... and ${total - 500} more. Use a folder filter to narrow results.`);
691
+ ... and ${total - cap} more. Use a folder filter or limit to narrow results.`);
501
692
  }
502
693
  return lines.join("\n");
503
694
  }
504
695
  });
696
+ server2.addTool({
697
+ name: "list_folders",
698
+ 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.",
699
+ parameters: z.object({}),
700
+ execute: async () => {
701
+ let paths = searchIndex2.listPaths();
702
+ if (paths.length === 0) {
703
+ paths = await vault2.listNotes();
704
+ }
705
+ const folders = /* @__PURE__ */ new Map();
706
+ for (const p of paths) {
707
+ const lastSlash = p.lastIndexOf("/");
708
+ if (lastSlash === -1) {
709
+ folders.set("(root)", (folders.get("(root)") ?? 0) + 1);
710
+ } else {
711
+ const folder = p.slice(0, lastSlash);
712
+ folders.set(folder, (folders.get(folder) ?? 0) + 1);
713
+ let parent = folder;
714
+ while (parent.includes("/")) {
715
+ parent = parent.slice(0, parent.lastIndexOf("/"));
716
+ if (!folders.has(parent)) folders.set(parent, 0);
717
+ }
718
+ }
719
+ }
720
+ if (folders.size === 0) {
721
+ return "Vault is empty.";
722
+ }
723
+ const sorted = [...folders.entries()].sort((a, b) => a[0].localeCompare(b[0]));
724
+ return sorted.map(([f, count]) => `- ${f} (${count} notes)`).join("\n");
725
+ }
726
+ });
727
+ server2.addTool({
728
+ name: "list_tags",
729
+ description: "List all tags used in the vault, sorted by frequency. Use this to discover tags before filtering with list_notes or search_vault.",
730
+ parameters: z.object({}),
731
+ execute: async () => {
732
+ const tags = searchIndex2.listAllTags();
733
+ if (tags.length === 0) {
734
+ return "No tags found in the vault.";
735
+ }
736
+ return tags.map(({ tag, count }) => `- #${tag} (${count} notes)`).join("\n");
737
+ }
738
+ });
505
739
  server2.addTool({
506
740
  name: "search_vault",
507
- description: "Search for a text query across all notes in the vault. Returns matching notes with snippets.",
741
+ description: "Full-text search across all notes (matches words, not substrings). Returns matching paths. Use modified_after to search only recent notes. Use tag to filter by tag. Set include_snippets=true to include surrounding content for each match.",
508
742
  parameters: z.object({
509
- query: z.string().describe("Text to search for (case-insensitive)")
743
+ query: z.string().describe("Text to search for (case-insensitive)"),
744
+ tag: z.string().optional().describe("Filter results by tag, e.g. 'project'. Use list_tags to discover available tags."),
745
+ modified_after: z.string().optional().describe("Only include notes modified after this ISO date, e.g. '2026-03-25'."),
746
+ include_snippets: z.boolean().optional().describe("Fetch content snippets for each result. Default false (paths only).")
510
747
  }),
511
- execute: async ({ query }) => {
512
- const results = searchIndex2.search(query);
513
- if (results.length === 0) {
748
+ execute: async ({ query, tag, modified_after, include_snippets }) => {
749
+ let paths = searchIndex2.search(query);
750
+ if (tag) {
751
+ paths = paths.filter((p) => searchIndex2.getTags(p).includes(tag));
752
+ }
753
+ if (modified_after) {
754
+ const cutoff = new Date(modified_after).getTime();
755
+ if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;
756
+ paths = paths.filter((p) => searchIndex2.getMtime(p) >= cutoff);
757
+ }
758
+ if (paths.length === 0) {
514
759
  return `No results for: ${query}`;
515
760
  }
516
- const lines = results.map((r) => {
517
- const deepLink = makeDeepLink(vaultName, r.path);
518
- return `### [${r.path}](${deepLink})
761
+ const lines = [];
762
+ for (const path of paths) {
763
+ const deepLink = makeDeepLink(vaultName, path);
764
+ if (include_snippets) {
765
+ const content = await vault2.readNote(path);
766
+ const snippet = content ? extractSnippet(content, query) : "";
767
+ lines.push(`### [${path}](${deepLink})
519
768
  \`\`\`
520
- ${r.snippet}
521
- \`\`\``;
522
- });
523
- return lines.join("\n\n");
769
+ ${snippet}
770
+ \`\`\``);
771
+ } else {
772
+ lines.push(`- [${path}](${deepLink})`);
773
+ }
774
+ }
775
+ return lines.join(include_snippets ? "\n\n" : "\n");
776
+ }
777
+ });
778
+ server2.addTool({
779
+ name: "edit_note",
780
+ description: "Edit a note without rewriting it. Use 'append' (default) to add content to the end, 'prepend' to add after frontmatter, or 'replace' to swap old_text with new content. For replace, the old_text must match exactly once.",
781
+ parameters: z.object({
782
+ path: z.string().describe("Vault-relative path to the note, e.g. 'daily/2026-03-25.md'"),
783
+ content: z.string().describe("Text to append, prepend, or use as replacement for old_text"),
784
+ operation: z.enum(["append", "prepend", "replace"]).optional().describe("'append' (default): add to end. 'prepend': add after frontmatter. 'replace': swap old_text with content."),
785
+ old_text: z.string().optional().describe("Required for replace operation. Exact text to find and replace. Must match exactly once.")
786
+ }),
787
+ execute: async ({ path, content: newContent, operation, old_text }) => {
788
+ const existing = await vault2.readNote(path);
789
+ if (existing === null) {
790
+ return `Note not found: ${path}`;
791
+ }
792
+ let updated;
793
+ const op = operation ?? "append";
794
+ if (op === "replace") {
795
+ if (!old_text) {
796
+ return "old_text is required for replace operation.";
797
+ }
798
+ const idx = existing.indexOf(old_text);
799
+ if (idx === -1) {
800
+ return "old_text not found in note.";
801
+ }
802
+ if (existing.indexOf(old_text, idx + 1) !== -1) {
803
+ return "old_text matches multiple times. Provide a longer, unique string.";
804
+ }
805
+ updated = existing.slice(0, idx) + newContent + existing.slice(idx + old_text.length);
806
+ } else if (op === "prepend") {
807
+ const fmMatch = existing.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);
808
+ if (fmMatch) {
809
+ const afterFm = fmMatch[0].length;
810
+ updated = existing.slice(0, afterFm) + newContent + "\n" + existing.slice(afterFm);
811
+ } else {
812
+ updated = newContent + "\n" + existing;
813
+ }
814
+ } else {
815
+ updated = existing.endsWith("\n") ? existing + newContent : existing + "\n" + newContent;
816
+ }
817
+ const ok = await vault2.writeNote(path, updated);
818
+ if (!ok) {
819
+ return `Failed to edit note: ${path}`;
820
+ }
821
+ searchIndex2.update(path, updated, Date.now());
822
+ const deepLink = makeDeepLink(vaultName, path);
823
+ return `Note edited (${op}): ${path}
824
+ [Open in Obsidian](${deepLink})`;
524
825
  }
525
826
  });
526
827
  server2.addTool({
@@ -549,7 +850,7 @@ ${r.snippet}
549
850
  return `Failed to move: ${from} \u2192 ${to}`;
550
851
  }
551
852
  searchIndex2.remove(from);
552
- if (content) searchIndex2.update(to, content);
853
+ if (content) searchIndex2.update(to, content, Date.now());
553
854
  const deepLink = makeDeepLink(vaultName, to);
554
855
  return `Moved: ${from} \u2192 ${to}
555
856
  [Open in Obsidian](${deepLink})`;
@@ -557,7 +858,7 @@ ${r.snippet}
557
858
  });
558
859
  server2.addTool({
559
860
  name: "get_note_metadata",
560
- description: "Get metadata about a note without reading its full content. Returns frontmatter properties, tags (both frontmatter and inline #tags), internal links ([[wikilinks]] and markdown links), file size, and timestamps.",
861
+ description: "Get metadata about a note without reading its full content. Returns frontmatter, tags, outgoing links, backlinks (notes that link to this one), size, and timestamps. Use this to navigate the knowledge graph.",
561
862
  parameters: z.object({
562
863
  path: z.string().describe("Vault-relative path to the note, e.g. 'projects/my-project.md'")
563
864
  }),
@@ -586,7 +887,12 @@ Tags: ${meta.tags.map((t) => `#${t}`).join(", ")}`);
586
887
  }
587
888
  if (meta.links.length > 0) {
588
889
  lines.push(`
589
- Links: ${meta.links.join(", ")}`);
890
+ Outgoing links: ${meta.links.join(", ")}`);
891
+ }
892
+ const backlinks = searchIndex2.getBacklinks(path);
893
+ if (backlinks.length > 0) {
894
+ lines.push(`
895
+ Backlinks: ${backlinks.join(", ")}`);
590
896
  }
591
897
  lines.push(`
592
898
  [Open in Obsidian](${deepLink})`);
@@ -596,10 +902,18 @@ Links: ${meta.links.join(", ")}`);
596
902
  }
597
903
 
598
904
  // src/main.ts
905
+ var debugLogging = process.env.LOG_LEVEL === "debug";
906
+ setGlobalLogFunction((message, level = LEVEL_INFO) => {
907
+ if (level < LEVEL_INFO) return;
908
+ if (!debugLogging && typeof message === "string") {
909
+ if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge|No replicator|\[ReplicatorService\]):/.test(message)) return;
910
+ }
911
+ console.log(message);
912
+ });
599
913
  var VAULT_PATH = process.env.VAULT_PATH;
600
914
  var COUCHDB_URL = process.env.COUCHDB_URL;
601
915
  var COUCHDB_USER = process.env.COUCHDB_USER ?? "admin";
602
- var COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD ?? "password";
916
+ var COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;
603
917
  var COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? "obsidian";
604
918
  var COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || void 0;
605
919
  var VAULT_NAME = process.env.VAULT_NAME ?? "MyVault";
@@ -608,11 +922,15 @@ var BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;
608
922
  var AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;
609
923
  var vault;
610
924
  if (VAULT_PATH) {
611
- const { LocalVault } = await import("./vault-local-3C2JVBRO.js");
925
+ const { LocalVault } = await import("./vault-local-NFQ7FPNH.js");
612
926
  vault = new LocalVault(VAULT_PATH);
613
927
  console.log(`Local mode: ${VAULT_PATH}`);
614
928
  } else if (COUCHDB_URL) {
615
- const { Vault } = await import("./vault-J2V2D3HA.js");
929
+ if (!COUCHDB_PASSWORD) {
930
+ console.error("COUCHDB_PASSWORD is required in remote mode.");
931
+ process.exit(1);
932
+ }
933
+ const { Vault } = await import("./vault-JP7SG3VJ.js");
616
934
  vault = new Vault({
617
935
  couchdbUrl: COUCHDB_URL,
618
936
  couchdbUser: COUCHDB_USER,
@@ -628,50 +946,125 @@ if (VAULT_PATH) {
628
946
  await vault.init();
629
947
  console.log("Vault ready.");
630
948
  var baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? "/tmp", ".obsidian-mcp");
631
- var vaultId = createHash2("sha256").update(VAULT_PATH ?? COUCHDB_URL ?? "default").digest("hex").slice(0, 12);
949
+ var vaultId = createHash2("sha256").update(VAULT_NAME).digest("hex").slice(0, 12);
632
950
  var dataDir = join(baseDataDir, vaultId);
633
951
  var indexPath = join(dataDir, "search-index.json");
634
- var searchIndex = new SearchIndex(indexPath);
635
- var loaded = await searchIndex.loadFromDisk();
636
- if (!loaded) {
637
- const start = performance.now();
638
- const notes = await vault.listNotes();
639
- console.log(`Building search index (${notes.length} notes)...`);
640
- for (let i = 0; i < notes.length; i++) {
641
- const content = await vault.readNote(notes[i]);
642
- if (content) searchIndex.update(notes[i], content);
643
- if (notes.length > 100 && (i + 1) % 500 === 0) {
644
- console.log(` indexed ${i + 1}/${notes.length}...`);
952
+ var searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);
953
+ var hadPersistedIndex = await searchIndex.loadFromDisk();
954
+ if (debugLogging && hadPersistedIndex) {
955
+ console.log(`[debug] Persisted index: ${searchIndex.size} notes, FlexSearch ready: ${!searchIndex.needsRebuild}, since: ${searchIndex.since || "(none)"}`);
956
+ }
957
+ var start = performance.now();
958
+ if (COUCHDB_URL && vault.catchUp) {
959
+ const changeCallback = (path, content, mtime) => {
960
+ if (content) {
961
+ searchIndex.update(path, content, mtime);
962
+ } else {
963
+ searchIndex.remove(path);
645
964
  }
965
+ };
966
+ let since = searchIndex.since || "0";
967
+ if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);
968
+ let changes = 0;
969
+ try {
970
+ const countingCallback = (path, content, mtime) => {
971
+ changes++;
972
+ if (debugLogging) console.log(`[debug] Change: ${path} ${content ? "(update)" : "(delete)"}`);
973
+ changeCallback(path, content, mtime);
974
+ };
975
+ const newSince = await vault.catchUp(since, countingCallback);
976
+ searchIndex.since = newSince;
977
+ } catch (err) {
978
+ console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);
979
+ searchIndex.clear();
980
+ changes = 0;
981
+ const newSince = await vault.catchUp("0", (path, content, mtime) => {
982
+ changes++;
983
+ changeCallback(path, content, mtime);
984
+ });
985
+ searchIndex.since = newSince;
986
+ }
987
+ if (changes > 0) {
988
+ console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1e3).toFixed(1)}s (${searchIndex.size} notes).`);
989
+ } else {
990
+ console.log(`Search index up to date (${searchIndex.size} notes).`);
991
+ }
992
+ } else if (VAULT_PATH) {
993
+ const notesWithMtime = await vault.listNotesWithMtime();
994
+ if (debugLogging) console.log(`[debug] Vault has ${notesWithMtime.length} notes`);
995
+ if (hadPersistedIndex && !searchIndex.needsRebuild && notesWithMtime.length > 0) {
996
+ const vaultPaths = new Set(notesWithMtime.map((n) => n.path));
997
+ const stale = searchIndex.listPaths().filter((p) => !vaultPaths.has(p));
998
+ for (const p of stale) {
999
+ if (debugLogging) console.log(`[debug] Removing stale: ${p}`);
1000
+ searchIndex.remove(p);
1001
+ }
1002
+ const toRead = notesWithMtime.filter((n) => n.mtime > searchIndex.getMtime(n.path));
1003
+ if (toRead.length > 0 || stale.length > 0) {
1004
+ for (const { path, mtime } of toRead) {
1005
+ if (debugLogging) console.log(`[debug] Reading changed: ${path}`);
1006
+ const content = await vault.readNote(path);
1007
+ if (content) searchIndex.update(path, content, mtime);
1008
+ }
1009
+ console.log(`Search index synced in ${((performance.now() - start) / 1e3).toFixed(1)}s: ${toRead.length} updated, ${stale.length} removed, ${notesWithMtime.length - toRead.length - stale.length} unchanged.`);
1010
+ } else {
1011
+ console.log(`Search index up to date (${searchIndex.size} notes).`);
1012
+ }
1013
+ } else if (notesWithMtime.length > 0) {
1014
+ if (debugLogging) console.log(`[debug] Full rebuild (persisted: ${hadPersistedIndex}, flexsearch ready: ${!searchIndex.needsRebuild})`);
1015
+ console.log(`Building search index (${notesWithMtime.length} notes)...`);
1016
+ for (let i = 0; i < notesWithMtime.length; i++) {
1017
+ const { path, mtime } = notesWithMtime[i];
1018
+ const content = await vault.readNote(path);
1019
+ if (content) searchIndex.update(path, content, mtime);
1020
+ if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {
1021
+ console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);
1022
+ }
1023
+ }
1024
+ console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1e3).toFixed(1)}s`);
646
1025
  }
647
- console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1e3).toFixed(1)}s`);
648
1026
  }
649
1027
  var fsWatcher = null;
650
1028
  if (VAULT_PATH) {
651
- fsWatcher = watch(VAULT_PATH, { recursive: true }, async (event, filename) => {
1029
+ const pending = /* @__PURE__ */ new Map();
1030
+ fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {
652
1031
  if (!filename || !filename.endsWith(".md")) return;
653
1032
  const notePath = filename.replace(/\\/g, "/");
1033
+ if (notePath.startsWith(".obsidian/") || notePath.includes("/.obsidian/")) return;
1034
+ if (pending.has(notePath)) clearTimeout(pending.get(notePath));
1035
+ pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));
1036
+ });
1037
+ async function handleFileChange(notePath) {
1038
+ pending.delete(notePath);
654
1039
  try {
655
- const content = await readFile3(join(VAULT_PATH, notePath), "utf-8");
656
- searchIndex.update(notePath, content);
1040
+ const content = await vault.readNote(notePath);
1041
+ if (content !== null) {
1042
+ const s = await stat(join(VAULT_PATH, notePath));
1043
+ searchIndex.update(notePath, content, s.mtimeMs);
1044
+ } else {
1045
+ searchIndex.remove(notePath);
1046
+ }
657
1047
  } catch {
658
1048
  searchIndex.remove(notePath);
659
1049
  }
660
- });
1050
+ }
661
1051
  console.log("Watching vault for external changes.");
662
1052
  } else if (COUCHDB_URL && vault.watchChanges) {
663
- vault.watchChanges((path, content) => {
1053
+ vault.watchChanges((path, content, mtime, seq) => {
664
1054
  if (content) {
665
- searchIndex.update(path, content);
1055
+ if (debugLogging) console.log(`[debug] CouchDB change: ${path} (mtime: ${mtime})`);
1056
+ searchIndex.update(path, content, mtime);
666
1057
  } else {
1058
+ if (debugLogging) console.log(`[debug] CouchDB delete: ${path}`);
667
1059
  searchIndex.remove(path);
668
1060
  }
1061
+ if (seq) searchIndex.since = String(seq);
669
1062
  });
670
1063
  console.log("Watching CouchDB for LiveSync changes.");
671
1064
  }
672
1065
  var serverOptions = {
673
1066
  name: "obsidian-sync-mcp",
674
- version: "0.3.0",
1067
+ version: "0.4.0",
675
1068
  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."
676
1069
  };
677
1070
  var auth = null;
@@ -689,7 +1082,12 @@ if (AUTH_TOKEN) {
689
1082
  };
690
1083
  console.log("Auth enabled (password-gated OAuth).");
691
1084
  } else {
692
- console.log("Auth disabled (set MCP_AUTH_TOKEN to enable).");
1085
+ const host = process.env.HOST ?? "0.0.0.0";
1086
+ if (host === "0.0.0.0") {
1087
+ console.warn("WARNING: No authentication and listening on all interfaces. Set MCP_AUTH_TOKEN or HOST=127.0.0.1.");
1088
+ } else {
1089
+ console.log("Auth disabled (set MCP_AUTH_TOKEN to enable).");
1090
+ }
693
1091
  }
694
1092
  var server = new FastMCP(serverOptions);
695
1093
  if (AUTH_TOKEN) {
@@ -710,7 +1108,10 @@ process.on("SIGTERM", shutdown);
710
1108
  process.on("SIGINT", shutdown);
711
1109
  setInterval(async () => {
712
1110
  await searchIndex.saveToDisk();
713
- if (auth) await auth.saveTokens();
1111
+ if (auth) {
1112
+ auth.cleanup();
1113
+ await auth.saveTokens();
1114
+ }
714
1115
  }, 5 * 60 * 1e3).unref();
715
1116
  server.start({
716
1117
  transportType: "httpStream",