standardnotes-mcp 0.0.0-stage → 3.0.1

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/LICENSE +22 -0
  3. package/README.md +336 -3
  4. package/SECURITY.md +56 -0
  5. package/dist/cli/install.js +180 -0
  6. package/dist/cli/isMain.js +21 -0
  7. package/dist/cli/login.js +117 -0
  8. package/dist/cli/logout.js +22 -0
  9. package/dist/cli/setup.js +192 -0
  10. package/dist/config.js +60 -0
  11. package/dist/index.js +10 -0
  12. package/dist/security/errors.js +20 -0
  13. package/dist/security/logger.js +17 -0
  14. package/dist/security/redact.js +31 -0
  15. package/dist/security/regex.js +27 -0
  16. package/dist/server.js +329 -0
  17. package/dist/sn/cache.js +53 -0
  18. package/dist/sn/client.js +1999 -0
  19. package/dist/sn/crypto.js +63 -0
  20. package/dist/sn/dates.js +157 -0
  21. package/dist/sn/entitlement.js +75 -0
  22. package/dist/sn/frontmatter.js +171 -0
  23. package/dist/sn/governance.js +40 -0
  24. package/dist/sn/http.js +289 -0
  25. package/dist/sn/links.js +78 -0
  26. package/dist/sn/markdownSections.js +141 -0
  27. package/dist/sn/predicates.js +135 -0
  28. package/dist/sn/protocol004.js +401 -0
  29. package/dist/sn/scope.js +68 -0
  30. package/dist/sn/search.js +260 -0
  31. package/dist/sn/session.js +55 -0
  32. package/dist/sn/tagHierarchy.js +105 -0
  33. package/dist/sn/tasks.js +32 -0
  34. package/dist/sn/templates.js +23 -0
  35. package/dist/sn/types.js +12 -0
  36. package/dist/tools/daily.js +126 -0
  37. package/dist/tools/export.js +96 -0
  38. package/dist/tools/history.js +41 -0
  39. package/dist/tools/links.js +51 -0
  40. package/dist/tools/notes.js +404 -0
  41. package/dist/tools/smartviews.js +52 -0
  42. package/dist/tools/tags.js +82 -0
  43. package/dist/tools/tasks.js +43 -0
  44. package/dist/tools/templates.js +145 -0
  45. package/dist/version.js +12 -0
  46. package/docs/protocol-004.md +72 -0
  47. package/docs/self-hosted.md +120 -0
  48. package/docs/troubleshooting.md +89 -0
  49. package/package.json +86 -6
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, writeFile, copyFile, mkdir } from "node:fs/promises";
3
+ import { existsSync } from "node:fs";
4
+ import { homedir, platform } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import readline from "node:readline";
8
+ import { storedAccounts } from "../sn/session.js";
9
+ import { isMainModule } from "./isMain.js";
10
+ /** Config key for this server in MCP client configs (renamed in 3.0.0). */
11
+ export const SERVER_KEY = "standardnotes-mcp";
12
+ const LEGACY_SERVER_KEY = "mcp-standardnotes";
13
+ /** Returns absolute paths for node + the server entrypoint. */
14
+ export function resolvePaths() {
15
+ const here = dirname(fileURLToPath(import.meta.url));
16
+ // The server entrypoint is always the BUILT artifact (dist/index.js) —
17
+ // even when this CLI runs from src/ via tsx (`npm run setup`).
18
+ const runningFromSrc = here.replace(/\\/g, "/").endsWith("src/cli");
19
+ const server = runningFromSrc
20
+ ? resolve(here, "..", "..", "dist", "index.js")
21
+ : resolve(here, "..", "index.js");
22
+ return { node: process.execPath, server };
23
+ }
24
+ export function desktopConfigPath() {
25
+ const p = platform();
26
+ if (p === "darwin") {
27
+ return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
28
+ }
29
+ if (p === "win32") {
30
+ const appdata = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
31
+ return join(appdata, "Claude", "claude_desktop_config.json");
32
+ }
33
+ throw new Error(`Claude Desktop is not available on ${p}. Use \`standardnotes-mcp-install code\` for Claude Code instead.`);
34
+ }
35
+ async function readJsonOrEmpty(path) {
36
+ if (!existsSync(path))
37
+ return {};
38
+ const raw = await readFile(path, "utf8");
39
+ if (!raw.trim())
40
+ return {};
41
+ try {
42
+ return JSON.parse(raw);
43
+ }
44
+ catch (err) {
45
+ throw new Error(`Existing config at ${path} is not valid JSON; refusing to overwrite. (${err instanceof Error ? err.message : String(err)})`);
46
+ }
47
+ }
48
+ async function backupOnce(path) {
49
+ if (!existsSync(path))
50
+ return null;
51
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
52
+ const backup = `${path}.bak-${stamp}`;
53
+ await copyFile(path, backup);
54
+ return backup;
55
+ }
56
+ /** Emails that have a stored keychain session (empty when none). */
57
+ export async function storedSessionEmails() {
58
+ return storedAccounts();
59
+ }
60
+ export async function pickEmail() {
61
+ if (process.env.SN_EMAIL)
62
+ return process.env.SN_EMAIL;
63
+ const accounts = await storedAccounts();
64
+ if (accounts.length === 1 && accounts[0])
65
+ return accounts[0];
66
+ if (accounts.length === 0) {
67
+ throw new Error("No stored Standard Notes session found. Run `standardnotes-mcp-login` first.");
68
+ }
69
+ // Multiple accounts — prompt
70
+ const rl = readline.createInterface({
71
+ input: process.stdin,
72
+ output: process.stdout,
73
+ terminal: true,
74
+ });
75
+ process.stdout.write("Multiple sessions found. Pick which email to use:\n");
76
+ accounts.forEach((a, i) => process.stdout.write(` [${i + 1}] ${a}\n`));
77
+ const answer = await new Promise((res) => rl.question("Number: ", (a) => {
78
+ rl.close();
79
+ res(a.trim());
80
+ }));
81
+ const idx = Number(answer) - 1;
82
+ const choice = accounts[idx];
83
+ if (!choice)
84
+ throw new Error(`Invalid selection: ${answer}`);
85
+ return choice;
86
+ }
87
+ export function buildEntry(paths, email, clientName) {
88
+ const env = { SN_EMAIL: email };
89
+ if (clientName !== undefined && clientName !== "") {
90
+ env.SN_CLIENT_NAME = clientName;
91
+ }
92
+ return {
93
+ command: paths.node,
94
+ args: [paths.server],
95
+ env,
96
+ };
97
+ }
98
+ /** Config file location for Cursor (mcpServers-style JSON). */
99
+ export function cursorConfigPath() {
100
+ return join(homedir(), ".cursor", "mcp.json");
101
+ }
102
+ /** Merge a server entry into any mcpServers-style JSON config file. */
103
+ export async function installJsonConfig(opts) {
104
+ await mkdir(dirname(opts.configPath), { recursive: true });
105
+ const backup = await backupOnce(opts.configPath);
106
+ const config = await readJsonOrEmpty(opts.configPath);
107
+ const servers = config.mcpServers ?? {};
108
+ // Replace the pre-3.0.0 key rather than leaving a duplicate server.
109
+ if (!opts.serverKey)
110
+ delete servers[LEGACY_SERVER_KEY];
111
+ servers[opts.serverKey ?? SERVER_KEY] = opts.entry;
112
+ config.mcpServers = servers;
113
+ await writeFile(opts.configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
114
+ return { configPath: opts.configPath, backup };
115
+ }
116
+ export async function installDesktop(opts) {
117
+ return installJsonConfig({
118
+ configPath: opts.configPath ?? desktopConfigPath(),
119
+ entry: buildEntry(opts.paths, opts.email, opts.clientName),
120
+ });
121
+ }
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`);
128
+ 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
+ }
130
+ function parseTargets(argv) {
131
+ const targets = [];
132
+ for (const a of argv) {
133
+ if (a === "desktop" || a === "code") {
134
+ if (!targets.includes(a))
135
+ targets.push(a);
136
+ }
137
+ else {
138
+ throw new Error(`Unknown argument: "${a}". Usage: standardnotes-mcp-install [desktop] [code]`);
139
+ }
140
+ }
141
+ if (targets.length === 0)
142
+ targets.push("desktop");
143
+ return targets;
144
+ }
145
+ async function main() {
146
+ const targets = parseTargets(process.argv.slice(2));
147
+ const paths = resolvePaths();
148
+ if (!existsSync(paths.server)) {
149
+ throw new Error(`Could not find the MCP server entrypoint at ${paths.server}. ` +
150
+ `Reinstall the package: \`npm install -g standardnotes-mcp\`.`);
151
+ }
152
+ const email = await pickEmail();
153
+ for (const t of targets) {
154
+ if (t === "desktop") {
155
+ try {
156
+ const { configPath, backup } = await installDesktop({ email, paths });
157
+ process.stdout.write(`Updated Claude Desktop config at ${configPath}\n`);
158
+ if (backup) {
159
+ process.stdout.write(`(previous config backed up to ${backup})\n`);
160
+ }
161
+ process.stdout.write("Quit Claude Desktop fully (⌘Q on macOS) and relaunch to pick up the change.\n");
162
+ }
163
+ catch (err) {
164
+ process.stderr.write(`Desktop install failed: ${err instanceof Error ? err.message : String(err)}\n`);
165
+ process.exitCode = 1;
166
+ }
167
+ }
168
+ else if (t === "code") {
169
+ await printCodeInstructions(paths, email);
170
+ }
171
+ }
172
+ }
173
+ // Don't auto-run when imported (e.g. from login.ts or tests).
174
+ if (isMainModule(import.meta.url)) {
175
+ main().catch((err) => {
176
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
177
+ process.exit(1);
178
+ });
179
+ }
180
+ //# sourceMappingURL=install.js.map
@@ -0,0 +1,21 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ /**
4
+ * True when the module at `metaUrl` is the script node was started with.
5
+ *
6
+ * Compares real paths, because npm installs global commands on macOS and
7
+ * Linux as symlinks named after the command (e.g. `standardnotes-mcp-login`
8
+ * -> dist/cli/login.js), so `process.argv[1]` is the link, not the file.
9
+ */
10
+ export function isMainModule(metaUrl) {
11
+ const entry = process.argv[1];
12
+ if (!entry)
13
+ return false;
14
+ try {
15
+ return realpathSync(entry) === realpathSync(fileURLToPath(metaUrl));
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ //# sourceMappingURL=isMain.js.map
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+ import readline from "node:readline";
3
+ import { logger } from "../security/logger.js";
4
+ import { createClientFromLogin } from "../sn/client.js";
5
+ import { isMainModule } from "./isMain.js";
6
+ const CTRL_C = "\u0003";
7
+ const DEL = "";
8
+ function promptVisible(question) {
9
+ return new Promise((resolve) => {
10
+ const rl = readline.createInterface({
11
+ input: process.stdin,
12
+ output: process.stdout,
13
+ terminal: true,
14
+ });
15
+ rl.question(question, (answer) => {
16
+ rl.close();
17
+ resolve(answer.trim());
18
+ });
19
+ });
20
+ }
21
+ function promptSilent(question) {
22
+ if (typeof process.stdin.setRawMode !== "function") {
23
+ // Piped/redirected stdin: no terminal, so nothing echoes the input.
24
+ return promptVisible(question);
25
+ }
26
+ return new Promise((resolve, reject) => {
27
+ const stdin = process.stdin;
28
+ process.stdout.write(question);
29
+ const wasRaw = stdin.isRaw === true;
30
+ stdin.setRawMode(true);
31
+ stdin.resume();
32
+ stdin.setEncoding("utf8");
33
+ let input = "";
34
+ const cleanup = () => {
35
+ stdin.setRawMode(wasRaw);
36
+ stdin.pause();
37
+ stdin.removeListener("data", onData);
38
+ };
39
+ const onData = (chunk) => {
40
+ for (const ch of chunk) {
41
+ if (ch === CTRL_C) {
42
+ cleanup();
43
+ process.stdout.write("\n");
44
+ reject(new Error("aborted"));
45
+ return;
46
+ }
47
+ if (ch === "\r" || ch === "\n") {
48
+ cleanup();
49
+ process.stdout.write("\n");
50
+ resolve(input);
51
+ return;
52
+ }
53
+ if (ch === DEL || ch === "\b") {
54
+ if (input.length > 0) {
55
+ input = input.slice(0, -1);
56
+ process.stdout.write("\b \b");
57
+ }
58
+ continue;
59
+ }
60
+ input += ch;
61
+ process.stdout.write("*");
62
+ }
63
+ };
64
+ stdin.on("data", onData);
65
+ });
66
+ }
67
+ function prompt(question, silent = false) {
68
+ return silent ? promptSilent(question) : promptVisible(question);
69
+ }
70
+ /**
71
+ * Interactive login: prompts for credentials (email reused from SN_EMAIL
72
+ * when set), derives keys, and stores the session in the OS keychain.
73
+ * Returns the account email. Throws on failure after logging the cause
74
+ * chain; callers decide how to exit.
75
+ */
76
+ export async function runLogin() {
77
+ const serverUrl = process.env.SN_SERVER_URL ?? "https://api.standardnotes.com";
78
+ const envEmail = process.env.SN_EMAIL;
79
+ const email = envEmail ?? (await prompt("Email: "));
80
+ if (!email)
81
+ throw new Error("email is required");
82
+ let password = await prompt("Password: ", true);
83
+ if (!password)
84
+ throw new Error("password is required");
85
+ try {
86
+ await createClientFromLogin({ serverUrl, email }, password, async () => prompt("Two-factor code (6 digits): "));
87
+ password = "";
88
+ logger.info("Login OK, session stored in keychain", { email, serverUrl });
89
+ process.stdout.write("Login successful. Session saved in OS keychain.\n");
90
+ return email;
91
+ }
92
+ catch (err) {
93
+ password = "";
94
+ const causes = [];
95
+ let cur = err;
96
+ while (cur instanceof Error) {
97
+ causes.push(cur.message);
98
+ cur = cur.cause;
99
+ }
100
+ logger.error("Login failed", {
101
+ message: causes[0] ?? String(err),
102
+ causes: causes.slice(1),
103
+ });
104
+ throw new Error("Login failed");
105
+ }
106
+ }
107
+ // Don't auto-run when imported (e.g. from setup.ts).
108
+ if (isMainModule(import.meta.url)) {
109
+ runLogin().catch((err) => {
110
+ // "Login failed" was already logged with its cause chain above.
111
+ if (err instanceof Error && err.message !== "Login failed") {
112
+ process.stderr.write(`${err.message}\n`);
113
+ }
114
+ process.exit(1);
115
+ });
116
+ }
117
+ //# sourceMappingURL=login.js.map
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ import { deleteSession } from "../sn/session.js";
3
+ async function main() {
4
+ const email = process.env.SN_EMAIL ?? process.argv[2];
5
+ if (!email) {
6
+ console.error("Usage: standardnotes-mcp-logout <email> (or set SN_EMAIL; from a source checkout: npm run logout -- <email>)");
7
+ process.exit(2);
8
+ }
9
+ const removed = await deleteSession(email);
10
+ if (removed) {
11
+ console.error(`Removed keychain entry for ${email}.`);
12
+ }
13
+ else {
14
+ console.error(`No keychain entry found for ${email}.`);
15
+ process.exit(1);
16
+ }
17
+ }
18
+ main().catch((err) => {
19
+ console.error(err instanceof Error ? err.message : String(err));
20
+ process.exit(1);
21
+ });
22
+ //# sourceMappingURL=logout.js.map
@@ -0,0 +1,192 @@
1
+ #!/usr/bin/env node
2
+ import readline from "node:readline";
3
+ import { existsSync } from "node:fs";
4
+ import { buildEntry, cursorConfigPath, installDesktop, installJsonConfig, pickEmail, printCodeInstructions, resolvePaths, storedSessionEmails, } from "./install.js";
5
+ import { runLogin } from "./login.js";
6
+ import { isMainModule } from "./isMain.js";
7
+ const CHOICES = [
8
+ { label: "Claude (Desktop app)", defaultName: "claude", wiring: "claude-desktop" },
9
+ { label: "Claude Code (CLI)", defaultName: "claude", wiring: "claude-code" },
10
+ { label: "ChatGPT", defaultName: "chatgpt", wiring: "manual" },
11
+ { label: "Kimi Code (CLI)", defaultName: "kimi", wiring: "manual" },
12
+ { label: "Lumo (Proton)", defaultName: "lumo", wiring: "manual" },
13
+ { label: "Cursor", defaultName: "cursor", wiring: "cursor" },
14
+ { label: "Other (enter a name)", defaultName: "", wiring: "manual" },
15
+ ];
16
+ async function wire(choice, clientName, email, paths) {
17
+ if (choice.wiring === "claude-desktop") {
18
+ const { configPath, backup } = await installDesktop({
19
+ email,
20
+ paths,
21
+ clientName,
22
+ });
23
+ process.stdout.write(` Updated Claude Desktop config at ${configPath}\n`);
24
+ if (backup)
25
+ process.stdout.write(` (previous config backed up to ${backup})\n`);
26
+ process.stdout.write(" Quit Claude Desktop fully and relaunch to pick up the change.\n");
27
+ return;
28
+ }
29
+ if (choice.wiring === "cursor") {
30
+ const { configPath, backup } = await installJsonConfig({
31
+ configPath: cursorConfigPath(),
32
+ entry: buildEntry(paths, email, clientName),
33
+ });
34
+ process.stdout.write(` Updated Cursor config at ${configPath}\n`);
35
+ if (backup)
36
+ process.stdout.write(` (previous config backed up to ${backup})\n`);
37
+ process.stdout.write(" Restart Cursor to pick up the change.\n");
38
+ return;
39
+ }
40
+ if (choice.wiring === "claude-code") {
41
+ await printCodeInstructions(paths, email, clientName);
42
+ return;
43
+ }
44
+ // manual: print a ready-to-paste snippet
45
+ 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");
47
+ }
48
+ async function main() {
49
+ const paths = resolvePaths();
50
+ if (!existsSync(paths.server)) {
51
+ throw new Error(`Server entrypoint not found at ${paths.server}. ` +
52
+ "In a source checkout run `npm run build` first; otherwise reinstall: `npm install -g standardnotes-mcp`.");
53
+ }
54
+ if (process.stdin.isTTY !== true) {
55
+ process.stdout.write("Note: stdin is not a terminal, so line editing (backspace) may not work.\n" +
56
+ "For a fully interactive run, start `standardnotes-mcp-setup` directly in a terminal.\n\n");
57
+ }
58
+ // Resolve the account before opening the readline UI below: the login
59
+ // flow uses its own stdin handling, so it must run before this
60
+ // interface exists.
61
+ const stored = await storedSessionEmails();
62
+ const envEmail = process.env.SN_EMAIL;
63
+ let email;
64
+ if (stored.length === 0 ||
65
+ (envEmail !== undefined && !stored.includes(envEmail))) {
66
+ process.stdout.write(stored.length === 0
67
+ ? "No stored Standard Notes session — logging in first.\n\n"
68
+ : `No stored session for ${envEmail} — logging in first.\n\n`);
69
+ email = await runLogin();
70
+ process.stdout.write("\n");
71
+ }
72
+ else {
73
+ email = await pickEmail();
74
+ }
75
+ const rl = readline.createInterface({
76
+ input: process.stdin,
77
+ output: process.stdout,
78
+ terminal: process.stdin.isTTY === true,
79
+ });
80
+ // Queue-based line reader: works for interactive TTYs and piped stdin
81
+ // alike (rl.question drops lines that arrive between questions).
82
+ const queue = [];
83
+ let waiter = null;
84
+ rl.on("line", (line) => {
85
+ const value = line.trim();
86
+ if (waiter) {
87
+ const w = waiter;
88
+ waiter = null;
89
+ w(value);
90
+ }
91
+ else {
92
+ queue.push(value);
93
+ }
94
+ });
95
+ rl.on("close", () => {
96
+ if (waiter) {
97
+ const w = waiter;
98
+ waiter = null;
99
+ w("");
100
+ }
101
+ });
102
+ const ask = (q) => {
103
+ process.stdout.write(q);
104
+ const queued = queue.shift();
105
+ if (queued !== undefined)
106
+ return Promise.resolve(queued);
107
+ return new Promise((res) => {
108
+ waiter = res;
109
+ });
110
+ };
111
+ 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);
126
+ }
127
+ if (selected.length === 0)
128
+ throw new Error("No clients selected.");
129
+ const askNameFor = async () => {
130
+ // eslint-disable-next-line no-constant-condition
131
+ while (true) {
132
+ const name = await ask(" Enter a governance name (letters, digits, dashes): ");
133
+ if (/^[a-z0-9-]+$/i.test(name))
134
+ return name;
135
+ process.stdout.write(" Letters, digits, and dashes only — try again.\n");
136
+ }
137
+ };
138
+ const wired = [];
139
+ for (const choice of selected) {
140
+ process.stdout.write(`\n── ${choice.label} ──\n`);
141
+ 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
+ }
162
+ }
163
+ 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
+ clientName = await askNameFor();
167
+ }
168
+ await wire(choice, clientName, email, paths);
169
+ wired.push({ label: choice.label, name: clientName });
170
+ }
171
+ process.stdout.write("\nDone. Governance identities:\n");
172
+ for (const w of wired) {
173
+ process.stdout.write(` ${w.label} → "${w.name}" (matches frontmatter ai-${w.name}: ...)\n`);
174
+ }
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");
181
+ }
182
+ finally {
183
+ rl.close();
184
+ }
185
+ }
186
+ if (isMainModule(import.meta.url)) {
187
+ main().catch((err) => {
188
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
189
+ process.exit(1);
190
+ });
191
+ }
192
+ //# sourceMappingURL=setup.js.map
package/dist/config.js ADDED
@@ -0,0 +1,60 @@
1
+ import { logger } from "./security/logger.js";
2
+ function trimmedOrNull(raw) {
3
+ return raw !== undefined && raw.trim() !== "" ? raw.trim() : null;
4
+ }
5
+ function parseBool(raw) {
6
+ if (raw === undefined)
7
+ return false;
8
+ const v = raw.trim().toLowerCase();
9
+ return v === "true" || v === "1" || v === "yes" || v === "on";
10
+ }
11
+ function parseTagList(raw) {
12
+ if (raw === undefined || raw.trim() === "")
13
+ return [];
14
+ return raw
15
+ .split(",")
16
+ .map((s) => s.trim())
17
+ .filter((s) => s.length > 0);
18
+ }
19
+ export function loadConfig(env = process.env) {
20
+ const readTags = parseTagList(env.SN_READ_TAGS);
21
+ const denyTags = parseTagList(env.SN_DENY_TAGS);
22
+ const govRaw = (env.SN_GOVERNANCE ?? "").trim().toLowerCase();
23
+ const config = {
24
+ readOnly: parseBool(env.SN_READ_ONLY),
25
+ scope: {
26
+ readTags: readTags.length > 0 ? readTags : null,
27
+ denyTags,
28
+ },
29
+ deleteElicitation: parseBool(env.SN_DELETE_ELICITATION),
30
+ governance: !(govRaw === "off" || govRaw === "false" || govRaw === "0"),
31
+ allowExport: parseBool(env.SN_ALLOW_EXPORT),
32
+ exportDir: env.SN_EXPORT_DIR !== undefined && env.SN_EXPORT_DIR.trim() !== ""
33
+ ? env.SN_EXPORT_DIR.trim()
34
+ : null,
35
+ clientName: env.SN_CLIENT_NAME !== undefined && env.SN_CLIENT_NAME.trim() !== ""
36
+ ? env.SN_CLIENT_NAME.trim()
37
+ : null,
38
+ templatesTag: trimmedOrNull(env.SN_TEMPLATES_TAG) ?? "Templates",
39
+ periodicTag: trimmedOrNull(env.SN_PERIODIC_TAG),
40
+ };
41
+ const scoped = config.scope.readTags !== null || config.scope.denyTags.length > 0;
42
+ logger.info("Server policy", {
43
+ readOnly: config.readOnly,
44
+ tagScope: scoped
45
+ ? {
46
+ readTags: config.scope.readTags,
47
+ denyTags: config.scope.denyTags,
48
+ }
49
+ : "none",
50
+ deleteElicitation: config.deleteElicitation,
51
+ governance: config.governance,
52
+ allowExport: config.allowExport,
53
+ exportDir: config.exportDir,
54
+ clientName: config.clientName,
55
+ templatesTag: config.templatesTag,
56
+ periodicTag: config.periodicTag,
57
+ });
58
+ return config;
59
+ }
60
+ //# sourceMappingURL=config.js.map
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { logger } from "./security/logger.js";
3
+ import { startServer } from "./server.js";
4
+ startServer().catch((err) => {
5
+ logger.error("Fatal startup error", {
6
+ message: err instanceof Error ? err.message : String(err),
7
+ });
8
+ process.exit(1);
9
+ });
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Structured tool errors. MCP clients (LLMs) recover far better from a
3
+ * machine-readable `reason` plus a `recoveryHint` than from a bare message
4
+ * string — the hint tells the agent what to do next (e.g. "run notes_search
5
+ * to find the uuid") instead of leaving it to guess.
6
+ */
7
+ export class ToolError extends Error {
8
+ reason;
9
+ recoveryHint;
10
+ constructor(reason, message, recoveryHint) {
11
+ super(message);
12
+ this.name = "ToolError";
13
+ this.reason = reason;
14
+ this.recoveryHint = recoveryHint;
15
+ }
16
+ }
17
+ export function isToolError(err) {
18
+ return err instanceof ToolError;
19
+ }
20
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,17 @@
1
+ import { redact, redactString } from "./redact.js";
2
+ function write(level, msg, meta) {
3
+ const line = meta === undefined
4
+ ? `[${level}] ${redactString(msg)}`
5
+ : `[${level}] ${redactString(msg)} ${JSON.stringify(redact(meta))}`;
6
+ process.stderr.write(line + "\n");
7
+ }
8
+ export const logger = {
9
+ debug: (msg, meta) => {
10
+ if (process.env.DEBUG)
11
+ write("debug", msg, meta);
12
+ },
13
+ info: (msg, meta) => write("info", msg, meta),
14
+ warn: (msg, meta) => write("warn", msg, meta),
15
+ error: (msg, meta) => write("error", msg, meta),
16
+ };
17
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,31 @@
1
+ const SENSITIVE_KEY_RE = /\b(password|pw|mk|ak|masterKey|rootKey|itemsKey|authKey|serverPassword|session|accessToken|refreshToken|jwt|authorization)\b/i;
2
+ const LONG_TOKEN_RE = /\b[A-Za-z0-9+/_-]{32,}={0,2}\b/g;
3
+ const MAX_DEPTH = 8;
4
+ export function redact(value, depth = 0) {
5
+ if (depth > MAX_DEPTH)
6
+ return "[depth-limit]";
7
+ if (value === null || value === undefined)
8
+ return value;
9
+ if (typeof value === "string") {
10
+ return value.replace(LONG_TOKEN_RE, "[REDACTED]");
11
+ }
12
+ if (typeof value !== "object")
13
+ return value;
14
+ if (Array.isArray(value)) {
15
+ return value.map((v) => redact(v, depth + 1));
16
+ }
17
+ const out = {};
18
+ for (const [k, v] of Object.entries(value)) {
19
+ if (SENSITIVE_KEY_RE.test(k)) {
20
+ out[k] = "[REDACTED]";
21
+ }
22
+ else {
23
+ out[k] = redact(v, depth + 1);
24
+ }
25
+ }
26
+ return out;
27
+ }
28
+ export function redactString(s) {
29
+ return s.replace(LONG_TOKEN_RE, "[REDACTED]");
30
+ }
31
+ //# sourceMappingURL=redact.js.map