@clarionstack/notesia 0.1.1 → 0.2.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.
package/README.md CHANGED
@@ -19,18 +19,41 @@ npm install -g @clarionstack/notesia
19
19
  ### Notes
20
20
 
21
21
  - `notesia get --id <id>|--supabase-id <uuid>|--title "<title>" [--json] [--with-meta]`
22
- - `notesia list [--limit <count>] [--format table|json]`
22
+ - `notesia list [--limit <count>] [--offset <n>] [--folder-id <id>] [--tag <tag>] [--format table|json]` *(use `--folder-id 0` for unfoldered root notes)*
23
23
  - `notesia store --title "<title>" [--tag <tag>]... [--folder-id <id>] [--content <text>]`
24
- - `notesia update --id <id>|... [--content <text>] [--title "<new title>"]`
25
- - `notesia append --id <id>|... [--content <text>]`
26
- - `notesia prepend --id <id>|... [--content <text>]`
27
- - `notesia move --id <id>|... --folder-id <id>` *(use 0 for root)*
28
- - `notesia trash --id <id>|...`
24
+ - `notesia update --id <id>|--supabase-id <uuid>|--match-title "<title>" [--content <text>] [--title "<new title>"]`
25
+ - `notesia append --id <id>|--supabase-id <uuid>|--match-title "<title>" [--content <text>]`
26
+ - `notesia prepend --id <id>|--supabase-id <uuid>|--match-title "<title>" [--content <text>]`
27
+ - `notesia move --id <id>|--supabase-id <uuid>|--match-title "<title>" --folder-id <id>` *(use 0 for root)*
28
+ - `notesia trash --id <id>|--supabase-id <uuid>|--match-title "<title>"`
29
29
  - `notesia capture --title "<title>" [--content <text>] [--tag <tag>]...`
30
30
  - `notesia open --id <id>|--title "<title>"`
31
31
  - `notesia sync`
32
32
  - `notesia auth status [--format text|json]`
33
33
 
34
+ ### Folders
35
+
36
+ - `notesia folder list [--format table|json]`
37
+ - `notesia folder create --name "<name>" [--parent-id <id>] [--icon <icon>] [--format text|json]`
38
+ - `notesia folder rename --id <id> --name "<new>" [--format text|json]`
39
+ - `notesia folder move --id <id> --parent-id <id> [--format text|json]` *(use 0 for root)*
40
+ - `notesia folder delete --id <id> [--format text|json]` *(empty non-system folders only)*
41
+
42
+ ### MCP Server (External AI Apps)
43
+
44
+ - `notesia mcp` — Start a local stdio Model Context Protocol (MCP) server exposing note, folder, tag, search, and sync tools over the running desktop bridge:
45
+
46
+ ```json
47
+ {
48
+ "mcpServers": {
49
+ "notesia": {
50
+ "command": "notesia",
51
+ "args": ["mcp"]
52
+ }
53
+ }
54
+ }
55
+ ```
56
+
34
57
  ### Search
35
58
 
36
59
  - `notesia search <query> [--limit <n>] [--format text|json]`
@@ -40,8 +63,8 @@ Alias for `notesia kb search`. Full-text search across all notes by title and co
40
63
  ### Tags
41
64
 
42
65
  - `notesia tags [--format text|json]` — List all tags with note counts
43
- - `notesia tag add --id <id>|... --tag <tag> [--tag <tag>]...` — Add tags to a note
44
- - `notesia tag remove --id <id>|... --tag <tag> [--tag <tag>]...` — Remove tags from a note
66
+ - `notesia tag add --id <id>|--supabase-id <uuid>|--match-title "<title>" --tag <tag> [--tag <tag>]...` — Add tags to a note
67
+ - `notesia tag remove --id <id>|--supabase-id <uuid>|--match-title "<title>" --tag <tag> [--tag <tag>]...` — Remove tags from a note
45
68
 
46
69
  ### Bulk Import
47
70
 
@@ -54,7 +77,7 @@ Recursively discovers files in a directory and imports them as notes into Notesi
54
77
  | Option | Description | Default |
55
78
  |---|---|---|
56
79
  | `<path>` | Source directory or file (required) | — |
57
- | `--ext <list>` | Comma-separated file extensions | `md,txt,pdf,docx,json` |
80
+ | `--ext <list>` | Comma-separated file extensions | `md,txt,html,htm,pdf,docx,json` |
58
81
  | `--folder <name>` | Target folder name (created if absent) | — |
59
82
  | `--tags <list>` | Comma-separated tags for all imported notes | — |
60
83
  | `--conflict <mode>` | `skip` or `overwrite` existing notes by title | `skip` |
@@ -63,7 +86,9 @@ Recursively discovers files in a directory and imports them as notes into Notesi
63
86
  | `--quiet` | Suppress stdout output | — |
64
87
  | `--verbose` | Print per-file progress to stderr | — |
65
88
 
66
- Supported file types: `.md`, `.txt`, `.html`, `.pdf`, `.docx`, `.json`.
89
+ Supported file types: `.md`, `.txt`, `.html`, `.htm`, `.pdf`, `.docx`, `.json`.
90
+
91
+ Markdown source is retained locally for exact workspace and export output. HTML imports keep the document body as editable rich text after scripts, styles, iframes, forms, event handlers, and unsafe URLs are removed.
67
92
 
68
93
  JSON imports are transformed into flattened key-path text (with truncation guards for very large arrays/strings) to improve embedding quality.
69
94
 
@@ -78,6 +103,13 @@ Notes exceeding 100,000 characters are automatically split into multiple parts.
78
103
 
79
104
  `kb ask` automatically reuses the same conversation in the same terminal session. Use `--conversation-id` only when you want to override/reset the session.
80
105
 
106
+ `kb context` is the CLI handoff path for external AI coding assistants: it returns
107
+ source context as JSON rather than generating an answer. Review or filter that JSON,
108
+ then provide it to your assistant with the task and ask the assistant to preserve the
109
+ source references instead of guessing beyond the supplied context. The in-app Knowledge
110
+ Base Inspector provides the same owner-oriented preview workflow, but does not push or
111
+ export directly to an assistant.
112
+
81
113
  ### Deep Links
82
114
 
83
115
  Open a note in the desktop app via URL scheme:
@@ -151,7 +183,7 @@ notesia import ~/Documents/notes
151
183
  notesia import ./project-docs --folder "Work" --tags "project,2026"
152
184
 
153
185
  # Import HTML, PDF, DOCX and JSON files too
154
- notesia import ./archive --ext md,txt,html,pdf,docx,json
186
+ notesia import ./archive --ext md,txt,html,htm,pdf,docx,json
155
187
 
156
188
  # Overwrite existing notes with the same title
157
189
  notesia import ./updated-notes --conflict overwrite
@@ -178,9 +210,12 @@ notesia kb search --query "project plan" --limit 10
178
210
  # Ask KB directly (searches notes and todos)
179
211
  notesia kb ask --query "what are my pending tasks?"
180
212
 
181
- # Load full context for AI prompt (returns JSON with full content)
213
+ # Load source context for a controlled external handoff (returns JSON with full content)
182
214
  notesia kb context --query "Q1 roadmap" --limit 5
183
215
 
216
+ # Save context for a trusted external assistant workflow
217
+ notesia kb context --query "How does folder sync work?" --limit 5 > notesia-context.json
218
+
184
219
  # Continue a KB conversation across calls
185
220
  notesia kb ask --query "what did I change yesterday?"
