obsidian-sync-mcp 0.1.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/LICENSE +21 -0
- package/README.md +360 -0
- package/dist/chunk-26MFONZB.js +20 -0
- package/dist/chunk-26MFONZB.js.map +1 -0
- package/dist/chunk-ZJJW3NJ5.js +43 -0
- package/dist/chunk-ZJJW3NJ5.js.map +1 -0
- package/dist/main.js +703 -0
- package/dist/main.js.map +1 -0
- package/dist/vault-IGTFVPKN.js +4890 -0
- package/dist/vault-IGTFVPKN.js.map +1 -0
- package/dist/vault-local-65IVVIHQ.js +135 -0
- package/dist/vault-local-65IVVIHQ.js.map +1 -0
- package/package.json +63 -0
package/dist/main.js
ADDED
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
// Node polyfills for livesync-commonlib browser globals
|
|
2
|
+
if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
|
|
3
|
+
import "./chunk-26MFONZB.js";
|
|
4
|
+
|
|
5
|
+
// src/main.ts
|
|
6
|
+
import { FastMCP } from "fastmcp";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { join } from "path";
|
|
9
|
+
import { timingSafeEqual as timingSafeEqual2, createHash as createHash2 } from "crypto";
|
|
10
|
+
import { watch } from "fs";
|
|
11
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
12
|
+
|
|
13
|
+
// src/deeplink.ts
|
|
14
|
+
function makeDeepLink(vaultName, notePath) {
|
|
15
|
+
const cleanPath = notePath.replace(/\.md$/, "");
|
|
16
|
+
const encodedVault = encodeURIComponent(vaultName);
|
|
17
|
+
const encodedPath = encodeURIComponent(cleanPath);
|
|
18
|
+
return `obsidian://open?vault=${encodedVault}&file=${encodedPath}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/auth.ts
|
|
22
|
+
import { randomUUID, randomBytes, createHash, timingSafeEqual } from "crypto";
|
|
23
|
+
import { readFile, writeFile, mkdir, chmod } from "fs/promises";
|
|
24
|
+
import { dirname } from "path";
|
|
25
|
+
var TOKEN_EXPIRY_MS = 3600 * 1e3;
|
|
26
|
+
var DEFAULT_REFRESH_DAYS = 14;
|
|
27
|
+
var REFRESH_EXPIRY_MS = parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) * 24 * 3600 * 1e3;
|
|
28
|
+
var MAX_FAILED_BEFORE_LOCKOUT = 5;
|
|
29
|
+
var BASE_LOCKOUT_MS = 5 * 1e3;
|
|
30
|
+
var MAX_CLIENTS = 100;
|
|
31
|
+
var MAX_PENDING = 100;
|
|
32
|
+
var PENDING_TTL_MS = 10 * 60 * 1e3;
|
|
33
|
+
function mountPasswordAuth(app, baseUrl, password, persistPath) {
|
|
34
|
+
const pendingAuths = /* @__PURE__ */ new Map();
|
|
35
|
+
const csrfTokens = /* @__PURE__ */ new Map();
|
|
36
|
+
const tokens = /* @__PURE__ */ new Map();
|
|
37
|
+
const refreshTokens = /* @__PURE__ */ new Map();
|
|
38
|
+
const clients = /* @__PURE__ */ new Map();
|
|
39
|
+
function cleanupPending() {
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
for (const [code, pending] of pendingAuths) {
|
|
42
|
+
if (now - pending.createdAt > PENDING_TTL_MS) {
|
|
43
|
+
pendingAuths.delete(code);
|
|
44
|
+
csrfTokens.delete(code);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
let failedAttempts = 0;
|
|
49
|
+
let lockoutCount = 0;
|
|
50
|
+
let lockedUntil = 0;
|
|
51
|
+
if (!baseUrl.startsWith("https://") && !baseUrl.includes("localhost")) {
|
|
52
|
+
console.warn("WARNING: BASE_URL is not HTTPS. OAuth tokens will be sent in cleartext. Use a tunnel (cloudflared, tailscale, ngrok) to provide TLS.");
|
|
53
|
+
}
|
|
54
|
+
app.get("/.well-known/oauth-protected-resource", (c) => {
|
|
55
|
+
return c.json({
|
|
56
|
+
resource: baseUrl,
|
|
57
|
+
authorization_servers: [baseUrl],
|
|
58
|
+
scopes_supported: ["mcp"]
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
app.get("/.well-known/oauth-authorization-server", (c) => {
|
|
62
|
+
return c.json({
|
|
63
|
+
issuer: baseUrl,
|
|
64
|
+
authorization_endpoint: `${baseUrl}/oauth/authorize`,
|
|
65
|
+
token_endpoint: `${baseUrl}/oauth/token`,
|
|
66
|
+
registration_endpoint: `${baseUrl}/oauth/register`,
|
|
67
|
+
response_types_supported: ["code"],
|
|
68
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
69
|
+
code_challenge_methods_supported: ["S256"],
|
|
70
|
+
token_endpoint_auth_methods_supported: ["client_secret_post", "none"],
|
|
71
|
+
scopes_supported: ["mcp"]
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
app.post("/oauth/register", async (c) => {
|
|
75
|
+
if (clients.size >= MAX_CLIENTS) {
|
|
76
|
+
return c.json({ error: "too_many_clients" }, 429);
|
|
77
|
+
}
|
|
78
|
+
const body = await c.req.json();
|
|
79
|
+
const clientId = randomUUID();
|
|
80
|
+
const clientSecret = randomBytes(32).toString("hex");
|
|
81
|
+
const client = {
|
|
82
|
+
clientId,
|
|
83
|
+
clientSecret,
|
|
84
|
+
redirectUris: body.redirect_uris || [],
|
|
85
|
+
clientName: body.client_name
|
|
86
|
+
};
|
|
87
|
+
clients.set(clientId, client);
|
|
88
|
+
return c.json({
|
|
89
|
+
client_id: clientId,
|
|
90
|
+
client_secret: clientSecret,
|
|
91
|
+
redirect_uris: client.redirectUris,
|
|
92
|
+
client_name: client.clientName,
|
|
93
|
+
token_endpoint_auth_method: "client_secret_post"
|
|
94
|
+
}, 201);
|
|
95
|
+
});
|
|
96
|
+
app.get("/oauth/authorize", (c) => {
|
|
97
|
+
const clientId = c.req.query("client_id") ?? "";
|
|
98
|
+
const redirectUri = c.req.query("redirect_uri") ?? "";
|
|
99
|
+
const codeChallenge = c.req.query("code_challenge") ?? "";
|
|
100
|
+
const codeChallengeMethod = c.req.query("code_challenge_method") ?? "S256";
|
|
101
|
+
const state = c.req.query("state") ?? "";
|
|
102
|
+
const client = clients.get(clientId);
|
|
103
|
+
if (!client) {
|
|
104
|
+
return c.text("Unknown client", 400);
|
|
105
|
+
}
|
|
106
|
+
if (client.redirectUris.length > 0 && !client.redirectUris.includes(redirectUri)) {
|
|
107
|
+
return c.text("Invalid redirect URI", 400);
|
|
108
|
+
}
|
|
109
|
+
if (codeChallengeMethod !== "S256" || !codeChallenge) {
|
|
110
|
+
return c.text("PKCE with S256 is required", 400);
|
|
111
|
+
}
|
|
112
|
+
cleanupPending();
|
|
113
|
+
if (pendingAuths.size >= MAX_PENDING) {
|
|
114
|
+
return c.text("Too many pending authorizations", 429);
|
|
115
|
+
}
|
|
116
|
+
const code = randomBytes(32).toString("hex");
|
|
117
|
+
pendingAuths.set(code, {
|
|
118
|
+
clientId,
|
|
119
|
+
redirectUri,
|
|
120
|
+
codeChallenge,
|
|
121
|
+
codeChallengeMethod,
|
|
122
|
+
state,
|
|
123
|
+
code,
|
|
124
|
+
createdAt: Date.now()
|
|
125
|
+
});
|
|
126
|
+
const csrf = randomBytes(32).toString("hex");
|
|
127
|
+
csrfTokens.set(code, csrf);
|
|
128
|
+
return c.html(renderPasswordPage(code, csrf));
|
|
129
|
+
});
|
|
130
|
+
app.post("/oauth/approve", async (c) => {
|
|
131
|
+
const body = await c.req.parseBody();
|
|
132
|
+
const code = body["code"];
|
|
133
|
+
const submittedCsrf = body["csrf"];
|
|
134
|
+
const submittedPassword = body["password"];
|
|
135
|
+
const pending = pendingAuths.get(code);
|
|
136
|
+
const expectedCsrf = csrfTokens.get(code);
|
|
137
|
+
if (!pending || !expectedCsrf) {
|
|
138
|
+
return c.html("<p>Invalid or expired authorization request.</p>", 400);
|
|
139
|
+
}
|
|
140
|
+
const csrfA = Buffer.from(submittedCsrf ?? "");
|
|
141
|
+
const csrfB = Buffer.from(expectedCsrf);
|
|
142
|
+
if (csrfA.length !== csrfB.length || !timingSafeEqual(csrfA, csrfB)) {
|
|
143
|
+
return c.html("<p>Invalid request.</p>", 403);
|
|
144
|
+
}
|
|
145
|
+
if (Date.now() < lockedUntil) {
|
|
146
|
+
const waitSec = Math.ceil((lockedUntil - Date.now()) / 1e3);
|
|
147
|
+
console.warn(`Auth: locked out, ${waitSec}s remaining`);
|
|
148
|
+
return c.html(renderPasswordPage(code, expectedCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);
|
|
149
|
+
}
|
|
150
|
+
const a = Buffer.from(submittedPassword);
|
|
151
|
+
const b = Buffer.from(password);
|
|
152
|
+
if (a.length !== b.length || !timingSafeEqual(a, b)) {
|
|
153
|
+
failedAttempts++;
|
|
154
|
+
console.warn(`Auth: failed attempt ${failedAttempts} total`);
|
|
155
|
+
if (failedAttempts >= MAX_FAILED_BEFORE_LOCKOUT) {
|
|
156
|
+
lockoutCount++;
|
|
157
|
+
const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);
|
|
158
|
+
lockedUntil = Date.now() + lockoutMs;
|
|
159
|
+
console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1e3}s`);
|
|
160
|
+
return c.html(renderPasswordPage(code, expectedCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1e3)} seconds.`), 429);
|
|
161
|
+
}
|
|
162
|
+
return c.html(renderPasswordPage(code, expectedCsrf, "Wrong password."), 401);
|
|
163
|
+
}
|
|
164
|
+
failedAttempts = 0;
|
|
165
|
+
lockoutCount = 0;
|
|
166
|
+
lockedUntil = 0;
|
|
167
|
+
csrfTokens.delete(code);
|
|
168
|
+
console.log("Auth: password accepted, issuing authorization code.");
|
|
169
|
+
const url = new URL(pending.redirectUri);
|
|
170
|
+
url.searchParams.set("code", code);
|
|
171
|
+
if (pending.state) url.searchParams.set("state", pending.state);
|
|
172
|
+
const redirectUrl = url.toString();
|
|
173
|
+
return c.redirect(redirectUrl);
|
|
174
|
+
});
|
|
175
|
+
app.post("/oauth/token", async (c) => {
|
|
176
|
+
const body = await c.req.parseBody();
|
|
177
|
+
const grantType = body["grant_type"];
|
|
178
|
+
if (grantType === "authorization_code") {
|
|
179
|
+
const code = body["code"];
|
|
180
|
+
const codeVerifier = body["code_verifier"];
|
|
181
|
+
const redirectUri = body["redirect_uri"];
|
|
182
|
+
const pending = pendingAuths.get(code);
|
|
183
|
+
if (!pending) {
|
|
184
|
+
return c.json({ error: "invalid_grant" }, 400);
|
|
185
|
+
}
|
|
186
|
+
if (redirectUri !== pending.redirectUri) {
|
|
187
|
+
return c.json({ error: "invalid_grant", error_description: "redirect_uri mismatch" }, 400);
|
|
188
|
+
}
|
|
189
|
+
if (pending.codeChallengeMethod === "S256") {
|
|
190
|
+
const expected = createHash("sha256").update(codeVerifier).digest("base64url");
|
|
191
|
+
if (expected !== pending.codeChallenge) {
|
|
192
|
+
return c.json({ error: "invalid_grant", error_description: "PKCE verification failed" }, 400);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
pendingAuths.delete(code);
|
|
196
|
+
const accessToken = randomBytes(32).toString("hex");
|
|
197
|
+
const refreshToken = randomBytes(32).toString("hex");
|
|
198
|
+
const record = {
|
|
199
|
+
accessToken,
|
|
200
|
+
refreshToken,
|
|
201
|
+
clientId: pending.clientId,
|
|
202
|
+
expiresAt: Date.now() + TOKEN_EXPIRY_MS,
|
|
203
|
+
refreshExpiresAt: Date.now() + REFRESH_EXPIRY_MS
|
|
204
|
+
};
|
|
205
|
+
tokens.set(accessToken, record);
|
|
206
|
+
refreshTokens.set(refreshToken, record);
|
|
207
|
+
return c.json({
|
|
208
|
+
access_token: accessToken,
|
|
209
|
+
token_type: "Bearer",
|
|
210
|
+
expires_in: TOKEN_EXPIRY_MS / 1e3,
|
|
211
|
+
refresh_token: refreshToken
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
if (grantType === "refresh_token") {
|
|
215
|
+
const refreshToken = body["refresh_token"];
|
|
216
|
+
const old = refreshTokens.get(refreshToken);
|
|
217
|
+
if (!old) {
|
|
218
|
+
return c.json({ error: "invalid_grant" }, 400);
|
|
219
|
+
}
|
|
220
|
+
if (Date.now() > old.refreshExpiresAt) {
|
|
221
|
+
tokens.delete(old.accessToken);
|
|
222
|
+
refreshTokens.delete(refreshToken);
|
|
223
|
+
console.log("Auth: refresh token expired, user must re-authenticate.");
|
|
224
|
+
return c.json({ error: "invalid_grant", error_description: "Refresh token expired" }, 400);
|
|
225
|
+
}
|
|
226
|
+
tokens.delete(old.accessToken);
|
|
227
|
+
refreshTokens.delete(refreshToken);
|
|
228
|
+
const accessToken = randomBytes(32).toString("hex");
|
|
229
|
+
const newRefreshToken = randomBytes(32).toString("hex");
|
|
230
|
+
const record = {
|
|
231
|
+
accessToken,
|
|
232
|
+
refreshToken: newRefreshToken,
|
|
233
|
+
clientId: old.clientId,
|
|
234
|
+
expiresAt: Date.now() + TOKEN_EXPIRY_MS,
|
|
235
|
+
refreshExpiresAt: old.refreshExpiresAt
|
|
236
|
+
// keep original expiry
|
|
237
|
+
};
|
|
238
|
+
tokens.set(accessToken, record);
|
|
239
|
+
refreshTokens.set(newRefreshToken, record);
|
|
240
|
+
return c.json({
|
|
241
|
+
access_token: accessToken,
|
|
242
|
+
token_type: "Bearer",
|
|
243
|
+
expires_in: TOKEN_EXPIRY_MS / 1e3,
|
|
244
|
+
refresh_token: newRefreshToken
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
return c.json({ error: "unsupported_grant_type" }, 400);
|
|
248
|
+
});
|
|
249
|
+
return {
|
|
250
|
+
validateToken(authHeader) {
|
|
251
|
+
if (!authHeader?.startsWith("Bearer ")) return false;
|
|
252
|
+
const token = authHeader.slice(7);
|
|
253
|
+
const record = tokens.get(token);
|
|
254
|
+
if (!record) return false;
|
|
255
|
+
if (Date.now() > record.expiresAt) {
|
|
256
|
+
tokens.delete(token);
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
return true;
|
|
260
|
+
},
|
|
261
|
+
async saveTokens() {
|
|
262
|
+
if (!persistPath) return;
|
|
263
|
+
try {
|
|
264
|
+
await mkdir(dirname(persistPath), { recursive: true });
|
|
265
|
+
const data = JSON.stringify({
|
|
266
|
+
tokens: Object.fromEntries(tokens),
|
|
267
|
+
refreshTokens: Object.fromEntries(refreshTokens),
|
|
268
|
+
clients: Object.fromEntries(clients)
|
|
269
|
+
});
|
|
270
|
+
await writeFile(persistPath, data, { encoding: "utf-8", mode: 384 });
|
|
271
|
+
await chmod(persistPath, 384);
|
|
272
|
+
console.log(`Auth tokens saved to disk (${tokens.size} sessions).`);
|
|
273
|
+
} catch (err) {
|
|
274
|
+
console.error("Failed to save auth tokens:", err);
|
|
275
|
+
}
|
|
276
|
+
},
|
|
277
|
+
async loadTokens() {
|
|
278
|
+
if (!persistPath) return false;
|
|
279
|
+
try {
|
|
280
|
+
const raw = await readFile(persistPath, "utf-8");
|
|
281
|
+
const data = JSON.parse(raw);
|
|
282
|
+
for (const [k, v] of Object.entries(data.tokens ?? {})) {
|
|
283
|
+
tokens.set(k, v);
|
|
284
|
+
}
|
|
285
|
+
for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {
|
|
286
|
+
refreshTokens.set(k, v);
|
|
287
|
+
}
|
|
288
|
+
for (const [k, v] of Object.entries(data.clients ?? {})) {
|
|
289
|
+
clients.set(k, v);
|
|
290
|
+
}
|
|
291
|
+
console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);
|
|
292
|
+
return tokens.size > 0;
|
|
293
|
+
} catch {
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function renderPasswordPage(code, csrf, error) {
|
|
300
|
+
return `<!DOCTYPE html>
|
|
301
|
+
<html><head><title>Obsidian Sync MCP - Authorize</title>
|
|
302
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; form-action 'self'">
|
|
303
|
+
<style>
|
|
304
|
+
body { font-family: system-ui; max-width: 400px; margin: 80px auto; padding: 0 20px; }
|
|
305
|
+
h1 { font-size: 1.3em; }
|
|
306
|
+
input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }
|
|
307
|
+
button { padding: 10px 20px; font-size: 1em; cursor: pointer; }
|
|
308
|
+
.error { color: red; }
|
|
309
|
+
</style></head>
|
|
310
|
+
<body>
|
|
311
|
+
<h1>Obsidian Sync MCP</h1>
|
|
312
|
+
${error ? `<p class="error">${error}</p>` : "<p>Enter the server password to authorize access to your vault.</p>"}
|
|
313
|
+
<form method="POST" action="/oauth/approve" autocomplete="on">
|
|
314
|
+
<input type="hidden" name="code" value="${code}">
|
|
315
|
+
<input type="hidden" name="csrf" value="${csrf}">
|
|
316
|
+
<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">
|
|
317
|
+
<input type="password" name="password" id="password" placeholder="Password" autocomplete="current-password" autofocus required>
|
|
318
|
+
<br><button type="submit">Authorize</button>
|
|
319
|
+
</form>
|
|
320
|
+
</body></html>`;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// src/search.ts
|
|
324
|
+
import FlexSearch from "flexsearch";
|
|
325
|
+
import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, chmod as chmod2 } from "fs/promises";
|
|
326
|
+
import { dirname as dirname2 } from "path";
|
|
327
|
+
var MAX_RESULTS = 50;
|
|
328
|
+
var SearchIndex = class {
|
|
329
|
+
index;
|
|
330
|
+
contents = /* @__PURE__ */ new Map();
|
|
331
|
+
// path -> content (for snippet extraction)
|
|
332
|
+
persistPath;
|
|
333
|
+
constructor(persistPath) {
|
|
334
|
+
this.persistPath = persistPath ?? null;
|
|
335
|
+
this.index = new FlexSearch.Document({
|
|
336
|
+
document: { id: "path", index: ["content", "path"] },
|
|
337
|
+
tokenize: "forward"
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
/** Try to load a persisted index from disk. Returns true if loaded. */
|
|
341
|
+
async loadFromDisk() {
|
|
342
|
+
if (!this.persistPath) return false;
|
|
343
|
+
try {
|
|
344
|
+
const data = await readFile2(this.persistPath, "utf-8");
|
|
345
|
+
const { contents } = JSON.parse(data);
|
|
346
|
+
for (const [path, content] of Object.entries(contents)) {
|
|
347
|
+
this.index.add({ path, content });
|
|
348
|
+
this.contents.set(path, content);
|
|
349
|
+
}
|
|
350
|
+
console.log(`Search index loaded from disk (${this.contents.size} notes).`);
|
|
351
|
+
return true;
|
|
352
|
+
} catch {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/** Save the index to disk. */
|
|
357
|
+
async saveToDisk() {
|
|
358
|
+
if (!this.persistPath) return;
|
|
359
|
+
try {
|
|
360
|
+
await mkdir2(dirname2(this.persistPath), { recursive: true });
|
|
361
|
+
const data = JSON.stringify({
|
|
362
|
+
contents: Object.fromEntries(this.contents)
|
|
363
|
+
});
|
|
364
|
+
await writeFile2(this.persistPath, data, { encoding: "utf-8", mode: 384 });
|
|
365
|
+
await chmod2(this.persistPath, 384);
|
|
366
|
+
console.log(`Search index saved to disk (${this.contents.size} notes).`);
|
|
367
|
+
} catch (err) {
|
|
368
|
+
console.error("Failed to save search index:", err);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/** Add or update a note in the index. */
|
|
372
|
+
update(path, content) {
|
|
373
|
+
if (this.contents.has(path)) {
|
|
374
|
+
this.index.remove(path);
|
|
375
|
+
}
|
|
376
|
+
this.index.add({ path, content });
|
|
377
|
+
this.contents.set(path, content);
|
|
378
|
+
}
|
|
379
|
+
/** Remove a note from the index. */
|
|
380
|
+
remove(path) {
|
|
381
|
+
if (this.contents.has(path)) {
|
|
382
|
+
this.index.remove(path);
|
|
383
|
+
this.contents.delete(path);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
/** Search for a query. Returns paths with snippets. */
|
|
387
|
+
search(query) {
|
|
388
|
+
const results = this.index.search(query, { limit: MAX_RESULTS });
|
|
389
|
+
const paths = /* @__PURE__ */ new Set();
|
|
390
|
+
for (const result of results) {
|
|
391
|
+
if (result.result) {
|
|
392
|
+
for (const id of result.result) {
|
|
393
|
+
paths.add(id);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
const output = [];
|
|
398
|
+
const lowerQuery = query.toLowerCase();
|
|
399
|
+
for (const path of paths) {
|
|
400
|
+
if (output.length >= MAX_RESULTS) break;
|
|
401
|
+
const content = this.contents.get(path);
|
|
402
|
+
if (!content) continue;
|
|
403
|
+
const idx = content.toLowerCase().indexOf(lowerQuery);
|
|
404
|
+
if (idx !== -1) {
|
|
405
|
+
const start = Math.max(0, idx - 80);
|
|
406
|
+
const end = Math.min(content.length, idx + query.length + 80);
|
|
407
|
+
const snippet = (start > 0 ? "..." : "") + content.slice(start, end) + (end < content.length ? "..." : "");
|
|
408
|
+
output.push({ path, snippet });
|
|
409
|
+
} else {
|
|
410
|
+
output.push({ path, snippet: content.slice(0, 160) + (content.length > 160 ? "..." : "") });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return output;
|
|
414
|
+
}
|
|
415
|
+
/** List all indexed paths, optionally filtered by folder prefix. */
|
|
416
|
+
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();
|
|
420
|
+
}
|
|
421
|
+
return paths.sort();
|
|
422
|
+
}
|
|
423
|
+
get size() {
|
|
424
|
+
return this.contents.size;
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
// src/main.ts
|
|
429
|
+
var VAULT_PATH = process.env.VAULT_PATH;
|
|
430
|
+
var COUCHDB_URL = process.env.COUCHDB_URL;
|
|
431
|
+
var COUCHDB_USER = process.env.COUCHDB_USER ?? "admin";
|
|
432
|
+
var COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD ?? "password";
|
|
433
|
+
var COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? "obsidian";
|
|
434
|
+
var COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || void 0;
|
|
435
|
+
var VAULT_NAME = process.env.VAULT_NAME ?? "MyVault";
|
|
436
|
+
var PORT = parseInt(process.env.PORT ?? "8787");
|
|
437
|
+
var BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;
|
|
438
|
+
var AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;
|
|
439
|
+
var vault;
|
|
440
|
+
if (VAULT_PATH) {
|
|
441
|
+
const { LocalVault } = await import("./vault-local-65IVVIHQ.js");
|
|
442
|
+
vault = new LocalVault(VAULT_PATH);
|
|
443
|
+
console.log(`Local mode: ${VAULT_PATH}`);
|
|
444
|
+
} else if (COUCHDB_URL) {
|
|
445
|
+
const { Vault } = await import("./vault-IGTFVPKN.js");
|
|
446
|
+
vault = new Vault({
|
|
447
|
+
couchdbUrl: COUCHDB_URL,
|
|
448
|
+
couchdbUser: COUCHDB_USER,
|
|
449
|
+
couchdbPassword: COUCHDB_PASSWORD,
|
|
450
|
+
database: COUCHDB_DATABASE,
|
|
451
|
+
passphrase: COUCHDB_PASSPHRASE
|
|
452
|
+
});
|
|
453
|
+
console.log(`Remote mode: ${COUCHDB_URL}`);
|
|
454
|
+
} else {
|
|
455
|
+
console.error("Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.");
|
|
456
|
+
process.exit(1);
|
|
457
|
+
}
|
|
458
|
+
await vault.init();
|
|
459
|
+
console.log("Vault ready.");
|
|
460
|
+
var homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
|
|
461
|
+
var vaultId = createHash2("sha256").update(VAULT_PATH ?? COUCHDB_URL ?? "default").digest("hex").slice(0, 12);
|
|
462
|
+
var dataDir = join(homeDir, ".obsidian-mcp", vaultId);
|
|
463
|
+
var indexPath = join(dataDir, "search-index.json");
|
|
464
|
+
var searchIndex = new SearchIndex(indexPath);
|
|
465
|
+
var loaded = await searchIndex.loadFromDisk();
|
|
466
|
+
if (!loaded) {
|
|
467
|
+
const start = performance.now();
|
|
468
|
+
const notes = await vault.listNotes();
|
|
469
|
+
console.log(`Building search index (${notes.length} notes)...`);
|
|
470
|
+
for (let i = 0; i < notes.length; i++) {
|
|
471
|
+
const content = await vault.readNote(notes[i]);
|
|
472
|
+
if (content) searchIndex.update(notes[i], content);
|
|
473
|
+
if (notes.length > 100 && (i + 1) % 500 === 0) {
|
|
474
|
+
console.log(` indexed ${i + 1}/${notes.length}...`);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1e3).toFixed(1)}s`);
|
|
478
|
+
}
|
|
479
|
+
var fsWatcher = null;
|
|
480
|
+
if (VAULT_PATH) {
|
|
481
|
+
fsWatcher = watch(VAULT_PATH, { recursive: true }, async (event, filename) => {
|
|
482
|
+
if (!filename || !filename.endsWith(".md")) return;
|
|
483
|
+
const notePath = filename.replace(/\\/g, "/");
|
|
484
|
+
try {
|
|
485
|
+
const content = await readFile3(join(VAULT_PATH, notePath), "utf-8");
|
|
486
|
+
searchIndex.update(notePath, content);
|
|
487
|
+
} catch {
|
|
488
|
+
searchIndex.remove(notePath);
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
console.log("Watching vault for external changes.");
|
|
492
|
+
} else if (COUCHDB_URL && "watchChanges" in vault) {
|
|
493
|
+
vault.watchChanges((path, content) => {
|
|
494
|
+
if (content) {
|
|
495
|
+
searchIndex.update(path, content);
|
|
496
|
+
} else {
|
|
497
|
+
searchIndex.remove(path);
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
console.log("Watching CouchDB for LiveSync changes.");
|
|
501
|
+
}
|
|
502
|
+
var serverOptions = {
|
|
503
|
+
name: "obsidian-sync-mcp",
|
|
504
|
+
version: "0.1.0",
|
|
505
|
+
instructions: "Access and manage an Obsidian vault. You can read, write, list, search, and delete markdown notes. Every response includes a deep link to open the note directly in Obsidian."
|
|
506
|
+
};
|
|
507
|
+
var auth = null;
|
|
508
|
+
if (AUTH_TOKEN) {
|
|
509
|
+
serverOptions.authenticate = async (req) => {
|
|
510
|
+
const header = req.headers["authorization"];
|
|
511
|
+
const expected = `Bearer ${AUTH_TOKEN}`;
|
|
512
|
+
if (header && header.length === expected.length && timingSafeEqual2(Buffer.from(header), Buffer.from(expected))) {
|
|
513
|
+
return { authenticated: true };
|
|
514
|
+
}
|
|
515
|
+
if (auth?.validateToken(header)) {
|
|
516
|
+
return { authenticated: true };
|
|
517
|
+
}
|
|
518
|
+
throw new Response("Unauthorized", { status: 401 });
|
|
519
|
+
};
|
|
520
|
+
console.log("Auth enabled (password-gated OAuth).");
|
|
521
|
+
} else {
|
|
522
|
+
console.log("Auth disabled (set MCP_AUTH_TOKEN to enable).");
|
|
523
|
+
}
|
|
524
|
+
var server = new FastMCP(serverOptions);
|
|
525
|
+
if (AUTH_TOKEN) {
|
|
526
|
+
const tokenPath = join(dataDir, "auth-tokens.json");
|
|
527
|
+
auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);
|
|
528
|
+
await auth.loadTokens();
|
|
529
|
+
}
|
|
530
|
+
server.addTool({
|
|
531
|
+
name: "read_note",
|
|
532
|
+
description: "Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.",
|
|
533
|
+
parameters: z.object({
|
|
534
|
+
path: z.string().describe("Vault-relative path to the note, e.g. 'daily/2026-03-23.md'")
|
|
535
|
+
}),
|
|
536
|
+
execute: async ({ path }) => {
|
|
537
|
+
const content = await vault.readNote(path);
|
|
538
|
+
if (content === null) {
|
|
539
|
+
return `Note not found: ${path}`;
|
|
540
|
+
}
|
|
541
|
+
const deepLink = makeDeepLink(VAULT_NAME, path);
|
|
542
|
+
return `${content}
|
|
543
|
+
|
|
544
|
+
---
|
|
545
|
+
[Open in Obsidian](${deepLink})`;
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
server.addTool({
|
|
549
|
+
name: "write_note",
|
|
550
|
+
description: "Write or update a note in the Obsidian vault. Creates the note if it doesn't exist, overwrites if it does.",
|
|
551
|
+
parameters: z.object({
|
|
552
|
+
path: z.string().describe("Vault-relative path to the note, e.g. 'daily/2026-03-23.md'"),
|
|
553
|
+
content: z.string().describe("Full markdown content for the note")
|
|
554
|
+
}),
|
|
555
|
+
execute: async ({ path, content }) => {
|
|
556
|
+
const ok = await vault.writeNote(path, content);
|
|
557
|
+
if (!ok) {
|
|
558
|
+
return `Failed to write note: ${path}`;
|
|
559
|
+
}
|
|
560
|
+
searchIndex.update(path, content);
|
|
561
|
+
const deepLink = makeDeepLink(VAULT_NAME, path);
|
|
562
|
+
return `Note saved: ${path}
|
|
563
|
+
[Open in Obsidian](${deepLink})`;
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
server.addTool({
|
|
567
|
+
name: "list_notes",
|
|
568
|
+
description: "List all markdown notes in the vault, optionally filtered to a folder.",
|
|
569
|
+
parameters: z.object({
|
|
570
|
+
folder: z.string().optional().describe("Folder to filter by, e.g. 'daily/' or 'projects/'. Omit for all notes.")
|
|
571
|
+
}),
|
|
572
|
+
execute: async ({ folder }) => {
|
|
573
|
+
let notes = searchIndex.listPaths(folder);
|
|
574
|
+
if (notes.length === 0) {
|
|
575
|
+
notes = await vault.listNotes(folder);
|
|
576
|
+
}
|
|
577
|
+
if (notes.length === 0) {
|
|
578
|
+
return folder ? `No notes found in folder: ${folder}` : "Vault is empty.";
|
|
579
|
+
}
|
|
580
|
+
const total = notes.length;
|
|
581
|
+
const capped = notes.slice(0, 500);
|
|
582
|
+
const lines = capped.map((p) => {
|
|
583
|
+
const deepLink = makeDeepLink(VAULT_NAME, p);
|
|
584
|
+
return `- [${p}](${deepLink})`;
|
|
585
|
+
});
|
|
586
|
+
if (total > 500) {
|
|
587
|
+
lines.push(`
|
|
588
|
+
... and ${total - 500} more. Use a folder filter to narrow results.`);
|
|
589
|
+
}
|
|
590
|
+
return lines.join("\n");
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
server.addTool({
|
|
594
|
+
name: "search_vault",
|
|
595
|
+
description: "Search for a text query across all notes in the vault. Returns matching notes with snippets.",
|
|
596
|
+
parameters: z.object({
|
|
597
|
+
query: z.string().describe("Text to search for (case-insensitive)")
|
|
598
|
+
}),
|
|
599
|
+
execute: async ({ query }) => {
|
|
600
|
+
const results = searchIndex.search(query);
|
|
601
|
+
if (results.length === 0) {
|
|
602
|
+
return `No results for: ${query}`;
|
|
603
|
+
}
|
|
604
|
+
const lines = results.map((r) => {
|
|
605
|
+
const deepLink = makeDeepLink(VAULT_NAME, r.path);
|
|
606
|
+
return `### [${r.path}](${deepLink})
|
|
607
|
+
\`\`\`
|
|
608
|
+
${r.snippet}
|
|
609
|
+
\`\`\``;
|
|
610
|
+
});
|
|
611
|
+
return lines.join("\n\n");
|
|
612
|
+
}
|
|
613
|
+
});
|
|
614
|
+
server.addTool({
|
|
615
|
+
name: "delete_note",
|
|
616
|
+
description: "Delete a note from the Obsidian vault.",
|
|
617
|
+
parameters: z.object({
|
|
618
|
+
path: z.string().describe("Vault-relative path to the note to delete")
|
|
619
|
+
}),
|
|
620
|
+
execute: async ({ path }) => {
|
|
621
|
+
const ok = await vault.deleteNote(path);
|
|
622
|
+
if (ok) searchIndex.remove(path);
|
|
623
|
+
return ok ? `Deleted: ${path}` : `Failed to delete: ${path}`;
|
|
624
|
+
}
|
|
625
|
+
});
|
|
626
|
+
server.addTool({
|
|
627
|
+
name: "move_note",
|
|
628
|
+
description: "Move or rename a note. Use this to rename a note within the same folder, move it to a different folder, or both at once. Creates destination folders automatically.",
|
|
629
|
+
parameters: z.object({
|
|
630
|
+
from: z.string().describe("Current path, e.g. 'daily/old-name.md'"),
|
|
631
|
+
to: z.string().describe("New path, e.g. 'projects/new-name.md'")
|
|
632
|
+
}),
|
|
633
|
+
execute: async ({ from, to }) => {
|
|
634
|
+
const content = await vault.readNote(from);
|
|
635
|
+
const ok = await vault.moveNote(from, to);
|
|
636
|
+
if (!ok) {
|
|
637
|
+
return `Failed to move: ${from} \u2192 ${to}`;
|
|
638
|
+
}
|
|
639
|
+
searchIndex.remove(from);
|
|
640
|
+
if (content) searchIndex.update(to, content);
|
|
641
|
+
const deepLink = makeDeepLink(VAULT_NAME, to);
|
|
642
|
+
return `Moved: ${from} \u2192 ${to}
|
|
643
|
+
[Open in Obsidian](${deepLink})`;
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
server.addTool({
|
|
647
|
+
name: "get_note_metadata",
|
|
648
|
+
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.",
|
|
649
|
+
parameters: z.object({
|
|
650
|
+
path: z.string().describe("Vault-relative path to the note, e.g. 'projects/my-project.md'")
|
|
651
|
+
}),
|
|
652
|
+
execute: async ({ path }) => {
|
|
653
|
+
const meta = await vault.getMetadata(path);
|
|
654
|
+
if (!meta) {
|
|
655
|
+
return `Note not found: ${path}`;
|
|
656
|
+
}
|
|
657
|
+
const deepLink = makeDeepLink(VAULT_NAME, path);
|
|
658
|
+
const lines = [
|
|
659
|
+
`**${path}**`,
|
|
660
|
+
`Size: ${meta.size} bytes`,
|
|
661
|
+
`Created: ${new Date(meta.ctime).toISOString()}`,
|
|
662
|
+
`Modified: ${new Date(meta.mtime).toISOString()}`
|
|
663
|
+
];
|
|
664
|
+
if (Object.keys(meta.frontmatter).length > 0) {
|
|
665
|
+
lines.push(`
|
|
666
|
+
Frontmatter:`);
|
|
667
|
+
for (const [k, v] of Object.entries(meta.frontmatter)) {
|
|
668
|
+
lines.push(` ${k}: ${v}`);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
if (meta.tags.length > 0) {
|
|
672
|
+
lines.push(`
|
|
673
|
+
Tags: ${meta.tags.map((t) => `#${t}`).join(", ")}`);
|
|
674
|
+
}
|
|
675
|
+
if (meta.links.length > 0) {
|
|
676
|
+
lines.push(`
|
|
677
|
+
Links: ${meta.links.join(", ")}`);
|
|
678
|
+
}
|
|
679
|
+
lines.push(`
|
|
680
|
+
[Open in Obsidian](${deepLink})`);
|
|
681
|
+
return lines.join("\n");
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
async function shutdown() {
|
|
685
|
+
console.log("Shutting down...");
|
|
686
|
+
if (fsWatcher) fsWatcher.close();
|
|
687
|
+
await searchIndex.saveToDisk();
|
|
688
|
+
if (auth) await auth.saveTokens();
|
|
689
|
+
await vault.close();
|
|
690
|
+
process.exit(0);
|
|
691
|
+
}
|
|
692
|
+
process.on("SIGTERM", shutdown);
|
|
693
|
+
process.on("SIGINT", shutdown);
|
|
694
|
+
setInterval(async () => {
|
|
695
|
+
await searchIndex.saveToDisk();
|
|
696
|
+
if (auth) await auth.saveTokens();
|
|
697
|
+
}, 5 * 60 * 1e3).unref();
|
|
698
|
+
server.start({
|
|
699
|
+
transportType: "httpStream",
|
|
700
|
+
httpStream: { port: PORT, endpoint: "/mcp" }
|
|
701
|
+
});
|
|
702
|
+
console.log(`MCP server listening on port ${PORT}`);
|
|
703
|
+
//# sourceMappingURL=main.js.map
|