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