186
221
  notesia kb ask --query "and what about folder sync?"
package/bin/notesia.mjs CHANGED
@@ -4,29 +4,38 @@ import { fileURLToPath } from 'url';
4
4
  import { dirname, resolve } from 'path';
5
5
  import { runCli } from '../src/commands.mjs';
6
6
  import { runImport } from '../src/import.mjs';
7
+ import { runMcpServer } from '../src/mcp.mjs';
7
8
 
8
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
9
10
  const require = createRequire(import.meta.url);
10
11
 
11
12
  const argv = process.argv.slice(2);
13
+ const { version } = require(resolve(__dirname, '../package.json'));
12
14
 
13
15
  // Handle version flag / command
14
16
  if (argv[0] === 'version' || argv[0] === '-v' || argv[0] === '--version') {
15
- const { version } = require(resolve(__dirname, '../package.json'));
16
17
  process.stdout.write(`notesia v${version}\n`);
17
18
  process.exit(0);
18
19
  }
19
20
 
20
- // Dispatch `notesia import` to the dedicated import handler
21
+ const ARG_ERROR_CODES = new Set(['INVALID_ARGS', 'INVALID_OP', 'MISSING_ARGS', 'SELECTOR_REQUIRED']);
22
+
23
+ // Dispatch `notesia import` and `notesia mcp` to dedicated handlers
21
24
  if (argv[0] === 'import') {
22
25
  runImport(argv.slice(1)).catch((error) => {
23
26
  process.stderr.write(`${error?.message || 'notesia import failed'}\n`);
24
27
  process.exit(1);
25
28
  });
29
+ } else if (argv[0] === 'mcp') {
30
+ runMcpServer(argv.slice(1), { serverVersion: version }).catch((error) => {
31
+ process.stderr.write(`${error?.message || 'notesia mcp failed'}\n`);
32
+ process.exit(1);
33
+ });
26
34
  } else {
27
35
  runCli(argv).catch((error) => {
28
36
  const message = error?.message || 'notesia CLI failed';
29
- process.stderr.write(`${message}\n`);
30
- process.exit(1);
37
+ const prefix = error?.code ? `${error.code}: ` : '';
38
+ process.stderr.write(`${prefix}${message}\n`);
39
+ process.exit(ARG_ERROR_CODES.has(error?.code) ? 2 : 1);
31
40
  });
32
41
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@clarionstack/notesia",
3
3
  "private": false,
4
- "version": "0.1.1",
4
+ "version": "0.2.1",
5
5
  "description": "Notesia desktop bridge CLI — read, write, and bulk-import notes",
6
6
  "type": "module",
7
7
  "files": [
package/src/commands.mjs CHANGED
@@ -11,14 +11,43 @@ import {
11
11
  printAuthStatusResult,
12
12
  printKbResult,
13
13
  printTagsResult,
14
+ printFolderListResult,
15
+ printFolderMutationResult,
14
16
  readInputContent as defaultReadInputContent,
15
17
  } from './io.mjs';
16
18
 
17
- const SUPPORTED_OPS = new Set(['get', 'list', 'store', 'update', 'append', 'prepend', 'move', 'open', 'sync', 'auth-status', 'kb-search', 'kb-folders', 'kb-context', 'kb-ask', 'trash', 'search', 'capture', 'tags', 'tag-add', 'tag-remove']);
19
+ export const SUPPORTED_OPS = new Set([
20
+ 'get',
21
+ 'list',
22
+ 'store',
23
+ 'update',
24
+ 'append',
25
+ 'prepend',
26
+ 'move',
27
+ 'open',
28
+ 'sync',
29
+ 'auth-status',
30
+ 'kb-search',
31
+ 'kb-folders',
32
+ 'kb-context',
33
+ 'kb-ask',
34
+ 'trash',
35
+ 'search',
36
+ 'capture',
37
+ 'tags',
38
+ 'tag-add',
39
+ 'tag-remove',
40
+ 'folder-list',
41
+ 'folder-create',
42
+ 'folder-rename',
43
+ 'folder-move',
44
+ 'folder-delete',
45
+ ]);
18
46
  const OP_ALIASES = new Map([
19
47
  ['retrieve', 'get'],
20
48
  ['storage', 'store'],
21
49
  ['whoami', 'auth-status'],
50
+ ['folders', 'folder-list'],
22
51
  ]);
23
52
  const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
24
53
  const KB_SESSION_TTL_MS = 24 * 60 * 60 * 1000;
@@ -140,6 +169,18 @@ function readFlagValue(args, index) {
140
169
  return value;
141
170
  }
142
171
 
172
+ function parseOptionalFolderId(rawValue, flagName) {
173
+ const normalized = String(rawValue ?? '').trim().toLowerCase();
174
+ if (normalized === '0' || normalized === 'null' || normalized === 'root') {
175
+ return 0;
176
+ }
177
+ const numeric = Number(rawValue);
178
+ if (!Number.isFinite(numeric) || numeric < 0) {
179
+ throw new CliCommandError('INVALID_ARGS', `${flagName} must be a non-negative number (or 0/null/root)`);
180
+ }
181
+ return numeric;
182
+ }
183
+
143
184
  export function parseArgs(argv = []) {
144
185
  const args = [...argv];
145
186
  const rawOp = args.shift();
@@ -186,6 +227,24 @@ export function parseArgs(argv = []) {
186
227
  op = tagOps[subcommand];
187
228
  }
188
229
 
230
+ if (rawOp === 'folder') {
231
+ const subcommand = args.shift();
232
+ if (!subcommand || subcommand === '--help' || subcommand === '-h') {
233
+ return { op: 'help' };
234
+ }
235
+ const folderOps = {
236
+ list: 'folder-list',
237
+ create: 'folder-create',
238
+ rename: 'folder-rename',
239
+ move: 'folder-move',
240
+ delete: 'folder-delete',
241
+ };
242
+ if (!folderOps[subcommand]) {
243
+ throw new CliCommandError('INVALID_OP', `Unsupported folder command: ${subcommand}. Use list, create, rename, move, or delete.`);
244
+ }
245
+ op = folderOps[subcommand];
246
+ }
247
+
189
248
  if (rawOp === 'search') {
190
249
  if (args.length > 0 && !args[0].startsWith('--')) {
191
250
  args.unshift('--query', args.shift());
@@ -205,9 +264,14 @@ export function parseArgs(argv = []) {
205
264
  id: null,
206
265
  supabaseId: null,
207
266
  title: null,
267
+ matchTitle: null,
268
+ name: null,
269
+ icon: null,
208
270
  folderId: null,
271
+ parentId: null,
209
272
  content: undefined,
210
273
  limit: null,
274
+ offset: null,
211
275
  threshold: null,
212
276
  withMeta: false,
213
277
  query: null,
@@ -244,11 +308,14 @@ export function parseArgs(argv = []) {
244
308
  continue;
245
309
  }
246
310
 
311
+ if (token === '--match-title') {
312
+ parsed.matchTitle = readFlagValue(args, i);
313
+ i += 1;
314
+ continue;
315
+ }
316
+
247
317
  if (token === '--folder-id') {
248
- parsed.folderId = Number(readFlagValue(args, i));
249
- if (!Number.isFinite(parsed.folderId)) {
250
- throw new CliCommandError('INVALID_ARGS', '--folder-id must be a number');
251
- }
318
+ parsed.folderId = parseOptionalFolderId(readFlagValue(args, i), '--folder-id');
252
319
  i += 1;
253
320
  continue;
254
321
  }
@@ -272,6 +339,34 @@ export function parseArgs(argv = []) {
272
339
  continue;
273
340
  }
274
341
 
342
+ if (token === '--offset') {
343
+ const offset = Number(readFlagValue(args, i));
344
+ if (!Number.isFinite(offset) || offset < 0) {
345
+ throw new CliCommandError('INVALID_ARGS', '--offset must be a non-negative number');
346
+ }
347
+ parsed.offset = Math.floor(offset);
348
+ i += 1;
349
+ continue;
350
+ }
351
+
352
+ if (token === '--name') {
353
+ parsed.name = readFlagValue(args, i);
354
+ i += 1;
355
+ continue;
356
+ }
357
+
358
+ if (token === '--icon') {
359
+ parsed.icon = readFlagValue(args, i);
360
+ i += 1;
361
+ continue;
362
+ }
363
+
364
+ if (token === '--parent-id') {
365
+ parsed.parentId = parseOptionalFolderId(readFlagValue(args, i), '--parent-id');
366
+ i += 1;
367
+ continue;
368
+ }
369
+
275
370
  if (token === '--threshold') {
276
371
  const threshold = Number(readFlagValue(args, i));
277
372
  if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
@@ -324,13 +419,28 @@ export function parseArgs(argv = []) {
324
419
  continue;
325
420
  }
326
421
 
422
+ if (token === '--tags') {
423
+ const rawTags = readFlagValue(args, i);
424
+ for (const item of rawTags.split(',')) {
425
+ const trimmed = item.trim();
426
+ if (trimmed) parsed.tags.push(trimmed);
427
+ }
428
+ i += 1;
429
+ continue;
430
+ }
431
+
327
432
  throw new CliCommandError('INVALID_ARGS', `Unknown argument: ${token} `);
328
433
  }
329
434
 
330
435
  const selector = {};
331
436
  if (parsed.id !== null) selector.id = parsed.id;
332
437
  if (parsed.supabaseId) selector.supabase_id = parsed.supabaseId;
333
- if (parsed.title && (op === 'get' || op === 'open')) selector.title = parsed.title;
438
+ const titleSelectorOps = new Set(['get', 'open', 'append', 'prepend', 'move', 'trash', 'tag-add', 'tag-remove']);
439
+ if (parsed.matchTitle) {
440
+ selector.title = parsed.matchTitle;
441
+ } else if (parsed.title && titleSelectorOps.has(op)) {
442
+ selector.title = parsed.title;
443
+ }
334
444
  if (Object.keys(selector).length > 0) parsed.selector = selector;
335
445
 
336
446
  return parsed;
@@ -342,24 +452,30 @@ function usageText() {
342
452
  '',
343
453
  'Commands:',
344
454
  ' get --id <id>|--supabase-id <uuid>|--title <title> [--json] [--with-meta]',
345
- ' list [--limit <count>] [--format table|json]',
455
+ ' list [--limit <count>] [--offset <n>] [--folder-id <id>] [--tag <tag>] [--format table|json]',
346
456
  ' store [--title <title>] [--tag <tag>]... [--folder-id <id>] [--content <text>]',
347
457
  ' capture [--title <title>] [--tag <tag>]... [--content <text>] (saves to Inbox)',
348
- ' update --id <id>|--supabase-id <uuid>|--title <title> [--content <text>] [--title <new>]',
349
- ' append --id <id>|--supabase-id <uuid>|--title <title> [--content <text>]',
350
- ' prepend --id <id>|--supabase-id <uuid>|--title <title> [--content <text>]',
458
+ ' update --id <id>|--supabase-id <uuid>|--match-title <title> [--content <text>] [--title <new>]',
459
+ ' append --id <id>|--supabase-id <uuid>|--match-title <title> [--content <text>]',
460
+ ' prepend --id <id>|--supabase-id <uuid>|--match-title <title> [--content <text>]',
351
461
  ' search <query>|--query <text> [--limit <n>] [--threshold <0-1>] [--format text|json]',
352
- ' move --id <id>|--supabase-id <uuid>|--title <title> --folder-id <id> (0 = root)',
462
+ ' move --id <id>|--supabase-id <uuid>|--match-title <title> --folder-id <id> (0 = root)',
353
463
  ' open --id <id>|--supabase-id <uuid>|--title <title>',
354
- ' trash --id <id>|--supabase-id <uuid>|--title <title>',
464
+ ' trash --id <id>|--supabase-id <uuid>|--match-title <title>',
355
465
  ' tags [--format table|json]',
356
- ' tag add --id <id>|... --tag <name> [--tag <name2>]...',
357
- ' tag remove --id <id>|... --tag <name> [--tag <name2>]...',
466
+ ' tag add --id <id>|--supabase-id <uuid>|--match-title <title> --tag <name> [--tag <name2>]...',
467
+ ' tag remove --id <id>|--supabase-id <uuid>|--match-title <title> --tag <name> [--tag <name2>]...',
468
+ ' folder list [--format table|json] (alias: folders)',
469
+ ' folder create --name <name> [--parent-id <id>] [--icon <icon>] [--format text|json]',
470
+ ' folder rename --id <id> --name <new> [--format text|json]',
471
+ ' folder move --id <id> --parent-id <id> [--format text|json] (0/null = root)',
472
+ ' folder delete --id <id> [--format text|json] (empty folders only)',
473
+ ' mcp (start stdio MCP server for external AI agents)',
358
474
  ' sync',
359
475
  ' auth status [--format text|json]',
360
476
  '',
361
477
  'Bulk Import:',
362
- ' import <path> [--ext md,txt,pdf,docx,json] [--folder <name>] [--tags <list>]',
478
+ ' import <path> [--ext md,txt,html,htm,pdf,docx,json] [--folder <name>] [--tags <list>]',
363
479
  ' [--conflict skip|overwrite] [--dry-run]',
364
480
  ' [--format text|json] [--quiet] [--verbose]',
365
481
  '',
@@ -404,9 +520,17 @@ function buildPayload(parsed, pipedContent) {
404
520
  }
405
521
 
406
522
  if (parsed.op === 'list') {
407
- return {
523
+ const payload = {
408
524
  limit: parsed.limit ?? 100,
525
+ offset: parsed.offset ?? 0,
409
526
  };
527
+ if (parsed.folderId !== null && parsed.folderId !== undefined) {
528
+ payload.folder_id = parsed.folderId === 0 ? null : parsed.folderId;
529
+ }
530
+ if (parsed.tags.length > 0) {
531
+ payload.tag = parsed.tags[0];
532
+ }
533
+ return payload;
410
534
  }
411
535
 
412
536
  if (parsed.op === 'sync') {
@@ -420,7 +544,7 @@ function buildPayload(parsed, pipedContent) {
420
544
  if (parsed.op === 'store') {
421
545
  return {
422
546
  title: parsed.title || undefined,
423
- folder_id: parsed.folderId ?? null,
547
+ folder_id: parsed.folderId === null || parsed.folderId === undefined || parsed.folderId === 0 ? null : parsed.folderId,
424
548
  content: parsed.content ?? pipedContent ?? '',
425
549
  tags: parsed.tags,
426
550
  };
@@ -548,6 +672,54 @@ function buildPayload(parsed, pipedContent) {
548
672
  };
549
673
  }
550
674
 
675
+ if (parsed.op === 'folder-list') {
676
+ return {};
677
+ }
678
+
679
+ if (parsed.op === 'folder-create') {
680
+ if (!parsed.name || !parsed.name.trim()) {
681
+ throw new CliCommandError('MISSING_ARGS', '--name is required for folder create');
682
+ }
683
+ return {
684
+ name: parsed.name.trim(),
685
+ parent_id: parsed.parentId === null || parsed.parentId === undefined || parsed.parentId === 0 ? null : parsed.parentId,
686
+ ...(parsed.icon ? { icon: parsed.icon } : {}),
687
+ };
688
+ }
689
+
690
+ if (parsed.op === 'folder-rename') {
691
+ if (parsed.id === null || parsed.id === undefined) {
692
+ throw new CliCommandError('MISSING_ARGS', '--id is required for folder rename');
693
+ }
694
+ if (!parsed.name || !parsed.name.trim()) {
695
+ throw new CliCommandError('MISSING_ARGS', '--name is required for folder rename');
696
+ }
697
+ return {
698
+ id: parsed.id,
699
+ name: parsed.name.trim(),
700
+ };
701
+ }
702
+
703
+ if (parsed.op === 'folder-move') {
704
+ if (parsed.id === null || parsed.id === undefined) {
705
+ throw new CliCommandError('MISSING_ARGS', '--id is required for folder move');
706
+ }
707
+ if (parsed.parentId === null || parsed.parentId === undefined) {
708
+ throw new CliCommandError('MISSING_ARGS', '--parent-id is required for folder move (use 0 for root)');
709
+ }
710
+ return {
711
+ id: parsed.id,
712
+ parent_id: parsed.parentId === 0 ? null : parsed.parentId,
713
+ };
714
+ }
715
+
716
+ if (parsed.op === 'folder-delete') {
717
+ if (parsed.id === null || parsed.id === undefined) {
718
+ throw new CliCommandError('MISSING_ARGS', '--id is required for folder delete');
719
+ }
720
+ return { id: parsed.id };
721
+ }
722
+
551
723
  throw new CliCommandError('INVALID_OP', `Unsupported command: ${parsed.op} `);
552
724
  }
553
725
 
@@ -616,6 +788,10 @@ export async function runCli(argv = [], {
616
788
  printOpenResult(response.data, { format: parsed.format, writeStdout });
617
789
  } else if (parsed.op === 'tags') {
618
790
  printTagsResult(response.data, { format: parsed.format === 'text' ? 'table' : parsed.format, writeStdout });
791
+ } else if (parsed.op === 'folder-list') {
792
+ printFolderListResult(response.data, { format: parsed.format === 'text' ? 'table' : parsed.format, writeStdout });
793
+ } else if (['folder-create', 'folder-rename', 'folder-move', 'folder-delete'].includes(parsed.op)) {
794
+ printFolderMutationResult(response.data, { format: parsed.format, writeStdout });
619
795
  } else if (['search', 'kb-search', 'kb-folders', 'kb-context', 'kb-ask'].includes(parsed.op)) {
620
796
  printKbResult(parsed.op === 'search' ? 'kb-search' : parsed.op, response.data, { format: parsed.format, writeStdout });
621
797
  } else {
package/src/import.mjs CHANGED
@@ -8,13 +8,12 @@
8
8
 
9
9
  import fs from 'node:fs/promises';
10
10
  import path from 'node:path';
11
- import readline from 'node:readline';
12
11
  import { requestBridge } from './client.mjs';
13
12
 
14
13
  const NOTE_CHAR_LIMIT = 100_000;
15
14
  const BRIDGE_MAX_REQUEST_BYTES = 1024 * 1024;
16
15
  const BRIDGE_TARGET_REQUEST_BYTES = Math.floor(BRIDGE_MAX_REQUEST_BYTES * 0.9);
17
- const DEFAULT_EXTENSIONS = ['md', 'txt', 'pdf', 'docx', 'json'];
16
+ const DEFAULT_EXTENSIONS = ['md', 'txt', 'html', 'htm', 'pdf', 'docx', 'json'];
18
17
  const JSON_MAX_DEPTH = 12;
19
18
  const JSON_MAX_ENTRIES = 5_000;
20
19
  const JSON_MAX_ARRAY_ITEMS = 100;
@@ -179,15 +178,6 @@ function titleFromPath(filePath, relativePath) {
179
178
  return stem;
180
179
  }
181
180
 
182
- function stripHtml(html) {
183
- return html
184
- .replace(/<br\s*\/?>/gi, '\n')
185
- .replace(/<[^>]+>/g, '')
186
- .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
187
- .replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, ' ')
188
- .trim();
189
- }
190
-
191
181
  function decodeXmlEntities(value) {
192
182
  if (!value) return '';
193
183
  return value
@@ -458,13 +448,17 @@ async function parseFile(absolutePath, extension, relativePath) {
458
448
  try {
459
449
  if (extension === 'md' || extension === 'txt') {
460
450
  const body = await fs.readFile(absolutePath, 'utf8');
461
- return { title: defaultTitle, body };
451
+ return {
452
+ title: defaultTitle,
453
+ body,
454
+ contentFormat: extension === 'md' ? 'markdown' : 'text',
455
+ };
462
456
  }
463
457
  if (extension === 'html' || extension === 'htm') {
464
458
  const raw = await fs.readFile(absolutePath, 'utf8');
465
459
  const titleMatch = raw.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
466
460
  const htmlTitle = titleMatch ? titleMatch[1].replace(/\s+/g, ' ').trim() : null;
467
- return { title: htmlTitle || defaultTitle, body: stripHtml(raw) };
461
+ return { title: htmlTitle || defaultTitle, body: raw, contentFormat: 'html' };
468
462
  }
469
463
  if (extension === 'json') {
470
464
  const sourcePath = relativePath || path.basename(absolutePath);
@@ -634,6 +628,7 @@ function normalizeImportItem(item) {
634
628
  return {
635
629
  title: item.title,
636
630
  content: item._parseError ? '' : item.content,
631
+ content_format: item.content_format,
637
632
  source_path: item.source_path,
638
633
  _parseError: item._parseError || null,
639
634
  };
@@ -735,26 +730,6 @@ function printResult(result, opts) {
735
730
  }
736
731
  }
737
732
 
738
- // ─── Interactive prompt ──────────────────────────────────────────────────────
739
-
740
- function createInterface() {
741
- return readline.createInterface({
742
- input: process.stdin,
743
- output: process.stdout,
744
- });
745
- }
746
-
747
- async function promptYesNo(question) {
748
- return new Promise((resolve) => {
749
- const rl = createInterface();
750
- rl.question(question, (answer) => {
751
- rl.close();
752
- const normalized = answer.trim().toLowerCase();
753
- resolve(normalized === 'y' || normalized === 'yes');
754
- });
755
- });
756
- }
757
-
758
733
  // ─── Main entry point ────────────────────────────────────────────────────────
759
734
 
760
735
  export async function runImport(argv, deps = {}) {
@@ -784,13 +759,26 @@ export async function runImport(argv, deps = {}) {
784
759
 
785
760
  if (parsed.error && !parsed.body) {
786
761
  if (opts.verbose) process.stderr.write(` [failed] ${file.relativePath} — ${parsed.error}\n`);
787
- items.push({ title: parsed.title, content: '', source_path: file.relativePath, _parseError: parsed.error });
762
+ items.push({
763
+ title: parsed.title,
764
+ content: '',
765
+ content_format: parsed.contentFormat,
766
+ source_path: file.relativePath,
767
+ _parseError: parsed.error,
768
+ });
788
769
  continue;
789
770
  }
790
771
 
791
772
  const chunks = splitContent(parsed.title, parsed.body);
792
- for (const chunk of chunks) {
793
- items.push({ title: chunk.title, content: chunk.content, source_path: file.relativePath });
773
+ for (const [chunkIndex, chunk] of chunks.entries()) {
774
+ items.push({
775
+ title: chunk.title,
776
+ content: chunk.content,
777
+ content_format: parsed.contentFormat,
778
+ source_path: chunkIndex === 0
779
+ ? file.relativePath
780
+ : `${file.relativePath}#part-${chunkIndex + 1}`,
781
+ });
794
782
  }
795
783
 
796
784
  if (opts.verbose) {
@@ -809,11 +797,10 @@ export async function runImport(argv, deps = {}) {
809
797
  failed: 0,
810
798
  items: [],
811
799
  };
812
- let createMissingFolder = false;
813
800
 
814
801
  for (let batchIndex = 0; batchIndex < itemBatches.length; batchIndex += 1) {
815
802
  const batchItems = itemBatches[batchIndex];
816
- let payload = buildBulkImportPayload(batchItems, opts, createMissingFolder);
803
+ const payload = buildBulkImportPayload(batchItems, opts, opts.createFolder);
817
804
 
818
805
  if (opts.verbose) {
819
806
  const estimatedBytes = estimateBridgeRequestBytes(payload);
@@ -826,8 +813,8 @@ export async function runImport(argv, deps = {}) {
826
813
  let response;
827
814
  try {
828
815
  response = await bridge({ op: 'bulk_import', payload }, { timeoutMs });
829
- process.stderr.write(` [debug] bridge response ok: ${response?.ok}, hasData: ${!!response?.data}\n`);
830
816
  if (opts.verbose || !response?.ok) {
817
+ process.stderr.write(` [debug] bridge response ok: ${response?.ok}, hasData: ${!!response?.data}\n`);
831
818
  process.stderr.write(` [debug] full response: ${JSON.stringify(response)}\n`);
832
819
  }
833
820
  } catch (err) {
@@ -842,39 +829,8 @@ export async function runImport(argv, deps = {}) {
842
829
 
843
830
  let bridgeError = getBridgeError(response);
844
831
 
845
- // Folder prompt flow happens once, then the same batch is retried with create_folder_if_missing=true.
846
- if (bridgeError?.code === 'FOLDER_NOT_FOUND' && opts.folder && opts.createFolder && !createMissingFolder) {
847
- const folderName = bridgeError?.details?.folderName || opts.folder;
848
- process.stdout.write(`\nFolder "${folderName}" does not exist in Notesia.\n`);
849
- const shouldCreate = await promptYesNo('Do you want to create it and continue import? [y/N] ');
850
- if (!shouldCreate) {
851
- process.stderr.write('Import cancelled.\n');
852
- process.exit(1);
853
- }
854
-
855
- createMissingFolder = true;
856
- payload = buildBulkImportPayload(batchItems, opts, true);
857
- try {
858
- response = await bridge({ op: 'bulk_import', payload }, { timeoutMs });
859
- process.stderr.write(` [debug] bridge response ok: ${response?.ok}, hasData: ${!!response?.data}\n`);
860
- if (opts.verbose || !response?.ok) {
861
- process.stderr.write(` [debug] full response: ${JSON.stringify(response)}\n`);
862
- }
863
- } catch (err) {
864
- const code = err.code || 'BRIDGE_ERROR';
865
- if (code === 'NOTESIA_APP_NOT_RUNNING') {
866
- process.stderr.write('NOTESIA_APP_NOT_RUNNING\n');
867
- process.exit(1);
868
- }
869
- process.stderr.write(`[${code}] ${err.message}\n`);
870
- process.exit(1);
871
- }
872
-
873
- bridgeError = getBridgeError(response);
874
- }
875
-
876
832
  if (bridgeError) {
877
- if (bridgeError.code === 'FOLDER_NOT_FOUND' && opts.folder && !opts.createFolder) {
833
+ if (bridgeError.code === 'FOLDER_NOT_FOUND' && opts.folder) {
878
834
  process.stderr.write(`[${bridgeError.code}] ${bridgeError.message}\n`);
879
835
  process.exit(1);
880
836
  }
package/src/io.mjs CHANGED
@@ -129,7 +129,11 @@ export function printListResult(result, {
129
129
 
130
130
  writeStdout(buildListTable(notes));
131
131
  if (typeof result?.total === 'number') {
132
- writeStdout(`Total: ${result.total}\n`);
132
+ const details = [];
133
+ if (typeof result?.offset === 'number' && result.offset > 0) details.push(`offset: ${result.offset}`);
134
+ if (result?.has_more) details.push('more available');
135
+ const suffix = details.length > 0 ? ` (${details.join(', ')})` : '';
136
+ writeStdout(`Total: ${result.total}${suffix}\n`);
133
137
  }
134
138
  }
135
139
 
@@ -262,3 +266,53 @@ export function printKbResult(op, result, {
262
266
  // Fallback for unknown kb ops
263
267
  writeStdout(`${JSON.stringify(result ?? {}, null, 2)}\n`);
264
268
  }
269
+
270
+ export function printFolderListResult(result, {
271
+ format = 'table',
272
+ writeStdout = defaultWriteStdout,
273
+ } = {}) {
274
+ if (format === 'json') {
275
+ writeStdout(`${JSON.stringify(result ?? { folders: [], total: 0, root_note_count: 0 }, null, 2)}\n`);
276
+ return;
277
+ }
278
+
279
+ const folders = Array.isArray(result?.folders) ? result.folders : [];
280
+ if (folders.length === 0) {
281
+ writeStdout('No folders found.\n');
282
+ if (typeof result?.root_note_count === 'number') {
283
+ writeStdout(`Root (unfoldered) notes: ${result.root_note_count}\n`);
284
+ }
285
+ return;
286
+ }
287
+
288
+ const headers = ['ID', 'PARENT_ID', 'NAME', 'NOTES', 'SYSTEM'];
289
+ const rows = folders.map((f) => [
290
+ formatCell(f.id),
291
+ formatCell(f.parent_id ?? '-'),
292
+ truncate(formatCell(f.name), 40),
293
+ formatCell(f.note_count ?? 0),
294
+ f.is_system ? 'yes' : 'no',
295
+ ]);
296
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
297
+ const renderRow = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();
298
+ const lines = [renderRow(headers), widths.map((w) => '-'.repeat(w)).join(' '), ...rows.map(renderRow)];
299
+ writeStdout(`${lines.join('\n')}\n`);
300
+ if (typeof result?.root_note_count === 'number') {
301
+ writeStdout(`Root (unfoldered) notes: ${result.root_note_count}\n`);
302
+ }
303
+ }
304
+
305
+ export function printFolderMutationResult(result, {
306
+ format = 'text',
307
+ writeStdout = defaultWriteStdout,
308
+ } = {}) {
309
+ if (format === 'json') {
310
+ writeStdout(`${JSON.stringify(result ?? { ok: true }, null, 2)}\n`);
311
+ return;
312
+ }
313
+ if (result?.folder) {
314
+ writeStdout(`ok (folder id: ${result.folder.id}, name: ${result.folder.name})\n`);
315
+ return;
316
+ }
317
+ writeStdout('ok\n');
318
+ }
package/src/mcp.mjs ADDED
@@ -0,0 +1,603 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import readline from 'node:readline';
3
+ import { requestBridge as defaultRequestBridge } from './client.mjs';
4
+
5
+ const SUPPORTED_PROTOCOL_VERSIONS = new Set([
6
+ '2025-06-18',
7
+ '2025-03-26',
8
+ '2024-11-05',
9
+ ]);
10
+ const DEFAULT_PROTOCOL_VERSION = '2024-11-05';
11
+ const MAX_CONTENT_BYTES = 512 * 1024;
12
+
13
+ function normalizeSelector(args = {}) {
14
+ const selector = {};
15
+ if (args.id !== undefined && args.id !== null) {
16
+ const numericId = Number(args.id);
17
+ if (!Number.isFinite(numericId)) {
18
+ throw new Error('id must be a number');
19
+ }
20
+ selector.id = numericId;
21
+ }
22
+ if (typeof args.supabase_id === 'string' && args.supabase_id.trim()) {
23
+ selector.supabase_id = args.supabase_id.trim();
24
+ }
25
+ const titleSelector = args.match_title ?? args.title;
26
+ if (typeof titleSelector === 'string' && titleSelector.length > 0 && Object.keys(selector).length === 0) {
27
+ selector.title = titleSelector;
28
+ } else if (typeof args.match_title === 'string' && args.match_title.length > 0) {
29
+ selector.title = args.match_title;
30
+ }
31
+ if (Object.keys(selector).length === 0) {
32
+ throw new Error('One of id, supabase_id, or title/match_title is required');
33
+ }
34
+ return selector;
35
+ }
36
+
37
+ function assertContentWithinLimit(content) {
38
+ if (typeof content !== 'string') {
39
+ throw new Error('content must be a string');
40
+ }
41
+ if (Buffer.byteLength(content, 'utf8') > MAX_CONTENT_BYTES) {
42
+ throw new Error('content exceeds 512 KB limit');
43
+ }
44
+ return content;
45
+ }
46
+
47
+ function normalizeOptionalParentId(value) {
48
+ if (value === undefined || value === null || value === 0) {
49
+ return null;
50
+ }
51
+ const numericValue = Number(value);
52
+ if (!Number.isFinite(numericValue) || numericValue < 0) {
53
+ throw new Error('parent_id must be a non-negative number');
54
+ }
55
+ return numericValue === 0 ? null : numericValue;
56
+ }
57
+
58
+ const SELECTOR_PROPERTIES = {
59
+ id: { type: 'number', description: 'Local numeric note ID.' },
60
+ supabase_id: { type: 'string', description: 'Remote UUID of the note.' },
61
+ match_title: { type: 'string', description: 'Exact title to match (fails if ambiguous).' },
62
+ };
63
+
64
+ export const MCP_TOOLS = [
65
+ {
66
+ name: 'auth_status',
67
+ description: 'Check whether the Notesia desktop app bridge is running and authenticated.',
68
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
69
+ op: 'auth-status',
70
+ toPayload: () => ({}),
71
+ },
72
+ {
73
+ name: 'list_notes',
74
+ description: 'List active non-secure notes with pagination and optional folder_id or tag filter.',
75
+ inputSchema: {
76
+ type: 'object',
77
+ properties: {
78
+ limit: { type: 'number', description: 'Max notes to return (1-1000, default 100).' },
79
+ offset: { type: 'number', description: 'Pagination offset (default 0).' },
80
+ folder_id: { type: 'number', description: 'Filter by folder ID; use 0 for unfoldered root notes.' },
81
+ tag: { type: 'string', description: 'Filter by tag name (case-insensitive).' },
82
+ },
83
+ additionalProperties: false,
84
+ },
85
+ op: 'list',
86
+ toPayload: (args = {}) => {
87
+ const payload = {
88
+ limit: args.limit ?? 100,
89
+ offset: args.offset ?? 0,
90
+ };
91
+ if (args.folder_id !== undefined) {
92
+ payload.folder_id = args.folder_id === null || args.folder_id === 0 ? null : Number(args.folder_id);
93
+ }
94
+ if (typeof args.tag === 'string' && args.tag.trim()) {
95
+ payload.tag = args.tag.trim();
96
+ }
97
+ return payload;
98
+ },
99
+ },
100
+ {
101
+ name: 'search_notes',
102
+ description: 'Search active non-secure notes by title and content.',
103
+ inputSchema: {
104
+ type: 'object',
105
+ properties: {
106
+ query: { type: 'string', description: 'Search query text.' },
107
+ limit: { type: 'number', description: 'Max results to return (default 20).' },
108
+ },
109
+ required: ['query'],
110
+ additionalProperties: false,
111
+ },
112
+ op: 'kb-search',
113
+ toPayload: (args = {}) => ({
114
+ query: String(args.query ?? ''),
115
+ limit: args.limit ?? 20,
116
+ }),
117
+ },
118
+ {
119
+ name: 'get_note',
120
+ description: 'Read a non-secure note by id, supabase_id, or exact title. Returns Markdown content and metadata.',
121
+ inputSchema: {
122
+ type: 'object',
123
+ properties: {
124
+ id: SELECTOR_PROPERTIES.id,
125
+ supabase_id: SELECTOR_PROPERTIES.supabase_id,
126
+ title: { type: 'string', description: 'Exact title of the note.' },
127
+ },
128
+ additionalProperties: false,
129
+ },
130
+ op: 'get',
131
+ toPayload: (args = {}) => ({ selector: normalizeSelector(args) }),
132
+ },
133
+ {
134
+ name: 'create_note',
135
+ description: 'Create a new Markdown note locally and enqueue it for cloud sync.',
136
+ inputSchema: {
137
+ type: 'object',
138
+ properties: {
139
+ title: { type: 'string', description: 'Note title.' },
140
+ content: { type: 'string', description: 'Markdown body content (max 512 KB).' },
141
+ folder_id: { type: 'number', description: 'Target folder ID (omit or 0 for root).' },
142
+ tags: { type: 'array', items: { type: 'string' }, description: 'Initial tag names.' },
143
+ },
144
+ additionalProperties: false,
145
+ },
146
+ op: 'store',
147
+ toPayload: (args = {}) => ({
148
+ ...(args.title ? { title: String(args.title) } : {}),
149
+ folder_id: normalizeOptionalParentId(args.folder_id),
150
+ content: args.content !== undefined ? assertContentWithinLimit(args.content) : '',
151
+ tags: Array.isArray(args.tags) ? args.tags.map(String) : [],
152
+ }),
153
+ },
154
+ {
155
+ name: 'update_note',
156
+ description: 'Replace an existing note title and/or Markdown content.',
157
+ inputSchema: {
158
+ type: 'object',
159
+ properties: {
160
+ ...SELECTOR_PROPERTIES,
161
+ title: { type: 'string', description: 'New title to set on the note.' },
162
+ content: { type: 'string', description: 'New Markdown content (max 512 KB).' },
163
+ },
164
+ additionalProperties: false,
165
+ },
166
+ op: 'update',
167
+ toPayload: (args = {}) => {
168
+ const hasContent = args.content !== undefined;
169
+ const hasTitle = typeof args.title === 'string' && args.title.trim().length > 0;
170
+ if (!hasContent && !hasTitle) {
171
+ throw new Error('Provide content and/or a non-empty new title');
172
+ }
173
+ return {
174
+ selector: normalizeSelector(args),
175
+ ...(hasContent ? { content: assertContentWithinLimit(args.content) } : {}),
176
+ ...(hasTitle ? { title: args.title } : {}),
177
+ };
178
+ },
179
+ },
180
+ {
181
+ name: 'append_note',
182
+ description: 'Append Markdown content to the end of an existing note.',
183
+ inputSchema: {
184
+ type: 'object',
185
+ properties: {
186
+ ...SELECTOR_PROPERTIES,
187
+ content: { type: 'string', description: 'Markdown text to append.' },
188
+ },
189
+ required: ['content'],
190
+ additionalProperties: false,
191
+ },
192
+ op: 'append',
193
+ toPayload: (args = {}) => ({
194
+ selector: normalizeSelector(args),
195
+ content: assertContentWithinLimit(args.content),
196
+ }),
197
+ },
198
+ {
199
+ name: 'prepend_note',
200
+ description: 'Prepend Markdown content before the existing body of a note.',
201
+ inputSchema: {
202
+ type: 'object',
203
+ properties: {
204
+ ...SELECTOR_PROPERTIES,
205
+ content: { type: 'string', description: 'Markdown text to prepend.' },
206
+ },
207
+ required: ['content'],
208
+ additionalProperties: false,
209
+ },
210
+ op: 'prepend',
211
+ toPayload: (args = {}) => ({
212
+ selector: normalizeSelector(args),
213
+ content: assertContentWithinLimit(args.content),
214
+ }),
215
+ },
216
+ {
217
+ name: 'move_note',
218
+ description: 'Move a note to another folder (pass folder_id: 0 or null to move to root).',
219
+ inputSchema: {
220
+ type: 'object',
221
+ properties: {
222
+ ...SELECTOR_PROPERTIES,
223
+ folder_id: { type: ['number', 'null'], description: 'Destination folder ID (0 or null for root).' },
224
+ },
225
+ required: ['folder_id'],
226
+ additionalProperties: false,
227
+ },
228
+ op: 'move',
229
+ toPayload: (args = {}) => ({
230
+ selector: normalizeSelector(args),
231
+ folder_id: normalizeOptionalParentId(args.folder_id),
232
+ }),
233
+ },
234
+ {
235
+ name: 'trash_note',
236
+ description: 'Soft-delete a note by moving it to Trash.',
237
+ inputSchema: {
238
+ type: 'object',
239
+ properties: { ...SELECTOR_PROPERTIES },
240
+ additionalProperties: false,
241
+ },
242
+ op: 'trash',
243
+ toPayload: (args = {}) => ({ selector: normalizeSelector(args) }),
244
+ },
245
+ {
246
+ name: 'list_tags',
247
+ description: 'List all tags with note counts.',
248
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
249
+ op: 'tags',
250
+ toPayload: () => ({}),
251
+ },
252
+ {
253
+ name: 'add_tags',
254
+ description: 'Add one or more tags to a note (creates missing tags automatically).',
255
+ inputSchema: {
256
+ type: 'object',
257
+ properties: {
258
+ ...SELECTOR_PROPERTIES,
259
+ tags: { type: 'array', items: { type: 'string' }, description: 'Tag names to add.' },
260
+ },
261
+ required: ['tags'],
262
+ additionalProperties: false,
263
+ },
264
+ op: 'tag-add',
265
+ toPayload: (args = {}) => {
266
+ if (!Array.isArray(args.tags) || args.tags.length === 0) {
267
+ throw new Error('tags must be a non-empty array');
268
+ }
269
+ return {
270
+ selector: normalizeSelector(args),
271
+ tags: args.tags.map(String),
272
+ };
273
+ },
274
+ },
275
+ {
276
+ name: 'remove_tags',
277
+ description: 'Remove one or more tags from a note.',
278
+ inputSchema: {
279
+ type: 'object',
280
+ properties: {
281
+ ...SELECTOR_PROPERTIES,
282
+ tags: { type: 'array', items: { type: 'string' }, description: 'Tag names to remove.' },
283
+ },
284
+ required: ['tags'],
285
+ additionalProperties: false,
286
+ },
287
+ op: 'tag-remove',
288
+ toPayload: (args = {}) => {
289
+ if (!Array.isArray(args.tags) || args.tags.length === 0) {
290
+ throw new Error('tags must be a non-empty array');
291
+ }
292
+ return {
293
+ selector: normalizeSelector(args),
294
+ tags: args.tags.map(String),
295
+ };
296
+ },
297
+ },
298
+ {
299
+ name: 'list_folders',
300
+ description: 'List all folders with parent_id, note counts, and root unfoldered note count.',
301
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
302
+ op: 'folder-list',
303
+ toPayload: () => ({}),
304
+ },
305
+ {
306
+ name: 'create_folder',
307
+ description: 'Create a new folder (optionally nested under parent_id).',
308
+ inputSchema: {
309
+ type: 'object',
310
+ properties: {
311
+ name: { type: 'string', description: 'Folder name.' },
312
+ parent_id: { type: ['number', 'null'], description: 'Parent folder ID (omit or 0 for root).' },
313
+ icon: { type: 'string', description: 'Optional Lucide icon name (default Folder).' },
314
+ },
315
+ required: ['name'],
316
+ additionalProperties: false,
317
+ },
318
+ op: 'folder-create',
319
+ toPayload: (args = {}) => ({
320
+ name: String(args.name ?? ''),
321
+ parent_id: normalizeOptionalParentId(args.parent_id),
322
+ ...(typeof args.icon === 'string' && args.icon.trim() ? { icon: args.icon.trim() } : {}),
323
+ }),
324
+ },
325
+ {
326
+ name: 'rename_folder',
327
+ description: 'Rename an existing non-system folder.',
328
+ inputSchema: {
329
+ type: 'object',
330
+ properties: {
331
+ id: { type: 'number', description: 'Folder ID to rename.' },
332
+ name: { type: 'string', description: 'New folder name.' },
333
+ },
334
+ required: ['id', 'name'],
335
+ additionalProperties: false,
336
+ },
337
+ op: 'folder-rename',
338
+ toPayload: (args = {}) => ({
339
+ id: Number(args.id),
340
+ name: String(args.name ?? ''),
341
+ }),
342
+ },
343
+ {
344
+ name: 'move_folder',
345
+ description: 'Move a non-system folder under another parent folder (0 or null for root).',
346
+ inputSchema: {
347
+ type: 'object',
348
+ properties: {
349
+ id: { type: 'number', description: 'Folder ID to move.' },
350
+ parent_id: { type: ['number', 'null'], description: 'Target parent folder ID (0 or null for root).' },
351
+ },
352
+ required: ['id', 'parent_id'],
353
+ additionalProperties: false,
354
+ },
355
+ op: 'folder-move',
356
+ toPayload: (args = {}) => ({
357
+ id: Number(args.id),
358
+ parent_id: normalizeOptionalParentId(args.parent_id),
359
+ }),
360
+ },
361
+ {
362
+ name: 'delete_folder',
363
+ description: 'Delete an empty non-system folder (refuses if folder contains notes or subfolders).',
364
+ inputSchema: {
365
+ type: 'object',
366
+ properties: {
367
+ id: { type: 'number', description: 'Empty folder ID to delete.' },
368
+ },
369
+ required: ['id'],
370
+ additionalProperties: false,
371
+ },
372
+ op: 'folder-delete',
373
+ toPayload: (args = {}) => ({ id: Number(args.id) }),
374
+ },
375
+ {
376
+ name: 'sync_notes',
377
+ description: 'Trigger a Notesia sync cycle to push queued local changes and pull remote updates.',
378
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
379
+ op: 'sync',
380
+ toPayload: () => ({}),
381
+ },
382
+ ];
383
+
384
+ const TOOL_BY_NAME = new Map(MCP_TOOLS.map((tool) => [tool.name, tool]));
385
+
386
+ export function createMcpMessageHandler({
387
+ requestBridge = defaultRequestBridge,
388
+ serverVersion = '0.2.1',
389
+ } = {}) {
390
+ return async function handleMcpMessage(message) {
391
+ if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') {
392
+ return {
393
+ jsonrpc: '2.0',
394
+ id: message?.id ?? null,
395
+ error: { code: -32600, message: 'Invalid Request' },
396
+ };
397
+ }
398
+
399
+ const { id, method, params } = message;
400
+
401
+ if (method === 'notifications/initialized' || method === 'notifications/cancelled') {
402
+ return null;
403
+ }
404
+
405
+ if (method === 'initialize') {
406
+ const requestedVersion = params?.protocolVersion;
407
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.has(requestedVersion)
408
+ ? requestedVersion
409
+ : DEFAULT_PROTOCOL_VERSION;
410
+ return {
411
+ jsonrpc: '2.0',
412
+ id,
413
+ result: {
414
+ protocolVersion,
415
+ capabilities: {
416
+ tools: {},
417
+ },
418
+ serverInfo: {
419
+ name: 'notesia',
420
+ version: serverVersion,
421
+ },
422
+ instructions: [
423
+ 'Connected to the local Notesia desktop app bridge.',
424
+ 'Use list_folders and list_notes/search_notes to inspect structure, get_note to read Markdown,',
425
+ 'create_folder/rename_folder/move_folder/delete_folder and create_note/update_note/move_note/add_tags/remove_tags',
426
+ 'to reorganize, and sync_notes to push changes. Secure (encrypted) notes and whiteboards are excluded.',
427
+ ].join(' '),
428
+ },
429
+ };
430
+ }
431
+
432
+ if (method === 'ping') {
433
+ return { jsonrpc: '2.0', id, result: {} };
434
+ }
435
+
436
+ if (method === 'tools/list') {
437
+ return {
438
+ jsonrpc: '2.0',
439
+ id,
440
+ result: {
441
+ tools: MCP_TOOLS.map(({ name, description, inputSchema }) => ({
442
+ name,
443
+ description,
444
+ inputSchema,
445
+ })),
446
+ },
447
+ };
448
+ }
449
+
450
+ if (method === 'tools/call') {
451
+ const toolName = params?.name;
452
+ const tool = TOOL_BY_NAME.get(toolName);
453
+ if (!tool) {
454
+ return {
455
+ jsonrpc: '2.0',
456
+ id,
457
+ error: { code: -32602, message: `Unknown tool: ${toolName || 'unknown'}` },
458
+ };
459
+ }
460
+
461
+ try {
462
+ const payload = tool.toPayload(params?.arguments || {});
463
+ const response = await requestBridge({
464
+ id: randomUUID(),
465
+ op: tool.op,
466
+ payload,
467
+ });
468
+ if (!response || typeof response !== 'object') {
469
+ return {
470
+ jsonrpc: '2.0',
471
+ id,
472
+ result: {
473
+ content: [{ type: 'text', text: 'INVALID_RESPONSE: Bridge returned an invalid response' }],
474
+ isError: true,
475
+ },
476
+ };
477
+ }
478
+ if (response.ok === false) {
479
+ const code = response.error?.code || 'BRIDGE_ERROR';
480
+ const msg = response.error?.message || 'Bridge request failed';
481
+ return {
482
+ jsonrpc: '2.0',
483
+ id,
484
+ result: {
485
+ content: [{ type: 'text', text: `${code}: ${msg}` }],
486
+ isError: true,
487
+ },
488
+ };
489
+ }
490
+ return {
491
+ jsonrpc: '2.0',
492
+ id,
493
+ result: {
494
+ content: [{ type: 'text', text: JSON.stringify(response.data ?? {}, null, 2) }],
495
+ isError: false,
496
+ },
497
+ };
498
+ } catch (error) {
499
+ const code = error?.code || 'TOOL_ERROR';
500
+ return {
501
+ jsonrpc: '2.0',
502
+ id,
503
+ result: {
504
+ content: [{ type: 'text', text: `${code}: ${error?.message || 'Tool execution failed'}` }],
505
+ isError: true,
506
+ },
507
+ };
508
+ }
509
+ }
510
+
511
+ if (id === undefined || id === null) {
512
+ return null;
513
+ }
514
+
515
+ return {
516
+ jsonrpc: '2.0',
517
+ id,
518
+ error: { code: -32601, message: `Method not found: ${method}` },
519
+ };
520
+ };
521
+ }
522
+
523
+ export function mcpUsageText() {
524
+ return [
525
+ 'notesia mcp',
526
+ '',
527
+ 'Start a local stdio Model Context Protocol (MCP) server for Notesia.',
528
+ 'Requires the Notesia desktop app to be running and signed in.',
529
+ '',
530
+ 'Example MCP client configuration (Claude Desktop / Cursor / Codex):',
531
+ ' {',
532
+ ' "mcpServers": {',
533
+ ' "notesia": {',
534
+ ' "command": "notesia",',
535
+ ' "args": ["mcp"]',
536
+ ' }',
537
+ ' }',
538
+ ' }',
539
+ '',
540
+ ].join('\n');
541
+ }
542
+
543
+ export async function runMcpServer(args = [], {
544
+ stdin = process.stdin,
545
+ stdout = process.stdout,
546
+ stderr = process.stderr,
547
+ requestBridge = defaultRequestBridge,
548
+ serverVersion = '0.2.1',
549
+ } = {}) {
550
+ if (args.includes('--help') || args.includes('-h')) {
551
+ stdout.write(mcpUsageText());
552
+ return;
553
+ }
554
+
555
+ const handleMessage = createMcpMessageHandler({ requestBridge, serverVersion });
556
+ const rl = readline.createInterface({ input: stdin, crlfDelay: Infinity });
557
+
558
+ const writeResponse = (payload) => {
559
+ if (!payload) return;
560
+ stdout.write(`${JSON.stringify(payload)}\n`);
561
+ };
562
+
563
+ return new Promise((resolve) => {
564
+ let queue = Promise.resolve();
565
+
566
+ rl.on('line', (rawLine) => {
567
+ const line = rawLine.trim();
568
+ if (!line) return;
569
+
570
+ queue = queue.then(async () => {
571
+ let parsed;
572
+ try {
573
+ parsed = JSON.parse(line);
574
+ } catch (error) {
575
+ writeResponse({
576
+ jsonrpc: '2.0',
577
+ id: null,
578
+ error: { code: -32700, message: `Parse error: ${error.message}` },
579
+ });
580
+ return;
581
+ }
582
+
583
+ try {
584
+ const response = await handleMessage(parsed);
585
+ writeResponse(response);
586
+ } catch (error) {
587
+ stderr.write(`[notesia-mcp] Unhandled error: ${error?.message || error}\n`);
588
+ if (parsed?.id !== undefined) {
589
+ writeResponse({
590
+ jsonrpc: '2.0',
591
+ id: parsed.id,
592
+ error: { code: -32603, message: error?.message || 'Internal error' },
593
+ });
594
+ }
595
+ }
596
+ });
597
+ });
598
+
599
+ rl.on('close', () => {
600
+ queue.then(resolve);
601
+ });
602
+ });
603
+ }