@inkdropapp/mcp-server 1.6.0 → 1.8.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.
@@ -0,0 +1,25 @@
1
+ # This file is machine-generated by `gh actions-lock`.
2
+ # Do not edit by hand; run `gh actions-lock` to update.
3
+ # Docs: https://gh.io/actions-lockfile
4
+ version: 'v0.0.3'
5
+ workflows:
6
+ '.github/workflows/publish.yml':
7
+ - 'actions/checkout@v7.0.1'
8
+ - 'actions/setup-node@v7.1.0'
9
+ - 'pnpm/action-setup@v6.1.1'
10
+ dependencies:
11
+ 'actions/checkout@v7.0.1':
12
+ ref: 'v7.0.1'
13
+ commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
14
+ owner_id: 44036562
15
+ repo_id: 197814629
16
+ 'actions/setup-node@v7.1.0':
17
+ ref: 'v7.1.0'
18
+ commit: 'sha1-949feb2413d6458794dcd2491c4babbbce0c15c1'
19
+ owner_id: 44036562
20
+ repo_id: 189476904
21
+ 'pnpm/action-setup@v6.1.1':
22
+ ref: 'v6.1.1'
23
+ commit: 'sha1-73e46992e05b19abd31f2f3c20e0e7370d762115'
24
+ owner_id: 21320719
25
+ repo_id: 262289747
@@ -0,0 +1,57 @@
1
+ name: Publish to npm
2
+
3
+ on:
4
+ push:
5
+ tags: ['v*']
6
+
7
+ permissions:
8
+ contents: read
9
+ id-token: write # npm trusted publishing (OIDC)
10
+
11
+ concurrency:
12
+ group: publish-${{ github.ref }}
13
+ cancel-in-progress: false
14
+
15
+ jobs:
16
+ publish:
17
+ runs-on: ubuntu-latest
18
+ timeout-minutes: 20
19
+ environment: npm
20
+ steps:
21
+ - name: Checkout
22
+ uses: actions/checkout@v7.0.1
23
+
24
+ - name: Install pnpm
25
+ uses: pnpm/action-setup@v6.1.1
26
+ with:
27
+ version: 12
28
+
29
+ - name: Set up Node.js
30
+ uses: actions/setup-node@v7.1.0
31
+ with:
32
+ node-version: 24
33
+ cache: pnpm
34
+ registry-url: 'https://registry.npmjs.org'
35
+
36
+ - name: Check that the tag matches the package version
37
+ env:
38
+ TAG: ${{ github.ref_name }}
39
+ run: |
40
+ version="$(node -p "require('./package.json').version")"
41
+ if [ "$TAG" != "v$version" ]; then
42
+ echo "::error::Tag $TAG does not match the version in package.json ($version)"
43
+ exit 1
44
+ fi
45
+
46
+ - name: Install dependencies
47
+ run: pnpm install --frozen-lockfile
48
+
49
+ - name: Check formatting
50
+ run: pnpm format:check
51
+
52
+ - name: Publish
53
+ # prepublishOnly builds dist/ with tsc, so the typecheck runs here.
54
+ run: npm publish
55
+ env:
56
+ # The token setup-node configures must be empty, or npm uses it instead of OIDC.
57
+ NODE_AUTH_TOKEN: ''
package/README.md CHANGED
@@ -46,17 +46,19 @@ Read [the docs here](https://docs.inkdrop.app/reference/mcp-server).
46
46
  - Optional inputs:
47
47
  - `status`: The note status (`none`, `active`, `onHold`, `completed`, `dropped`).
48
48
  - `tags`: An array of tag IDs to assign to the note. Each must start with 'tag:'.
49
- 7. **`update-note`**: Update an existing note in the database. Only the fields you provide will be updated; omitted fields remain unchanged.
49
+ 7. **`update-note`**: Update one or more existing notes in the database. Only the fields you provide will be updated; omitted fields remain unchanged. Each note is saved independently, so a failed update does not roll back the others.
50
50
  - Required inputs:
51
- - `_id`: The note ID. Must start with 'note:'.
52
- - `_rev`: The revision ID (CouchDB MVCC-token).
53
- - Optional inputs:
54
- - `bookId`: The notebook ID. Must start with 'book:' or be 'trash' or 'template'.
55
- - `title`: The note title.
56
- - `body`: The content of the note in Markdown.
57
- - `status`: The note status (`none`, `active`, `onHold`, `completed`, `dropped`).
58
- - `tags`: An array of tag IDs to assign to the note. Each must start with 'tag:'.
59
- 8. **`patch-note`**: Update the body of an existing note by performing an exact string replacement. More efficient than `update-note` for small edits to large notes as it saves tokens. You must first read the note with `read-note` to get the current body.
51
+ - `notes`: An array of notes to update. Each item takes:
52
+ - `_id` (required): The note ID. Must start with 'note:'.
53
+ - `_rev` (required): The revision ID (CouchDB MVCC-token).
54
+ - `bookId`: The notebook ID. Must start with 'book:' or be 'trash' or 'template'.
55
+ - `title`: The note title.
56
+ - `body`: The content of the note in Markdown.
57
+ - `status`: The note status (`none`, `active`, `onHold`, `completed`, `dropped`).
58
+ - `tags`: An array of tag IDs to assign to the note. Each must start with 'tag:'.
59
+ - `createdAt`: The creation time as a Unix timestamp in milliseconds. Omit it to keep the current value.
60
+ - `updatedAt`: The last update time as a Unix timestamp in milliseconds. Defaults to the current time.
61
+ 8. **`patch-note`**: Update the body of an existing note by performing one or more exact string replacements in a single call. More efficient than `update-note` for small edits to large notes as it saves tokens. You must first read the note with `read-note` to get the current body.
60
62
  - Required inputs:
61
63
  - `_id`: The note ID. Must start with 'note:'.
62
64
  - `_rev`: The revision ID (CouchDB MVCC-token).
package/dist/index.js CHANGED
@@ -131,10 +131,10 @@ You can use special qualifiers to get more accurate results. See the qualifiers
131
131
  - **book**
132
132
  \`book:Blog\`: Searches for notes in the 'Blog' notebook.
133
133
  \`book:"Desktop App"\`: Searches for notes in the 'Desktop App' notebook.
134
- - **bookId**
135
- \`bookId:kGlLniaV\`: Searches for notes in the notebook ID 'book:kGlLniaV'.
134
+ \`book:kGlLniaV\`: Searches for notes in the notebook with the ID 'book:kGlLniaV'.
136
135
  - **tag**
137
136
  \`tag:JavaScript\`: Searches for all notes having the 'JavaScript' tag. Read more about [tags](https://docs.inkdrop.app/manual/write-notes#tag-notes).
137
+ \`tag:pQ7xYt2R\`: Searches for all notes having the tag with the ID 'tag:pQ7xYt2R'.
138
138
  - **status**
139
139
  \`status:onHold\`: Searches for all notes with the 'On hold' status. Read more about [statuses](/reference/note-statuses).
140
140
  - **title**
@@ -235,8 +235,8 @@ You have to retrieve the full note content by calling \`read-note\`.
235
235
  limit: zod_1.z.number().optional().default(100).describe(`Limit the number of results returned`)
236
236
  }
237
237
  }, async ({ bookId, tagIds, keyword, sort, descending, limit }) => {
238
- const bookFilter = bookId ? `bookId:${bookId.split(':')[1]}` : '';
239
- const tagFilter = tagIds ? tagIds.map(t => `tagId:${t}`).join(' ') : '';
238
+ const bookFilter = bookId ?? '';
239
+ const tagFilter = tagIds?.join(' ') ?? '';
240
240
  keyword = `${bookFilter} ${tagFilter} ${keyword || ''}`.trim();
241
241
  const notes = await (0, api_1.fetchJSON)('/notes', {
242
242
  keyword,
@@ -319,59 +319,93 @@ server.registerTool('create-note', {
319
319
  ]
320
320
  };
321
321
  });
322
+ /**
323
+ * Merges the given fields into the stored note and saves it.
324
+ *
325
+ * @param noteUpdate - The note ID, its current revision, and the fields to change
326
+ * @returns The response of the local server for the saved note
327
+ * @throws If the note can't be fetched at that revision or the save is rejected
328
+ */
329
+ async function updateNote(noteUpdate) {
330
+ const existingNote = await (0, api_1.fetchJSON)(`/${noteUpdate._id}`, { rev: noteUpdate._rev });
331
+ return (0, api_1.postJSON)('/notes', {
332
+ ...existingNote,
333
+ ...noteUpdate,
334
+ updatedAt: noteUpdate.updatedAt ?? +new Date()
335
+ });
336
+ }
322
337
  server.registerTool('update-note', {
323
- description: 'Update the existing note in the database. Only the fields you provide will be updated; omitted fields remain unchanged.',
338
+ description: 'Update one or more existing notes in the database. Only the fields you provide will be updated; omitted fields remain unchanged. Each note is saved independently, so a failed update does not roll back the others; the result reports the outcome of every note.',
324
339
  inputSchema: {
325
- _id: zod_1.z
326
- .string()
327
- .min(6)
328
- .max(128)
329
- .regex(/^note:/)
330
- .describe('The unique document ID which should start with `note:` and the remains are randomly generated string'),
331
- _rev: zod_1.z
332
- .string()
333
- .describe('This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'),
334
- bookId: zod_1.z
335
- .string()
336
- .min(5)
337
- .max(128)
338
- .regex(/^(book:|trash$|template$)/)
339
- .optional()
340
- .describe('The notebook ID. Specify `template` to turn the note into a custom note template'),
341
- title: zod_1.z.string().max(128).optional().describe('The note title'),
342
- body: zod_1.z
343
- .string()
344
- .max(1048576)
345
- .optional()
346
- .describe('The content of the note in Markdown. NOTE: Do not escape special characters like `\\n`.'),
347
- status: zod_1.z
348
- .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
349
- .optional()
350
- .describe('The status of the note'),
351
- tags: zod_1.z
352
- .array(zod_1.z.string().startsWith('tag:'))
353
- .optional()
354
- .describe('An array of tag IDs to assign to the note. Call `list-tags` or `read-tag` to retrieve available tags. You can create a new tag with `create-tag` tool if necessary.')
340
+ notes: zod_1.z
341
+ .array(zod_1.z.object({
342
+ _id: zod_1.z
343
+ .string()
344
+ .min(6)
345
+ .max(128)
346
+ .regex(/^note:/)
347
+ .describe('The unique document ID which should start with `note:` and the remains are randomly generated string'),
348
+ _rev: zod_1.z
349
+ .string()
350
+ .describe('This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'),
351
+ bookId: zod_1.z
352
+ .string()
353
+ .min(5)
354
+ .max(128)
355
+ .regex(/^(book:|trash$|template$)/)
356
+ .optional()
357
+ .describe('The notebook ID. Specify `template` to turn the note into a custom note template'),
358
+ title: zod_1.z.string().max(128).optional().describe('The note title'),
359
+ body: zod_1.z
360
+ .string()
361
+ .max(1048576)
362
+ .optional()
363
+ .describe('The content of the note in Markdown. NOTE: Do not escape special characters like `\\n`.'),
364
+ status: zod_1.z
365
+ .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
366
+ .optional()
367
+ .describe('The status of the note'),
368
+ tags: zod_1.z
369
+ .array(zod_1.z.string().startsWith('tag:'))
370
+ .optional()
371
+ .describe('An array of tag IDs to assign to the note. Call `list-tags` or `read-tag` to retrieve available tags. You can create a new tag with `create-tag` tool if necessary.'),
372
+ createdAt: zod_1.z
373
+ .number()
374
+ .int()
375
+ .nonnegative()
376
+ .optional()
377
+ .describe('The date time when the note was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.'),
378
+ updatedAt: zod_1.z
379
+ .number()
380
+ .int()
381
+ .nonnegative()
382
+ .optional()
383
+ .describe('The date time when the note was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.')
384
+ }))
385
+ .min(1)
386
+ .describe('The notes to update.')
355
387
  }
356
- }, async (noteData) => {
357
- const rev = noteData._rev;
358
- const existingNote = await (0, api_1.fetchJSON)(`/${noteData._id}`, { rev });
359
- const res = await (0, api_1.postJSON)(`/notes`, {
360
- ...existingNote,
361
- ...noteData,
362
- updatedAt: +new Date()
363
- });
388
+ }, async ({ notes }) => {
389
+ const settledUpdates = await Promise.allSettled(notes.map(updateNote));
390
+ const results = settledUpdates.map((settledUpdate, noteIndex) => settledUpdate.status === 'fulfilled'
391
+ ? settledUpdate.value
392
+ : {
393
+ ok: false,
394
+ id: notes[noteIndex]._id,
395
+ error: settledUpdate.reason.message
396
+ });
364
397
  return {
365
398
  content: [
366
399
  {
367
400
  type: 'text',
368
- text: JSON.stringify(res, null, 2)
401
+ text: JSON.stringify(results, null, 2)
369
402
  }
370
- ]
403
+ ],
404
+ isError: settledUpdates.some(settledUpdate => settledUpdate.status === 'rejected')
371
405
  };
372
406
  });
373
407
  server.registerTool('patch-note', {
374
- description: 'Update the body of the existing note by performing an exact string replacement. Use this tool to make partial updates to the note body without replacing the entire content. You must first read the note with `read-note` to get the current body, then specify the exact substring to replace.',
408
+ description: 'Update the body of the existing note by performing one or more exact string replacements. Use this tool to make partial updates to the note body without replacing the entire content. You must first read the note with `read-note` to get the current body, then specify the exact substrings to replace. Edits are applied in order, each against the result of the previous one, and the note is only saved if all of them succeed.',
375
409
  inputSchema: {
376
410
  _id: zod_1.z
377
411
  .string()
@@ -382,46 +416,50 @@ server.registerTool('patch-note', {
382
416
  _rev: zod_1.z
383
417
  .string()
384
418
  .describe('This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'),
385
- old_string: zod_1.z
386
- .string()
419
+ edits: zod_1.z
420
+ .array(zod_1.z.object({
421
+ old_string: zod_1.z
422
+ .string()
423
+ .min(1)
424
+ .describe('The exact text to find in the note body. Must match exactly one occurrence. Include enough surrounding context to ensure a unique match.'),
425
+ new_string: zod_1.z
426
+ .string()
427
+ .describe('The text to replace `old_string` with. Use an empty string to delete the matched text.')
428
+ }))
387
429
  .min(1)
388
- .describe('The exact text to find in the note body. Must match exactly one occurrence. Include enough surrounding context to ensure a unique match.'),
389
- new_string: zod_1.z
390
- .string()
391
- .describe('The text to replace `old_string` with. Use an empty string to delete the matched text.')
430
+ .describe('The replacements to perform, applied in order.'),
431
+ createdAt: zod_1.z
432
+ .number()
433
+ .int()
434
+ .nonnegative()
435
+ .optional()
436
+ .describe('The date time when the note was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.'),
437
+ updatedAt: zod_1.z
438
+ .number()
439
+ .int()
440
+ .nonnegative()
441
+ .optional()
442
+ .describe('The date time when the note was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.')
392
443
  }
393
- }, async ({ _id, _rev, old_string, new_string }) => {
444
+ }, async ({ _id, _rev, edits, createdAt, updatedAt }) => {
394
445
  const existingNote = await (0, api_1.fetchJSON)(`/${_id}`, { rev: _rev });
395
- const body = existingNote.body;
396
- const firstIndex = body.indexOf(old_string);
397
- if (firstIndex === -1) {
398
- return {
399
- content: [
400
- {
401
- type: 'text',
402
- text: 'Failed to patch: `old_string` was not found in the note body.'
403
- }
404
- ],
405
- isError: true
406
- };
407
- }
408
- const secondIndex = body.indexOf(old_string, firstIndex + 1);
409
- if (secondIndex !== -1) {
446
+ const patchResult = (0, utils_1.applyTextEdits)(existingNote.body, edits);
447
+ if (!patchResult.ok) {
410
448
  return {
411
449
  content: [
412
450
  {
413
451
  type: 'text',
414
- text: 'Failed to patch: `old_string` matches multiple locations in the note body. Provide more surrounding context to make it unique.'
452
+ text: `Failed to patch: ${patchResult.error} No edits were saved.`
415
453
  }
416
454
  ],
417
455
  isError: true
418
456
  };
419
457
  }
420
- const patched = body.slice(0, firstIndex) + new_string + body.slice(firstIndex + old_string.length);
421
458
  const res = await (0, api_1.postJSON)('/notes', {
422
459
  ...existingNote,
423
- body: patched,
424
- updatedAt: +new Date()
460
+ body: patchResult.text,
461
+ createdAt: createdAt ?? existingNote.createdAt,
462
+ updatedAt: updatedAt ?? +new Date()
425
463
  });
426
464
  return {
427
465
  content: [
@@ -583,12 +621,24 @@ server.registerTool('update-book', {
583
621
  .regex(/^book:/)
584
622
  .nullable()
585
623
  .optional()
586
- .describe('The ID of the parent notebook. Pass `null` to move the notebook to the root level.')
624
+ .describe('The ID of the parent notebook. Pass `null` to move the notebook to the root level.'),
625
+ createdAt: zod_1.z
626
+ .number()
627
+ .int()
628
+ .nonnegative()
629
+ .optional()
630
+ .describe('The date time when the notebook was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.'),
631
+ updatedAt: zod_1.z
632
+ .number()
633
+ .int()
634
+ .nonnegative()
635
+ .optional()
636
+ .describe('The date time when the notebook was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.')
587
637
  }
588
638
  }, async ({ _id, ...updateFields }) => {
589
639
  const res = await (0, api_1.postJSON)(`/${_id}`, {
590
640
  ...updateFields,
591
- updatedAt: +new Date()
641
+ updatedAt: updateFields.updatedAt ?? +new Date()
592
642
  });
593
643
  return {
594
644
  content: [
package/dist/utils.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getNoteUri = getNoteUri;
4
4
  exports.getFileUri = getFileUri;
5
5
  exports.inferImageContentType = inferImageContentType;
6
+ exports.applyTextEdits = applyTextEdits;
6
7
  exports.isViewableImageType = isViewableImageType;
7
8
  const node_path_1 = require("node:path");
8
9
  const inkdrop_model_1 = require("inkdrop-model");
@@ -45,6 +46,42 @@ function inferImageContentType(filePath) {
45
46
  const ext = (0, node_path_1.extname)(filePath).toLowerCase().replace(/^\./, '');
46
47
  return inkdrop_model_1.SUPPORTED_IMAGE_MIME_TYPES[ext === 'svg' ? 'svg+xml' : ext];
47
48
  }
49
+ /**
50
+ * Applies exact string replacements in order, each against the result of the
51
+ * previous one, so a later edit can match text an earlier edit produced.
52
+ *
53
+ * Every `old_string` must match exactly one location at the time it is applied.
54
+ * Processing stops at the first edit that does not, so callers never see a
55
+ * partially patched text.
56
+ *
57
+ * @param text - The text to patch
58
+ * @param edits - The replacements to perform
59
+ * @returns The patched text, or an error naming the 1-based position of the failing edit
60
+ */
61
+ function applyTextEdits(text, edits) {
62
+ let patchedText = text;
63
+ for (const [editIndex, { old_string, new_string }] of edits.entries()) {
64
+ const editLabel = `edit ${editIndex + 1} of ${edits.length}`;
65
+ const firstMatchIndex = patchedText.indexOf(old_string);
66
+ if (firstMatchIndex === -1) {
67
+ return {
68
+ ok: false,
69
+ error: `\`old_string\` of ${editLabel} was not found in the note body.`
70
+ };
71
+ }
72
+ if (patchedText.indexOf(old_string, firstMatchIndex + 1) !== -1) {
73
+ return {
74
+ ok: false,
75
+ error: `\`old_string\` of ${editLabel} matches multiple locations in the note body. Provide more surrounding context to make it unique.`
76
+ };
77
+ }
78
+ patchedText =
79
+ patchedText.slice(0, firstMatchIndex) +
80
+ new_string +
81
+ patchedText.slice(firstMatchIndex + old_string.length);
82
+ }
83
+ return { ok: true, text: patchedText };
84
+ }
48
85
  /**
49
86
  * Content types the MCP `image` content block can carry. Inkdrop also accepts
50
87
  * SVG and HEIC/HEIF attachments, which have to be written to disk instead.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkdropapp/mcp-server",
3
- "version": "1.6.0",
3
+ "version": "1.8.0",
4
4
  "description": "Inkdrop Model Context Protocol Server",
5
5
  "bin": {
6
6
  "inkdrop-mcp-server": "dist/index.js"
@@ -26,14 +26,14 @@
26
26
  "author": "Takuya Matsuyama<contact@inkdrop.app>",
27
27
  "license": "Apache-2.0",
28
28
  "dependencies": {
29
- "@modelcontextprotocol/sdk": "^1.32.1",
29
+ "@modelcontextprotocol/sdk": "^1.32.2",
30
30
  "ajv": "^8.20.0",
31
31
  "inkdrop-model": "^3.0.1",
32
32
  "zod": "^4.6.7"
33
33
  },
34
34
  "devDependencies": {
35
- "@types/node": "^26.6.5",
36
- "oxfmt": "^0.73.0",
35
+ "@types/node": "^26.6.6",
36
+ "oxfmt": "^0.76.0",
37
37
  "typescript": "^7.0.2"
38
38
  }
39
39
  }
package/src/index.ts CHANGED
@@ -18,7 +18,13 @@ import {
18
18
  import { z } from 'zod'
19
19
 
20
20
  import { fetchJSON, postJSON } from './api'
21
- import { getFileUri, getNoteUri, inferImageContentType, isViewableImageType } from './utils'
21
+ import {
22
+ applyTextEdits,
23
+ getFileUri,
24
+ getNoteUri,
25
+ inferImageContentType,
26
+ isViewableImageType
27
+ } from './utils'
22
28
 
23
29
  const server = new McpServer({
24
30
  name: 'Inkdrop',
@@ -167,10 +173,10 @@ You can use special qualifiers to get more accurate results. See the qualifiers
167
173
  - **book**
168
174
  \`book:Blog\`: Searches for notes in the 'Blog' notebook.
169
175
  \`book:"Desktop App"\`: Searches for notes in the 'Desktop App' notebook.
170
- - **bookId**
171
- \`bookId:kGlLniaV\`: Searches for notes in the notebook ID 'book:kGlLniaV'.
176
+ \`book:kGlLniaV\`: Searches for notes in the notebook with the ID 'book:kGlLniaV'.
172
177
  - **tag**
173
178
  \`tag:JavaScript\`: Searches for all notes having the 'JavaScript' tag. Read more about [tags](https://docs.inkdrop.app/manual/write-notes#tag-notes).
179
+ \`tag:pQ7xYt2R\`: Searches for all notes having the tag with the ID 'tag:pQ7xYt2R'.
174
180
  - **status**
175
181
  \`status:onHold\`: Searches for all notes with the 'On hold' status. Read more about [statuses](/reference/note-statuses).
176
182
  - **title**
@@ -281,8 +287,8 @@ You have to retrieve the full note content by calling \`read-note\`.
281
287
  }
282
288
  },
283
289
  async ({ bookId, tagIds, keyword, sort, descending, limit }) => {
284
- const bookFilter = bookId ? `bookId:${bookId.split(':')[1]}` : ''
285
- const tagFilter = tagIds ? tagIds.map(t => `tagId:${t}`).join(' ') : ''
290
+ const bookFilter = bookId ?? ''
291
+ const tagFilter = tagIds?.join(' ') ?? ''
286
292
  keyword = `${bookFilter} ${tagFilter} ${keyword || ''}`.trim()
287
293
  const notes: Note[] = await fetchJSON('/notes', {
288
294
  keyword,
@@ -385,76 +391,123 @@ server.registerTool(
385
391
  }
386
392
  )
387
393
 
394
+ type NoteUpdate = Partial<Note> & Pick<Note, '_id' | '_rev'>
395
+
396
+ /**
397
+ * Merges the given fields into the stored note and saves it.
398
+ *
399
+ * @param noteUpdate - The note ID, its current revision, and the fields to change
400
+ * @returns The response of the local server for the saved note
401
+ * @throws If the note can't be fetched at that revision or the save is rejected
402
+ */
403
+ async function updateNote(noteUpdate: NoteUpdate) {
404
+ const existingNote = await fetchJSON<Note>(`/${noteUpdate._id}`, { rev: noteUpdate._rev })
405
+
406
+ return postJSON<{ ok: boolean; id: string; rev: string }>('/notes', {
407
+ ...existingNote,
408
+ ...noteUpdate,
409
+ updatedAt: noteUpdate.updatedAt ?? +new Date()
410
+ })
411
+ }
412
+
388
413
  server.registerTool(
389
414
  'update-note',
390
415
  {
391
416
  description:
392
- 'Update the existing note in the database. Only the fields you provide will be updated; omitted fields remain unchanged.',
417
+ 'Update one or more existing notes in the database. Only the fields you provide will be updated; omitted fields remain unchanged. Each note is saved independently, so a failed update does not roll back the others; the result reports the outcome of every note.',
393
418
  inputSchema: {
394
- _id: z
395
- .string()
396
- .min(6)
397
- .max(128)
398
- .regex(/^note:/)
399
- .describe(
400
- 'The unique document ID which should start with `note:` and the remains are randomly generated string'
401
- ),
402
-
403
- _rev: z
404
- .string()
405
- .describe(
406
- 'This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'
407
- ),
408
-
409
- bookId: z
410
- .string()
411
- .min(5)
412
- .max(128)
413
- .regex(/^(book:|trash$|template$)/)
414
- .optional()
415
- .describe(
416
- 'The notebook ID. Specify `template` to turn the note into a custom note template'
417
- ),
418
-
419
- title: z.string().max(128).optional().describe('The note title'),
420
-
421
- body: z
422
- .string()
423
- .max(1048576)
424
- .optional()
425
- .describe(
426
- 'The content of the note in Markdown. NOTE: Do not escape special characters like `\\n`.'
427
- ),
428
-
429
- status: z
430
- .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
431
- .optional()
432
- .describe('The status of the note'),
433
-
434
- tags: z
435
- .array(z.string().startsWith('tag:'))
436
- .optional()
437
- .describe(
438
- 'An array of tag IDs to assign to the note. Call `list-tags` or `read-tag` to retrieve available tags. You can create a new tag with `create-tag` tool if necessary.'
419
+ notes: z
420
+ .array(
421
+ z.object({
422
+ _id: z
423
+ .string()
424
+ .min(6)
425
+ .max(128)
426
+ .regex(/^note:/)
427
+ .describe(
428
+ 'The unique document ID which should start with `note:` and the remains are randomly generated string'
429
+ ),
430
+
431
+ _rev: z
432
+ .string()
433
+ .describe(
434
+ 'This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'
435
+ ),
436
+
437
+ bookId: z
438
+ .string()
439
+ .min(5)
440
+ .max(128)
441
+ .regex(/^(book:|trash$|template$)/)
442
+ .optional()
443
+ .describe(
444
+ 'The notebook ID. Specify `template` to turn the note into a custom note template'
445
+ ),
446
+
447
+ title: z.string().max(128).optional().describe('The note title'),
448
+
449
+ body: z
450
+ .string()
451
+ .max(1048576)
452
+ .optional()
453
+ .describe(
454
+ 'The content of the note in Markdown. NOTE: Do not escape special characters like `\\n`.'
455
+ ),
456
+
457
+ status: z
458
+ .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
459
+ .optional()
460
+ .describe('The status of the note'),
461
+
462
+ tags: z
463
+ .array(z.string().startsWith('tag:'))
464
+ .optional()
465
+ .describe(
466
+ 'An array of tag IDs to assign to the note. Call `list-tags` or `read-tag` to retrieve available tags. You can create a new tag with `create-tag` tool if necessary.'
467
+ ),
468
+
469
+ createdAt: z
470
+ .number()
471
+ .int()
472
+ .nonnegative()
473
+ .optional()
474
+ .describe(
475
+ 'The date time when the note was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.'
476
+ ),
477
+
478
+ updatedAt: z
479
+ .number()
480
+ .int()
481
+ .nonnegative()
482
+ .optional()
483
+ .describe(
484
+ 'The date time when the note was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.'
485
+ )
486
+ })
439
487
  )
488
+ .min(1)
489
+ .describe('The notes to update.')
440
490
  }
441
491
  },
442
- async noteData => {
443
- const rev = noteData._rev
444
- const existingNote = await fetchJSON<Note>(`/${noteData._id}`, { rev })
445
-
446
- const res = await postJSON(`/notes`, {
447
- ...existingNote,
448
- ...noteData,
449
- updatedAt: +new Date()
450
- })
492
+ async ({ notes }) => {
493
+ const settledUpdates = await Promise.allSettled(notes.map(updateNote))
494
+ const results = settledUpdates.map((settledUpdate, noteIndex) =>
495
+ settledUpdate.status === 'fulfilled'
496
+ ? settledUpdate.value
497
+ : {
498
+ ok: false,
499
+ id: notes[noteIndex]._id,
500
+ error: (settledUpdate.reason as Error).message
501
+ }
502
+ )
451
503
  return {
452
504
  content: [
453
505
  {
454
506
  type: 'text',
455
- text: JSON.stringify(res, null, 2)
507
+ text: JSON.stringify(results, null, 2)
456
508
  }
457
- ]
509
+ ],
510
+ isError: settledUpdates.some(settledUpdate => settledUpdate.status === 'rejected')
458
511
  }
459
512
  }
460
513
  )
@@ -463,7 +516,7 @@ server.registerTool(
463
516
  'patch-note',
464
517
  {
465
518
  description:
466
- 'Update the body of the existing note by performing an exact string replacement. Use this tool to make partial updates to the note body without replacing the entire content. You must first read the note with `read-note` to get the current body, then specify the exact substring to replace.',
519
+ 'Update the body of the existing note by performing one or more exact string replacements. Use this tool to make partial updates to the note body without replacing the entire content. You must first read the note with `read-note` to get the current body, then specify the exact substrings to replace. Edits are applied in order, each against the result of the previous one, and the note is only saved if all of them succeed.',
467
520
  inputSchema: {
468
521
  _id: z
469
522
  .string()
@@ -480,57 +533,66 @@ server.registerTool(
480
533
  'This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'
481
534
  ),
482
535
 
483
- old_string: z
484
- .string()
536
+ edits: z
537
+ .array(
538
+ z.object({
539
+ old_string: z
540
+ .string()
541
+ .min(1)
542
+ .describe(
543
+ 'The exact text to find in the note body. Must match exactly one occurrence. Include enough surrounding context to ensure a unique match.'
544
+ ),
545
+
546
+ new_string: z
547
+ .string()
548
+ .describe(
549
+ 'The text to replace `old_string` with. Use an empty string to delete the matched text.'
550
+ )
551
+ })
552
+ )
485
553
  .min(1)
554
+ .describe('The replacements to perform, applied in order.'),
555
+
556
+ createdAt: z
557
+ .number()
558
+ .int()
559
+ .nonnegative()
560
+ .optional()
486
561
  .describe(
487
- 'The exact text to find in the note body. Must match exactly one occurrence. Include enough surrounding context to ensure a unique match.'
562
+ 'The date time when the note was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.'
488
563
  ),
489
564
 
490
- new_string: z
491
- .string()
565
+ updatedAt: z
566
+ .number()
567
+ .int()
568
+ .nonnegative()
569
+ .optional()
492
570
  .describe(
493
- 'The text to replace `old_string` with. Use an empty string to delete the matched text.'
571
+ 'The date time when the note was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.'
494
572
  )
495
573
  }
496
574
  },
497
- async ({ _id, _rev, old_string, new_string }) => {
575
+ async ({ _id, _rev, edits, createdAt, updatedAt }) => {
498
576
  const existingNote = await fetchJSON<Note>(`/${_id}`, { rev: _rev })
499
- const body = existingNote.body
500
-
501
- const firstIndex = body.indexOf(old_string)
502
- if (firstIndex === -1) {
503
- return {
504
- content: [
505
- {
506
- type: 'text',
507
- text: 'Failed to patch: `old_string` was not found in the note body.'
508
- }
509
- ],
510
- isError: true
511
- }
512
- }
513
577
 
514
- const secondIndex = body.indexOf(old_string, firstIndex + 1)
515
- if (secondIndex !== -1) {
578
+ const patchResult = applyTextEdits(existingNote.body, edits)
579
+ if (!patchResult.ok) {
516
580
  return {
517
581
  content: [
518
582
  {
519
583
  type: 'text',
520
- text: 'Failed to patch: `old_string` matches multiple locations in the note body. Provide more surrounding context to make it unique.'
584
+ text: `Failed to patch: ${patchResult.error} No edits were saved.`
521
585
  }
522
586
  ],
523
587
  isError: true
524
588
  }
525
589
  }
526
590
 
527
- const patched =
528
- body.slice(0, firstIndex) + new_string + body.slice(firstIndex + old_string.length)
529
-
530
591
  const res = await postJSON('/notes', {
531
592
  ...existingNote,
532
- body: patched,
533
- updatedAt: +new Date()
593
+ body: patchResult.text,
594
+ createdAt: createdAt ?? existingNote.createdAt,
595
+ updatedAt: updatedAt ?? +new Date()
534
596
  })
535
597
  return {
536
598
  content: [
@@ -746,13 +808,29 @@ server.registerTool(
746
808
  .optional()
747
809
  .describe(
748
810
  'The ID of the parent notebook. Pass `null` to move the notebook to the root level.'
811
+ ),
812
+ createdAt: z
813
+ .number()
814
+ .int()
815
+ .nonnegative()
816
+ .optional()
817
+ .describe(
818
+ 'The date time when the notebook was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.'
819
+ ),
820
+ updatedAt: z
821
+ .number()
822
+ .int()
823
+ .nonnegative()
824
+ .optional()
825
+ .describe(
826
+ 'The date time when the notebook was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.'
749
827
  )
750
828
  }
751
829
  },
752
830
  async ({ _id, ...updateFields }) => {
753
831
  const res = await postJSON(`/${_id}`, {
754
832
  ...updateFields,
755
- updatedAt: +new Date()
833
+ updatedAt: updateFields.updatedAt ?? +new Date()
756
834
  })
757
835
  return {
758
836
  content: [
package/src/utils.ts CHANGED
@@ -44,6 +44,55 @@ export function inferImageContentType(filePath: string): ImageFileType | undefin
44
44
  return SUPPORTED_IMAGE_MIME_TYPES[ext === 'svg' ? 'svg+xml' : ext]
45
45
  }
46
46
 
47
+ export type TextEdit = {
48
+ old_string: string
49
+ new_string: string
50
+ }
51
+
52
+ export type ApplyTextEditsResult = { ok: true; text: string } | { ok: false; error: string }
53
+
54
+ /**
55
+ * Applies exact string replacements in order, each against the result of the
56
+ * previous one, so a later edit can match text an earlier edit produced.
57
+ *
58
+ * Every `old_string` must match exactly one location at the time it is applied.
59
+ * Processing stops at the first edit that does not, so callers never see a
60
+ * partially patched text.
61
+ *
62
+ * @param text - The text to patch
63
+ * @param edits - The replacements to perform
64
+ * @returns The patched text, or an error naming the 1-based position of the failing edit
65
+ */
66
+ export function applyTextEdits(text: string, edits: TextEdit[]): ApplyTextEditsResult {
67
+ let patchedText = text
68
+
69
+ for (const [editIndex, { old_string, new_string }] of edits.entries()) {
70
+ const editLabel = `edit ${editIndex + 1} of ${edits.length}`
71
+
72
+ const firstMatchIndex = patchedText.indexOf(old_string)
73
+ if (firstMatchIndex === -1) {
74
+ return {
75
+ ok: false,
76
+ error: `\`old_string\` of ${editLabel} was not found in the note body.`
77
+ }
78
+ }
79
+
80
+ if (patchedText.indexOf(old_string, firstMatchIndex + 1) !== -1) {
81
+ return {
82
+ ok: false,
83
+ error: `\`old_string\` of ${editLabel} matches multiple locations in the note body. Provide more surrounding context to make it unique.`
84
+ }
85
+ }
86
+
87
+ patchedText =
88
+ patchedText.slice(0, firstMatchIndex) +
89
+ new_string +
90
+ patchedText.slice(firstMatchIndex + old_string.length)
91
+ }
92
+
93
+ return { ok: true, text: patchedText }
94
+ }
95
+
47
96
  /**
48
97
  * Content types the MCP `image` content block can carry. Inkdrop also accepts
49
98
  * SVG and HEIC/HEIF attachments, which have to be written to disk instead.
@@ -1,5 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": ["Bash(claude mcp list:*)"]
4
- }
5
- }
package/Session.vim DELETED
@@ -1,122 +0,0 @@
1
- let SessionLoad = 1
2
- let s:so_save = &g:so | let s:siso_save = &g:siso | setg so=0 siso=0 | setl so=-1 siso=-1
3
- let v:this_session=expand("<sfile>:p")
4
- doautoall SessionLoadPre
5
- silent only
6
- silent tabonly
7
- cd ~/Developments/inkdrop/mcp-server
8
- if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''
9
- let s:wipebuf = bufnr('%')
10
- endif
11
- let s:shortmess_save = &shortmess
12
- set shortmess+=aoO
13
- badd +34 package.json
14
- badd +79 src/index.ts
15
- badd +258 node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/mcp.d.ts
16
- badd +6 src/utils.ts
17
- argglobal
18
- %argdel
19
- $argadd package.json
20
- edit src/index.ts
21
- let s:save_splitbelow = &splitbelow
22
- let s:save_splitright = &splitright
23
- set splitbelow splitright
24
- wincmd _ | wincmd |
25
- vsplit
26
- wincmd _ | wincmd |
27
- vsplit
28
- 2wincmd h
29
- wincmd w
30
- wincmd w
31
- let &splitbelow = s:save_splitbelow
32
- let &splitright = s:save_splitright
33
- wincmd t
34
- let s:save_winminheight = &winminheight
35
- let s:save_winminwidth = &winminwidth
36
- set winminheight=0
37
- set winheight=1
38
- set winminwidth=0
39
- set winwidth=1
40
- exe 'vert 1resize ' . ((&columns * 153 + 230) / 460)
41
- exe 'vert 2resize ' . ((&columns * 153 + 230) / 460)
42
- exe 'vert 3resize ' . ((&columns * 152 + 230) / 460)
43
- argglobal
44
- balt package.json
45
- setlocal foldmethod=expr
46
- setlocal foldexpr=nvim_treesitter#foldexpr()
47
- setlocal foldmarker={{{,}}}
48
- setlocal foldignore=#
49
- setlocal foldlevel=99
50
- setlocal foldminlines=1
51
- setlocal foldnestmax=20
52
- setlocal foldenable
53
- let s:l = 79 - ((41 * winheight(0) + 40) / 81)
54
- if s:l < 1 | let s:l = 1 | endif
55
- keepjumps exe s:l
56
- normal! zt
57
- keepjumps 79
58
- normal! 031|
59
- wincmd w
60
- argglobal
61
- if bufexists(fnamemodify("src/index.ts", ":p")) | buffer src/index.ts | else | edit src/index.ts | endif
62
- if &buftype ==# 'terminal'
63
- silent file src/index.ts
64
- endif
65
- balt package.json
66
- setlocal foldmethod=expr
67
- setlocal foldexpr=nvim_treesitter#foldexpr()
68
- setlocal foldmarker={{{,}}}
69
- setlocal foldignore=#
70
- setlocal foldlevel=99
71
- setlocal foldminlines=1
72
- setlocal foldnestmax=20
73
- setlocal foldenable
74
- let s:l = 389 - ((37 * winheight(0) + 40) / 81)
75
- if s:l < 1 | let s:l = 1 | endif
76
- keepjumps exe s:l
77
- normal! zt
78
- keepjumps 389
79
- normal! 010|
80
- wincmd w
81
- argglobal
82
- if bufexists(fnamemodify("package.json", ":p")) | buffer package.json | else | edit package.json | endif
83
- if &buftype ==# 'terminal'
84
- silent file package.json
85
- endif
86
- balt src/index.ts
87
- setlocal foldmethod=expr
88
- setlocal foldexpr=nvim_treesitter#foldexpr()
89
- setlocal foldmarker={{{,}}}
90
- setlocal foldignore=#
91
- setlocal foldlevel=99
92
- setlocal foldminlines=1
93
- setlocal foldnestmax=20
94
- setlocal foldenable
95
- let s:l = 34 - ((33 * winheight(0) + 40) / 81)
96
- if s:l < 1 | let s:l = 1 | endif
97
- keepjumps exe s:l
98
- normal! zt
99
- keepjumps 34
100
- normal! 025|
101
- wincmd w
102
- exe 'vert 1resize ' . ((&columns * 153 + 230) / 460)
103
- exe 'vert 2resize ' . ((&columns * 153 + 230) / 460)
104
- exe 'vert 3resize ' . ((&columns * 152 + 230) / 460)
105
- tabnext 1
106
- if exists('s:wipebuf') && len(win_findbuf(s:wipebuf)) == 0 && getbufvar(s:wipebuf, '&buftype') isnot# 'terminal'
107
- silent exe 'bwipe ' . s:wipebuf
108
- endif
109
- unlet! s:wipebuf
110
- set winheight=1 winwidth=20
111
- let &shortmess = s:shortmess_save
112
- let &winminheight = s:save_winminheight
113
- let &winminwidth = s:save_winminwidth
114
- let s:sx = expand("<sfile>:p:r")."x.vim"
115
- if filereadable(s:sx)
116
- exe "source " . fnameescape(s:sx)
117
- endif
118
- let &g:so = s:so_save | let &g:siso = s:siso_save
119
- set hlsearch
120
- doautoall SessionLoadPost
121
- unlet SessionLoad
122
- " vim: set ft=vim :
package/dist/bak.js DELETED
@@ -1,331 +0,0 @@
1
- "use strict";
2
- /**
3
- * Example: MCP Proxy for Inkdrop's local HTTP server.
4
- *
5
- * Requirements:
6
- * 1) Inkdrop's local server is running at config.baseUrl (e.g. http://localhost:19840).
7
- * 2) A Basic auth username/password is set in Inkdrop.
8
- * 3) This script can be run with `npx ts-node inkdrop-mcp-proxy.ts`.
9
- * 4) Then, an MCP client (e.g. MCP Inspector, or Claude) can connect to:
10
- * GET http://localhost:3002/sse (SSE endpoint)
11
- * POST http://localhost:3002/messages (MCP messages endpoint)
12
- */
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- const url_1 = require("url");
15
- const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
16
- const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
17
- const zod_1 = require("zod");
18
- /** Configuration for talking to Inkdrop’s local HTTP server */
19
- const config = {
20
- baseUrl: "http://localhost:19841", // or https://localhost:19840
21
- username: "foo@bar.com",
22
- password: "bar",
23
- /** If Inkdrop uses self-signed cert over HTTPS, you may need to allow that. */
24
- };
25
- /** Build the 'Authorization: Basic ...' header */
26
- function getAuthHeaders() {
27
- const token = Buffer.from(`${config.username}:${config.password}`).toString("base64");
28
- return {
29
- Authorization: `Basic ${token}`
30
- };
31
- }
32
- /** Helper to attach query parameters to a given path */
33
- function buildUrl(path, qs = {}) {
34
- const url = new url_1.URL(path, config.baseUrl);
35
- for (const [k, v] of Object.entries(qs)) {
36
- if (v !== undefined && v !== null)
37
- url.searchParams.set(k, String(v));
38
- }
39
- return url.toString();
40
- }
41
- /** Helper to do a GET request and return JSON or throw an error. */
42
- async function fetchJSON(path, qs = {}) {
43
- const url = buildUrl(path, qs);
44
- const resp = await fetch(url, { headers: getAuthHeaders() });
45
- if (!resp.ok) {
46
- throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
47
- }
48
- return await resp.json();
49
- }
50
- /** Helper to do a POST request with JSON body */
51
- async function postJSON(path, body) {
52
- const url = buildUrl(path);
53
- const resp = await fetch(url, {
54
- method: "POST",
55
- headers: {
56
- ...getAuthHeaders(),
57
- "Content-Type": "application/json"
58
- },
59
- body: JSON.stringify(body)
60
- });
61
- if (!resp.ok) {
62
- throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
63
- }
64
- return await resp.json();
65
- }
66
- /** Helper to do a DELETE request */
67
- async function deleteJSON(path) {
68
- const url = buildUrl(path);
69
- const resp = await fetch(url, {
70
- method: "DELETE",
71
- headers: getAuthHeaders()
72
- });
73
- if (!resp.ok) {
74
- throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
75
- }
76
- return await resp.json();
77
- }
78
- /** Create the MCP Server that proxies to Inkdrop’s local API. */
79
- function createInkdropProxyServer() {
80
- const server = new mcp_js_1.McpServer({
81
- name: "Inkdrop MCP Proxy",
82
- version: "1.0.0"
83
- });
84
- //
85
- // 1) Root meta info (like GET "/")
86
- //
87
- server.resource("root", "inkdrop://root", async (uri) => {
88
- const body = await fetchJSON("/");
89
- return {
90
- contents: [
91
- {
92
- uri: uri.href,
93
- text: JSON.stringify(body, null, 2)
94
- }
95
- ]
96
- };
97
- });
98
- //
99
- // 2) Notes
100
- //
101
- // 2a) List all notes (proxy GET /notes, with query params)
102
- server.resource("notes", new mcp_js_1.ResourceTemplate("inkdrop://notes{?keyword,limit,skip,sort,descending}", {
103
- list: undefined
104
- }), async (uri) => {
105
- // forward query to /notes
106
- const qs = Object.fromEntries(uri.searchParams.entries());
107
- const body = await fetchJSON("/notes", qs);
108
- return {
109
- contents: [
110
- {
111
- uri: uri.href,
112
- text: JSON.stringify(body, null, 2)
113
- }
114
- ]
115
- };
116
- });
117
- // 2b) Create/update note (proxy POST /notes)
118
- server.tool("save-note", {
119
- _id: zod_1.z.string().optional(),
120
- _rev: zod_1.z.string().optional(),
121
- doctype: zod_1.z.string().optional(),
122
- bookId: zod_1.z.string().optional(),
123
- status: zod_1.z.string().optional(),
124
- share: zod_1.z.string().optional(),
125
- title: zod_1.z.string().optional(),
126
- body: zod_1.z.string().optional(),
127
- pinned: zod_1.z.boolean().optional(),
128
- tags: zod_1.z.array(zod_1.z.string()).optional()
129
- }, async (args) => {
130
- const ret = await postJSON("/notes", args);
131
- return {
132
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
133
- };
134
- });
135
- // 2c) Get single note (proxy GET /note:docId)
136
- server.resource("single-note", new mcp_js_1.ResourceTemplate("inkdrop://note/{docId}{?rev,attachments}", { list: undefined }), async (uri, { docId }) => {
137
- const qs = Object.fromEntries(uri.searchParams.entries());
138
- const body = await fetchJSON(`/note:${docId}`, qs);
139
- return {
140
- contents: [
141
- {
142
- uri: uri.href,
143
- text: JSON.stringify(body, null, 2)
144
- }
145
- ]
146
- };
147
- });
148
- // 2d) Delete note (proxy DELETE /note:docId)
149
- server.tool("delete-note", { docId: zod_1.z.string() }, async ({ docId }) => {
150
- const ret = await deleteJSON(`/note:${docId}`);
151
- return {
152
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
153
- };
154
- });
155
- //
156
- // 3) Books (Notebooks)
157
- //
158
- // 3a) List notebooks (GET /books)
159
- server.resource("books", new mcp_js_1.ResourceTemplate("inkdrop://books{?limit,skip}", { list: undefined }), async (uri) => {
160
- const qs = Object.fromEntries(uri.searchParams.entries());
161
- const body = await fetchJSON("/books", qs);
162
- return {
163
- contents: [
164
- {
165
- uri: uri.href,
166
- text: JSON.stringify(body, null, 2)
167
- }
168
- ]
169
- };
170
- });
171
- // 3b) Create/update a book (POST /books)
172
- server.tool("save-book", {
173
- _id: zod_1.z.string().optional(),
174
- _rev: zod_1.z.string().optional(),
175
- name: zod_1.z.string().optional(),
176
- parentBookId: zod_1.z.string().optional()
177
- }, async (args) => {
178
- const ret = await postJSON("/books", args);
179
- return {
180
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
181
- };
182
- });
183
- // 3c) Get a single book (GET /book:docId)
184
- server.resource("single-book", new mcp_js_1.ResourceTemplate("inkdrop://book/{docId}{?rev,attachments}", { list: undefined }), async (uri, { docId }) => {
185
- const qs = Object.fromEntries(uri.searchParams.entries());
186
- const body = await fetchJSON(`/book:${docId}`, qs);
187
- return {
188
- contents: [
189
- {
190
- uri: uri.href,
191
- text: JSON.stringify(body, null, 2)
192
- }
193
- ]
194
- };
195
- });
196
- // 3d) Delete book (DELETE /book:docId)
197
- server.tool("delete-book", { docId: zod_1.z.string() }, async ({ docId }) => {
198
- const ret = await deleteJSON(`/book:${docId}`);
199
- return {
200
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
201
- };
202
- });
203
- //
204
- // 4) Tags
205
- //
206
- // 4a) List tags (GET /tags)
207
- server.resource("tags", new mcp_js_1.ResourceTemplate("inkdrop://tags{?limit,skip}", { list: undefined }), async (uri) => {
208
- const qs = Object.fromEntries(uri.searchParams.entries());
209
- const body = await fetchJSON("/tags", qs);
210
- return {
211
- contents: [
212
- {
213
- uri: uri.href,
214
- text: JSON.stringify(body, null, 2)
215
- }
216
- ]
217
- };
218
- });
219
- // 4b) Create/update tag (POST /tags)
220
- server.tool("save-tag", {
221
- _id: zod_1.z.string().optional(),
222
- _rev: zod_1.z.string().optional(),
223
- name: zod_1.z.string(),
224
- color: zod_1.z.string().optional()
225
- }, async (args) => {
226
- const ret = await postJSON("/tags", args);
227
- return {
228
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
229
- };
230
- });
231
- // 4c) Get tag (GET /tag:docId)
232
- server.resource("single-tag", new mcp_js_1.ResourceTemplate("inkdrop://tag/{docId}{?rev,attachments}", { list: undefined }), async (uri, { docId }) => {
233
- const qs = Object.fromEntries(uri.searchParams.entries());
234
- const body = await fetchJSON(`/tag:${docId}`, qs);
235
- return {
236
- contents: [
237
- {
238
- uri: uri.href,
239
- text: JSON.stringify(body, null, 2)
240
- }
241
- ]
242
- };
243
- });
244
- // 4d) Delete tag (DELETE /tag:docId)
245
- server.tool("delete-tag", { docId: zod_1.z.string() }, async ({ docId }) => {
246
- const ret = await deleteJSON(`/tag:${docId}`);
247
- return {
248
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
249
- };
250
- });
251
- //
252
- // 5) Files
253
- //
254
- // 5a) List files (GET /files)
255
- server.resource("files", new mcp_js_1.ResourceTemplate("inkdrop://files{?limit,skip}", { list: undefined }), async (uri) => {
256
- const qs = Object.fromEntries(uri.searchParams.entries());
257
- const body = await fetchJSON("/files", qs);
258
- return {
259
- contents: [
260
- {
261
- uri: uri.href,
262
- text: JSON.stringify(body, null, 2)
263
- }
264
- ]
265
- };
266
- });
267
- // 5b) Create/update file (POST /files)
268
- server.tool("save-file", {
269
- _id: zod_1.z.string().optional(),
270
- _rev: zod_1.z.string().optional(),
271
- name: zod_1.z.string(),
272
- contentType: zod_1.z.string().optional(),
273
- contentLength: zod_1.z.number().optional(),
274
- publicIn: zod_1.z.array(zod_1.z.string()).optional(),
275
- _attachments: zod_1.z.any().optional()
276
- }, async (args) => {
277
- const ret = await postJSON("/files", args);
278
- return {
279
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
280
- };
281
- });
282
- // 5c) Get file (GET /file:docId)
283
- server.resource("single-file", new mcp_js_1.ResourceTemplate("inkdrop://file/{docId}{?rev,attachments}", { list: undefined }), async (uri, { docId }) => {
284
- const qs = Object.fromEntries(uri.searchParams.entries());
285
- const body = await fetchJSON(`/file:${docId}`, qs);
286
- return {
287
- contents: [
288
- {
289
- uri: uri.href,
290
- text: JSON.stringify(body, null, 2)
291
- }
292
- ]
293
- };
294
- });
295
- // 5d) Delete file (DELETE /file:docId)
296
- server.tool("delete-file", { docId: zod_1.z.string() }, async ({ docId }) => {
297
- const ret = await deleteJSON(`/file:${docId}`);
298
- return {
299
- content: [{ type: "text", text: JSON.stringify(ret, null, 2) }]
300
- };
301
- });
302
- //
303
- // 6) Changes feed (GET /_changes)
304
- //
305
- server.resource("changes", new mcp_js_1.ResourceTemplate("inkdrop://changes{?descending,since,limit,include_docs,conflicts,attachments}", { list: undefined }), async (uri) => {
306
- const qs = Object.fromEntries(uri.searchParams.entries());
307
- const body = await fetchJSON("/_changes", qs);
308
- return {
309
- contents: [
310
- {
311
- uri: uri.href,
312
- text: JSON.stringify(body, null, 2)
313
- }
314
- ]
315
- };
316
- });
317
- // Done! We have a resource/tool for every Inkdrop endpoint.
318
- return server;
319
- }
320
- /** Actually run an HTTP server exposing this MCP server over SSE and POST. */
321
- async function main() {
322
- const mcpServer = createInkdropProxyServer();
323
- const transport = new stdio_js_1.StdioServerTransport();
324
- console.log("MCP (stdio) proxy for Inkdrop is now running...");
325
- console.log("Send MCP requests on stdin, responses come out on stdout.\n");
326
- await mcpServer.connect(transport);
327
- }
328
- main().catch((err) => {
329
- console.error("Error starting proxy:", err);
330
- process.exit(1);
331
- });