standardnotes-mcp 3.0.1 → 3.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.
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
7
7
  import readline from "node:readline";
8
8
  import { storedAccounts } from "../sn/session.js";
9
9
  import { isMainModule } from "./isMain.js";
10
+ import { claudeCodeAddArgs, shellQuote } from "./clients.js";
10
11
  /** Config key for this server in MCP client configs (renamed in 3.0.0). */
11
12
  export const SERVER_KEY = "standardnotes-mcp";
12
13
  const LEGACY_SERVER_KEY = "mcp-standardnotes";
@@ -84,11 +85,21 @@ export async function pickEmail() {
84
85
  throw new Error(`Invalid selection: ${answer}`);
85
86
  return choice;
86
87
  }
87
- export function buildEntry(paths, email, clientName) {
88
+ /**
89
+ * Env keys setup owns. On re-install these come only from the new entry
90
+ * (SN_READ_TAGS is removed when the new scope is the whole vault); every
91
+ * other key already in the client's config, such as a hand-added
92
+ * SN_DENY_TAGS or SN_READ_ONLY, is kept.
93
+ */
94
+ export const MANAGED_ENV_KEYS = ["SN_EMAIL", "SN_CLIENT_NAME", "SN_READ_TAGS"];
95
+ export function buildEntry(paths, email, clientName, readTags) {
88
96
  const env = { SN_EMAIL: email };
89
97
  if (clientName !== undefined && clientName !== "") {
90
98
  env.SN_CLIENT_NAME = clientName;
91
99
  }
100
+ if (readTags !== undefined && readTags.length > 0) {
101
+ env.SN_READ_TAGS = readTags.join(",");
102
+ }
92
103
  return {
93
104
  command: paths.node,
94
105
  args: [paths.server],
@@ -99,16 +110,56 @@ export function buildEntry(paths, email, clientName) {
99
110
  export function cursorConfigPath() {
100
111
  return join(homedir(), ".cursor", "mcp.json");
101
112
  }
113
+ function envOf(entry) {
114
+ if (typeof entry !== "object" || entry === null)
115
+ return {};
116
+ const env = entry.env;
117
+ if (typeof env !== "object" || env === null)
118
+ return {};
119
+ const out = {};
120
+ for (const [k, v] of Object.entries(env)) {
121
+ if (typeof v === "string")
122
+ out[k] = v;
123
+ }
124
+ return out;
125
+ }
126
+ /**
127
+ * The env of this server's existing entry in an mcpServers-style config
128
+ * (current key, else the pre-3.0.0 one), or null when there is none or the
129
+ * file can't be read. Used to offer the current folder scope as the default.
130
+ */
131
+ export async function existingServerEnv(configPath) {
132
+ try {
133
+ const config = await readJsonOrEmpty(configPath);
134
+ const servers = config.mcpServers;
135
+ if (!servers)
136
+ return null;
137
+ const entry = servers[SERVER_KEY] ?? servers[LEGACY_SERVER_KEY];
138
+ return entry === undefined ? null : envOf(entry);
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ }
102
144
  /** Merge a server entry into any mcpServers-style JSON config file. */
103
145
  export async function installJsonConfig(opts) {
104
146
  await mkdir(dirname(opts.configPath), { recursive: true });
105
147
  const backup = await backupOnce(opts.configPath);
106
148
  const config = await readJsonOrEmpty(opts.configPath);
107
149
  const servers = config.mcpServers ?? {};
150
+ const key = opts.serverKey ?? SERVER_KEY;
151
+ // Keep env settings setup doesn't manage (SN_DENY_TAGS, SN_READ_ONLY, ...)
152
+ // from the existing entry, so re-running setup never silently drops them.
153
+ const previousEnv = {
154
+ ...(!opts.serverKey ? envOf(servers[LEGACY_SERVER_KEY]) : {}),
155
+ ...envOf(servers[key]),
156
+ };
157
+ for (const k of MANAGED_ENV_KEYS)
158
+ delete previousEnv[k];
108
159
  // Replace the pre-3.0.0 key rather than leaving a duplicate server.
109
160
  if (!opts.serverKey)
110
161
  delete servers[LEGACY_SERVER_KEY];
111
- servers[opts.serverKey ?? SERVER_KEY] = opts.entry;
162
+ servers[key] = { ...opts.entry, env: { ...previousEnv, ...opts.entry.env } };
112
163
  config.mcpServers = servers;
113
164
  await writeFile(opts.configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
114
165
  return { configPath: opts.configPath, backup };
@@ -116,15 +167,13 @@ export async function installJsonConfig(opts) {
116
167
  export async function installDesktop(opts) {
117
168
  return installJsonConfig({
118
169
  configPath: opts.configPath ?? desktopConfigPath(),
119
- entry: buildEntry(opts.paths, opts.email, opts.clientName),
170
+ entry: buildEntry(opts.paths, opts.email, opts.clientName, opts.readTags),
120
171
  });
121
172
  }
122
- export async function printCodeInstructions(paths, email, clientName) {
123
- const nameEnv = clientName !== undefined && clientName !== ""
124
- ? ` --env SN_CLIENT_NAME=${clientName}`
125
- : "";
126
- process.stdout.write("For Claude Code, run this command (it shells out to the `claude` CLI):\n\n");
127
- process.stdout.write(` claude mcp add standardnotes-mcp "${paths.node}" "${paths.server}" --env SN_EMAIL=${email}${nameEnv}\n\n`);
173
+ export async function printCodeInstructions(paths, email, clientName, readTags) {
174
+ const args = claudeCodeAddArgs(paths, buildEntry(paths, email, clientName, readTags).env);
175
+ process.stdout.write("For Claude Code, run this command (it uses the `claude` CLI):\n\n");
176
+ process.stdout.write(` claude ${args.map(shellQuote).join(" ")}\n\n`);
128
177
  process.stdout.write("If you don't have the `claude` CLI installed, add the same JSON entry manually to ~/.claude.json under `mcpServers`.\n");
129
178
  }
130
179
  function parseTargets(argv) {
package/dist/cli/login.js CHANGED
@@ -105,8 +105,20 @@ export async function runLogin() {
105
105
  }
106
106
  }
107
107
  // Don't auto-run when imported (e.g. from setup.ts).
108
+ // Run directly, login continues into the guided setup (name each AI client,
109
+ // write or print its MCP settings), so a new install needs this one command.
110
+ // Skipped with --no-setup or when stdin isn't a terminal (scripts).
108
111
  if (isMainModule(import.meta.url)) {
109
- runLogin().catch((err) => {
112
+ (async () => {
113
+ const email = await runLogin();
114
+ if (process.argv.includes("--no-setup") || process.stdin.isTTY !== true) {
115
+ process.stdout.write("Run `standardnotes-mcp-setup` to connect your AI clients.\n");
116
+ return;
117
+ }
118
+ process.stdout.write("\nNext: connect your AI clients.\n");
119
+ const { runSetup } = await import("./setup.js");
120
+ await runSetup({ email });
121
+ })().catch((err) => {
110
122
  // "Login failed" was already logged with its cause chain above.
111
123
  if (err instanceof Error && err.message !== "Login failed") {
112
124
  process.stderr.write(`${err.message}\n`);
package/dist/cli/setup.js CHANGED
@@ -1,24 +1,81 @@
1
1
  #!/usr/bin/env node
2
2
  import readline from "node:readline";
3
3
  import { existsSync } from "node:fs";
4
- import { buildEntry, cursorConfigPath, installDesktop, installJsonConfig, pickEmail, printCodeInstructions, resolvePaths, storedSessionEmails, } from "./install.js";
4
+ import { buildEntry, cursorConfigPath, desktopConfigPath, existingServerEnv, installDesktop, installJsonConfig, pickEmail, printCodeInstructions, resolvePaths, storedSessionEmails, } from "./install.js";
5
5
  import { runLogin } from "./login.js";
6
+ import { folderHint, parseFolderAnswer } from "./folders.js";
7
+ import { claudeCodeAddArgs, lumoFormText, detectInstalled, parseSelection, realProbes, runClaude, } from "./clients.js";
8
+ import { createClientFromSession } from "../sn/client.js";
6
9
  import { isMainModule } from "./isMain.js";
7
10
  const CHOICES = [
8
11
  { label: "Claude (Desktop app)", defaultName: "claude", wiring: "claude-desktop" },
9
12
  { label: "Claude Code (CLI)", defaultName: "claude", wiring: "claude-code" },
10
13
  { label: "ChatGPT", defaultName: "chatgpt", wiring: "manual" },
11
14
  { label: "Kimi Code (CLI)", defaultName: "kimi", wiring: "manual" },
12
- { label: "Lumo (Proton)", defaultName: "lumo", wiring: "manual" },
15
+ { label: "Lumo (Proton)", defaultName: "lumo", wiring: "lumo" },
13
16
  { label: "Cursor", defaultName: "cursor", wiring: "cursor" },
14
17
  { label: "Other (enter a name)", defaultName: "", wiring: "manual" },
15
18
  ];
16
- async function wire(choice, clientName, email, paths) {
19
+ /** Config file setup writes for this client, when it writes one. */
20
+ function configFileFor(choice) {
21
+ try {
22
+ if (choice.wiring === "claude-desktop")
23
+ return desktopConfigPath();
24
+ if (choice.wiring === "cursor")
25
+ return cursorConfigPath();
26
+ }
27
+ catch {
28
+ // Claude Desktop doesn't exist on this platform.
29
+ }
30
+ return null;
31
+ }
32
+ /**
33
+ * Folder titles in the vault, for checking what the user types. Reads the
34
+ * vault with the stored session (the same full sync the server does at
35
+ * start). null when that fails; names are then accepted unchecked.
36
+ */
37
+ async function loadFolderTitles(email) {
38
+ process.stdout.write("\nReading your tags from Standard Notes...\n");
39
+ try {
40
+ const client = await createClientFromSession({
41
+ serverUrl: process.env.SN_SERVER_URL ?? "https://api.standardnotes.com",
42
+ email,
43
+ });
44
+ return (await client.listTags()).map((t) => t.title);
45
+ }
46
+ catch (err) {
47
+ process.stdout.write(` Couldn't read your tags (${err instanceof Error ? err.message : String(err)}),\n` +
48
+ " so tag names you enter won't be checked. Type them exactly as in Standard Notes.\n");
49
+ return null;
50
+ }
51
+ }
52
+ /**
53
+ * Adds the server to Claude Code with its own CLI, for every project
54
+ * (--scope user). An existing entry with this name is replaced, as setup
55
+ * does for Claude Desktop. Returns false when it couldn't, after saying why;
56
+ * the caller then prints the command to run by hand.
57
+ */
58
+ function addToClaudeCode(paths, env) {
59
+ const args = claudeCodeAddArgs(paths, env);
60
+ let res = runClaude(args);
61
+ if (!res.ok && /already exists/i.test(res.output)) {
62
+ runClaude(["mcp", "remove", "--scope", "user", "standardnotes-mcp"]);
63
+ res = runClaude(args);
64
+ }
65
+ if (res.ok) {
66
+ process.stdout.write(" Added to Claude Code (all projects). Restart any open Claude Code sessions.\n");
67
+ return true;
68
+ }
69
+ process.stdout.write(` Couldn't add it automatically${res.output ? `: ${res.output}` : ""}\n`);
70
+ return false;
71
+ }
72
+ async function wire(choice, clientName, email, paths, readTags) {
17
73
  if (choice.wiring === "claude-desktop") {
18
74
  const { configPath, backup } = await installDesktop({
19
75
  email,
20
76
  paths,
21
77
  clientName,
78
+ readTags,
22
79
  });
23
80
  process.stdout.write(` Updated Claude Desktop config at ${configPath}\n`);
24
81
  if (backup)
@@ -29,7 +86,7 @@ async function wire(choice, clientName, email, paths) {
29
86
  if (choice.wiring === "cursor") {
30
87
  const { configPath, backup } = await installJsonConfig({
31
88
  configPath: cursorConfigPath(),
32
- entry: buildEntry(paths, email, clientName),
89
+ entry: buildEntry(paths, email, clientName, readTags),
33
90
  });
34
91
  process.stdout.write(` Updated Cursor config at ${configPath}\n`);
35
92
  if (backup)
@@ -38,14 +95,25 @@ async function wire(choice, clientName, email, paths) {
38
95
  return;
39
96
  }
40
97
  if (choice.wiring === "claude-code") {
41
- await printCodeInstructions(paths, email, clientName);
98
+ await printCodeInstructions(paths, email, clientName, readTags);
99
+ return;
100
+ }
101
+ if (choice.wiring === "lumo") {
102
+ // Lumo's settings are a form, not a JSON file: print field by field.
103
+ // Values start at the left edge so a copied value carries no indent.
104
+ process.stdout.write(lumoFormText(buildEntry(paths, email, clientName, readTags)));
42
105
  return;
43
106
  }
44
107
  // manual: print a ready-to-paste snippet
45
108
  process.stdout.write(` Add this to ${choice.label}'s MCP server config:\n\n`);
46
- process.stdout.write(JSON.stringify({ mcpServers: { "standardnotes-mcp": buildEntry(paths, email, clientName) } }, null, 2) + "\n\n");
109
+ process.stdout.write(JSON.stringify({ mcpServers: { "standardnotes-mcp": buildEntry(paths, email, clientName, readTags) } }, null, 2) + "\n\n");
47
110
  }
48
- async function main() {
111
+ /**
112
+ * Runs the guided setup. With `email` (just logged in by
113
+ * standardnotes-mcp-login) it skips the account step and goes straight to
114
+ * connecting AI clients.
115
+ */
116
+ export async function runSetup(opts = {}) {
49
117
  const paths = resolvePaths();
50
118
  if (!existsSync(paths.server)) {
51
119
  throw new Error(`Server entrypoint not found at ${paths.server}. ` +
@@ -58,10 +126,13 @@ async function main() {
58
126
  // Resolve the account before opening the readline UI below: the login
59
127
  // flow uses its own stdin handling, so it must run before this
60
128
  // interface exists.
61
- const stored = await storedSessionEmails();
129
+ const stored = opts.email !== undefined ? [] : await storedSessionEmails();
62
130
  const envEmail = process.env.SN_EMAIL;
63
131
  let email;
64
- if (stored.length === 0 ||
132
+ if (opts.email !== undefined) {
133
+ email = opts.email;
134
+ }
135
+ else if (stored.length === 0 ||
65
136
  (envEmail !== undefined && !stored.includes(envEmail))) {
66
137
  process.stdout.write(stored.length === 0
67
138
  ? "No stored Standard Notes session — logging in first.\n\n"
@@ -109,82 +180,115 @@ async function main() {
109
180
  });
110
181
  };
111
182
  try {
112
- process.stdout.write("\nWhich AI clients should use this MCP server?\n");
113
- process.stdout.write("(enter numbers separated by commas, e.g. 1,3)\n");
114
- CHOICES.forEach((c, i) => process.stdout.write(` [${i + 1}] ${c.label}\n`));
115
- const picks = (await ask("Numbers: "))
116
- .split(",")
117
- .map((s) => Number(s.trim()) - 1)
118
- .filter((n) => Number.isInteger(n));
119
- const selected = [];
120
- for (const n of picks) {
121
- const c = CHOICES[n];
122
- if (!c)
123
- throw new Error(`Invalid selection: ${n + 1}`);
124
- if (!selected.includes(c))
125
- selected.push(c);
183
+ const found = detectInstalled(realProbes(desktopConfigPath));
184
+ const detected = CHOICES.flatMap((c, i) => c.wiring !== "lumo" && c.wiring !== "manual" && found.has(c.wiring) ? [i] : []);
185
+ process.stdout.write("\nWhich AI apps should use Standard Notes?\n");
186
+ CHOICES.forEach((c, i) => process.stdout.write(` [${i + 1}] ${c.label}${detected.includes(i) ? " (found on this computer)" : ""}\n`));
187
+ process.stdout.write(detected.length > 0
188
+ ? `Enter numbers separated by commas, or press Enter for the apps found (${detected.map((i) => i + 1).join(", ")}). Type 0 to skip.\n`
189
+ : "Enter numbers separated by commas, e.g. 1,3, or press Enter to skip for now.\n");
190
+ let selected = [];
191
+ // eslint-disable-next-line no-constant-condition
192
+ while (true) {
193
+ const sel = parseSelection(await ask("Apps: "), CHOICES.length, detected);
194
+ if (sel.kind === "error") {
195
+ process.stdout.write(` ${sel.message}\n`);
196
+ continue;
197
+ }
198
+ selected = sel.indexes.map((i) => CHOICES[i]);
199
+ break;
200
+ }
201
+ if (selected.length === 0) {
202
+ process.stdout.write("\nNo clients connected. Run `standardnotes-mcp-setup` any time to connect one.\n");
203
+ return;
126
204
  }
127
- if (selected.length === 0)
128
- throw new Error("No clients selected.");
129
205
  const askNameFor = async () => {
130
206
  // eslint-disable-next-line no-constant-condition
131
207
  while (true) {
132
- const name = await ask(" Enter a governance name (letters, digits, dashes): ");
208
+ const name = await ask(" Name for this app (letters, digits, dashes): ");
133
209
  if (/^[a-z0-9-]+$/i.test(name))
134
210
  return name;
135
211
  process.stdout.write(" Letters, digits, and dashes only — try again.\n");
136
212
  }
137
213
  };
214
+ // Folder list is read once, on first need (skipping clients costs nothing).
215
+ let folderTitles;
216
+ const askFolders = async (choice) => {
217
+ if (folderTitles === undefined)
218
+ folderTitles = await loadFolderTitles(email);
219
+ const configFile = configFileFor(choice);
220
+ const current = configFile !== null ? await existingServerEnv(configFile) : null;
221
+ const currentTags = (current?.SN_READ_TAGS ?? "")
222
+ .split(",")
223
+ .map((t) => t.trim())
224
+ .filter((t) => t !== "");
225
+ const hasCurrent = currentTags.length > 0;
226
+ process.stdout.write(`\nWhich tags should ${choice.label} be able to see?\n` +
227
+ " Enter tag names separated by commas. It will see only notes with those\n" +
228
+ " tags (or their child tags); everything else is hidden from it.\n" +
229
+ (hasCurrent
230
+ ? ` Press Enter to keep the current setting (${currentTags.join(", ")}), or type "all" for the whole vault.\n`
231
+ : " Press Enter to let it see your whole vault.\n") +
232
+ (folderTitles !== null ? ` Your tags: ${folderHint(folderTitles)}\n` : ""));
233
+ // eslint-disable-next-line no-constant-condition
234
+ while (true) {
235
+ const ans = parseFolderAnswer(await ask("Tags: "), folderTitles, hasCurrent);
236
+ if (ans.kind === "keep")
237
+ return currentTags;
238
+ if (ans.kind === "all")
239
+ return [];
240
+ if (ans.kind === "folders")
241
+ return ans.folders;
242
+ process.stdout.write(` No tag named ${ans.names.map((n) => `"${n}"`).join(", ")}. Check the spelling against the list above.\n`);
243
+ }
244
+ };
138
245
  const wired = [];
139
246
  for (const choice of selected) {
140
247
  process.stdout.write(`\n── ${choice.label} ──\n`);
248
+ // The app's name (SN_CLIENT_NAME) is what per-note rules like
249
+ // "ai-lumo: no-access" match. Not asked: keep the name already in the
250
+ // app's config, else use the app's default. Only "Other" has none.
251
+ const configFile = configFileFor(choice);
252
+ const currentName = configFile !== null ? (await existingServerEnv(configFile))?.SN_CLIENT_NAME : undefined;
141
253
  let clientName;
142
- if (choice.defaultName !== "") {
143
- const d = choice.defaultName;
144
- process.stdout.write(`Each note can carry rules that apply to this client only, like\n` +
145
- `"ai-${d}: no-access" (hide the note from it) or "ai-${d}: read-only"\n` +
146
- `(no edits). Those rules match on a name stored in the client's\n` +
147
- `config — the AI itself cannot change it.\n`);
148
- const ans = (await ask(`Use the name "${d}" for ${choice.label}? [Y/n]: `)).toLowerCase();
149
- if (ans === "" || ans === "y" || ans === "yes") {
150
- clientName = d;
151
- }
152
- else if (ans === "n" || ans === "no") {
153
- clientName = await askNameFor();
154
- }
155
- else if (/^[a-z0-9-]+$/i.test(ans)) {
156
- // Typed a name directly instead of y/n — accept it.
157
- clientName = ans;
158
- }
159
- else {
160
- clientName = await askNameFor();
161
- }
254
+ if (currentName !== undefined && /^[a-z0-9-]+$/i.test(currentName)) {
255
+ clientName = currentName;
256
+ }
257
+ else if (choice.defaultName !== "") {
258
+ clientName = choice.defaultName;
162
259
  }
163
260
  else {
164
- process.stdout.write(`Pick a governance name for this client. Notes with frontmatter\n` +
165
- `"ai-<name>: <rule>" will apply to it (e.g. "ai-workai: no-access").\n`);
166
261
  clientName = await askNameFor();
167
262
  }
168
- await wire(choice, clientName, email, paths);
169
- wired.push({ label: choice.label, name: clientName });
263
+ const readTags = await askFolders(choice);
264
+ if (choice.wiring === "claude-code" && found.has("claude-code")) {
265
+ const yes = (await ask("Add it to Claude Code now (runs `claude mcp add`)? [Y/n]: ")).toLowerCase();
266
+ if (yes === "" || yes === "y" || yes === "yes") {
267
+ if (!addToClaudeCode(paths, buildEntry(paths, email, clientName, readTags).env)) {
268
+ await wire(choice, clientName, email, paths, readTags);
269
+ }
270
+ wired.push({ label: choice.label, name: clientName, readTags });
271
+ continue;
272
+ }
273
+ }
274
+ await wire(choice, clientName, email, paths, readTags);
275
+ wired.push({ label: choice.label, name: clientName, readTags });
170
276
  }
171
- process.stdout.write("\nDone. Governance identities:\n");
277
+ process.stdout.write("\nDone.\n");
172
278
  for (const w of wired) {
173
- process.stdout.write(` ${w.label} → "${w.name}" (matches frontmatter ai-${w.name}: ...)\n`);
279
+ process.stdout.write(` ${w.label}: sees ${w.readTags.length > 0 ? `only ${w.readTags.join(", ")}` : "the whole vault"}; name "${w.name}"\n`);
174
280
  }
175
- process.stdout.write("\nTip for sensitive notes — default-deny is fail-safe:\n" +
176
- " ai: no-access (hidden from every AI)\n" +
177
- ` ai-${wired[0]?.name ?? "kimi"}: ok (…except this one)\n` +
178
- "With that pattern, a mistyped identity keeps the note hidden instead\n" +
179
- "of exposing it. Verify any time via the sn://status resource, which\n" +
180
- "reports the active client identity.\n");
281
+ process.stdout.write("\nThe name is what per-note rules match: a note with \"ai-" +
282
+ `${wired[0]?.name ?? "lumo"}: no-access" in its frontmatter is hidden from that app.\n` +
283
+ "To use a different name, change SN_CLIENT_NAME in the app's MCP settings.\n" +
284
+ "More in the README: Per-note rules, and Limiting an AI to tags.\n");
181
285
  }
182
286
  finally {
183
287
  rl.close();
184
288
  }
185
289
  }
186
290
  if (isMainModule(import.meta.url)) {
187
- main().catch((err) => {
291
+ runSetup().catch((err) => {
188
292
  process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
189
293
  process.exit(1);
190
294
  });
package/dist/config.js CHANGED
@@ -8,6 +8,30 @@ function parseBool(raw) {
8
8
  const v = raw.trim().toLowerCase();
9
9
  return v === "true" || v === "1" || v === "yes" || v === "on";
10
10
  }
11
+ function parseDeleteConfirm(env) {
12
+ const raw = (env.SN_DELETE_CONFIRM ?? "").trim().toLowerCase();
13
+ if (["off", "false", "0", "no", "none"].includes(raw))
14
+ return "off";
15
+ if (raw === "prompt")
16
+ return "prompt";
17
+ if (raw === "" && parseBool(env.SN_DELETE_ELICITATION))
18
+ return "prompt";
19
+ if (raw !== "" && raw !== "auto" && !["on", "true", "1", "yes"].includes(raw)) {
20
+ logger.warn(`SN_DELETE_CONFIRM "${raw}" not recognised; using auto (auto, prompt or off)`);
21
+ }
22
+ return "auto";
23
+ }
24
+ /** An editor identifier like com.example.editor; anything else is ignored with a warning. */
25
+ function parseEditorId(raw) {
26
+ const v = trimmedOrNull(raw);
27
+ if (v === null)
28
+ return null;
29
+ if (!/^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(v)) {
30
+ logger.warn(`SN_NEW_NOTE_EDITOR "${v}" is not an editor identifier (like com.example.editor); ignored`);
31
+ return null;
32
+ }
33
+ return v;
34
+ }
11
35
  function parseTagList(raw) {
12
36
  if (raw === undefined || raw.trim() === "")
13
37
  return [];
@@ -26,7 +50,7 @@ export function loadConfig(env = process.env) {
26
50
  readTags: readTags.length > 0 ? readTags : null,
27
51
  denyTags,
28
52
  },
29
- deleteElicitation: parseBool(env.SN_DELETE_ELICITATION),
53
+ deleteConfirm: parseDeleteConfirm(env),
30
54
  governance: !(govRaw === "off" || govRaw === "false" || govRaw === "0"),
31
55
  allowExport: parseBool(env.SN_ALLOW_EXPORT),
32
56
  exportDir: env.SN_EXPORT_DIR !== undefined && env.SN_EXPORT_DIR.trim() !== ""
@@ -36,7 +60,9 @@ export function loadConfig(env = process.env) {
36
60
  ? env.SN_CLIENT_NAME.trim()
37
61
  : null,
38
62
  templatesTag: trimmedOrNull(env.SN_TEMPLATES_TAG) ?? "Templates",
63
+ sharedTemplates: parseBool(env.SN_SHARED_TEMPLATES),
39
64
  periodicTag: trimmedOrNull(env.SN_PERIODIC_TAG),
65
+ newNoteEditor: parseEditorId(env.SN_NEW_NOTE_EDITOR),
40
66
  };
41
67
  const scoped = config.scope.readTags !== null || config.scope.denyTags.length > 0;
42
68
  logger.info("Server policy", {
@@ -47,13 +73,15 @@ export function loadConfig(env = process.env) {
47
73
  denyTags: config.scope.denyTags,
48
74
  }
49
75
  : "none",
50
- deleteElicitation: config.deleteElicitation,
76
+ deleteConfirm: config.deleteConfirm,
51
77
  governance: config.governance,
52
78
  allowExport: config.allowExport,
53
79
  exportDir: config.exportDir,
54
80
  clientName: config.clientName,
55
81
  templatesTag: config.templatesTag,
82
+ sharedTemplates: config.sharedTemplates,
56
83
  periodicTag: config.periodicTag,
84
+ newNoteEditor: config.newNoteEditor,
57
85
  });
58
86
  return config;
59
87
  }
@@ -0,0 +1,88 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { ToolError } from "./security/errors.js";
3
+ const TOKEN_TTL_MS = 10 * 60 * 1000;
4
+ function describe(req) {
5
+ const where = req.permanent ? "PERMANENTLY (cannot be undone)" : "to the trash";
6
+ if (req.notes.length === 1) {
7
+ const n = req.notes[0];
8
+ return `Delete note "${n.title}" ${where}?`;
9
+ }
10
+ const titles = req.notes.slice(0, 10).map((n) => `"${n.title}"`).join(", ");
11
+ const more = req.notes.length > 10 ? ` and ${req.notes.length - 10} more` : "";
12
+ return `Delete ${req.notes.length} notes ${where}: ${titles}${more}?`;
13
+ }
14
+ function keyOf(req) {
15
+ return `${req.permanent ? "P" : "T"}:${req.notes.map((n) => n.uuid).sort().join(",")}`;
16
+ }
17
+ /**
18
+ * Builds the delete guard. A delete goes ahead only after the user agrees:
19
+ *
20
+ * - App prompt (MCP elicitation): shown when the app supports it. Accept
21
+ * deletes; decline or dismiss cancels.
22
+ * - Chat confirmation (auto mode, apps without a prompt such as Lumo): the
23
+ * first call deletes nothing and returns a one-time `confirmToken` with the
24
+ * question to ask. The AI must ask the user, and only on a clear yes call
25
+ * again with the same arguments plus the token. A token is bound to exactly
26
+ * those notes and that trash/permanent choice, works once, and expires
27
+ * after 10 minutes.
28
+ * - prompt mode refuses (confirmation_unavailable) when the app can't show a
29
+ * prompt, rather than deleting unasked.
30
+ */
31
+ export function makeDeleteGuard(server, mode, now = Date.now) {
32
+ const pending = new Map();
33
+ const cannotConfirm = () => new ToolError("confirmation_unavailable", "Deletes need the user's confirmation in the app's prompt (SN_DELETE_CONFIRM=prompt), but this AI app can't show one, so nothing was deleted.", "Tell the user to delete the note in Standard Notes, or to remove SN_DELETE_CONFIRM=prompt (or SN_DELETE_ELICITATION) for this app so the AI can ask in chat instead.");
34
+ const askInChat = (req, token) => {
35
+ const t = now();
36
+ for (const [k, v] of pending)
37
+ if (v.expires <= t)
38
+ pending.delete(k);
39
+ const key = keyOf(req);
40
+ if (token !== undefined) {
41
+ const entry = pending.get(token);
42
+ if (entry && entry.key === key) {
43
+ pending.delete(token);
44
+ return { proceed: true };
45
+ }
46
+ }
47
+ const fresh = randomBytes(9).toString("hex");
48
+ pending.set(fresh, { key, expires: t + TOKEN_TTL_MS });
49
+ const question = describe(req);
50
+ return {
51
+ proceed: false,
52
+ result: {
53
+ ok: false,
54
+ confirmationRequired: true,
55
+ ...(token !== undefined
56
+ ? { tokenProblem: "That confirmToken was expired, already used, or for different notes. Ask the user again." }
57
+ : {}),
58
+ question,
59
+ confirmToken: fresh,
60
+ instructions: `Nothing was deleted. Ask the user exactly: ${question} Only if they clearly say yes, call ${req.tool} again with the same arguments plus confirmToken "${fresh}". If they say no or don't answer, don't call it again.`,
61
+ },
62
+ };
63
+ };
64
+ return async (req, token) => {
65
+ if (mode === "off" || req.notes.length === 0)
66
+ return { proceed: true };
67
+ if (server.getClientCapabilities()?.elicitation) {
68
+ try {
69
+ const res = await server.elicitInput({
70
+ message: `${describe(req)}${req.permanent ? "" : " Trash can be restored."}`,
71
+ requestedSchema: { type: "object", properties: {} },
72
+ });
73
+ return res.action === "accept"
74
+ ? { proceed: true }
75
+ : { proceed: false, result: { ok: false, cancelled: true } };
76
+ }
77
+ catch {
78
+ if (mode === "prompt")
79
+ throw cannotConfirm();
80
+ return askInChat(req, token);
81
+ }
82
+ }
83
+ if (mode === "prompt")
84
+ throw cannotConfirm();
85
+ return askInChat(req, token);
86
+ };
87
+ }
88
+ //# sourceMappingURL=confirmDelete.js.map