@clarionstack/notesia 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.0',
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.0',
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
+ }