@inkdropapp/mcp-server 1.4.0 → 1.6.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.
@@ -1,7 +1,5 @@
1
1
  {
2
2
  "permissions": {
3
- "allow": [
4
- "Bash(claude mcp list:*)"
5
- ]
3
+ "allow": ["Bash(claude mcp list:*)"]
6
4
  }
7
5
  }
package/.oxfmtrc.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "$schema": "./node_modules/oxfmt/configuration_schema.json",
3
+ "arrowParens": "avoid",
4
+ "singleQuote": true,
5
+ "bracketSpacing": true,
6
+ "endOfLine": "lf",
7
+ "semi": false,
8
+ "tabWidth": 2,
9
+ "trailingComma": "none",
10
+ "sortPackageJson": false,
11
+ "ignorePatterns": []
12
+ }
package/README.md CHANGED
@@ -4,27 +4,7 @@ A [Model Context Protocol](https://github.com/modelcontextprotocol) server for t
4
4
 
5
5
  ## Installation
6
6
 
7
- 1. [Set up a local HTTP server](https://developers.inkdrop.app/guides/integrate-with-external-programs)
8
-
9
- 2. Add server config to Claude Desktop:
10
- - MacOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
11
- - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
12
-
13
- ```json
14
- {
15
- "mcpServers": {
16
- "inkdrop": {
17
- "command": "npx",
18
- "args": ["-y", "@inkdropapp/mcp-server"],
19
- "env": {
20
- "INKDROP_LOCAL_SERVER_URL": "http://localhost:19840",
21
- "INKDROP_LOCAL_USERNAME": "your-local-server-username",
22
- "INKDROP_LOCAL_PASSWORD": "your-local-server-password"
23
- }
24
- }
25
- }
26
- }
27
- ```
7
+ Read [the docs here](https://docs.inkdrop.app/reference/mcp-server).
28
8
 
29
9
  ## Components
30
10
 
@@ -54,50 +34,81 @@ A [Model Context Protocol](https://github.com/modelcontextprotocol) server for t
54
34
  - `sort`: Sort field (`updatedAt`, `createdAt`, or `title`). Default: `updatedAt`.
55
35
  - `descending`: Reverse the order of output. Default: `true`.
56
36
  - Note: Results include truncated note bodies (200 characters). Use `read-note` to get full content.
57
- 5. **`create-note`**: Create a new note in the database.
37
+ 5. **`list-templates`**: List note templates — your custom templates, followed by the official ones bundled with Inkdrop.
38
+ - Optional inputs:
39
+ - `keyword`: Filter templates by fuzzy-matching their titles.
40
+ - Note: Results include truncated template bodies (200 characters). Use `read-note` to get full content.
41
+ 6. **`create-note`**: Create a new note in the database.
58
42
  - Required inputs:
59
- - `bookId`: The notebook ID. Must start with 'book:' or be 'trash'.
43
+ - `bookId`: The notebook ID. Must start with 'book:' or be 'trash' or 'template'. Specify 'template' to create a custom note template.
60
44
  - `title`: The note title.
61
45
  - `body`: The content of the note in Markdown.
62
46
  - Optional inputs:
63
47
  - `status`: The note status (`none`, `active`, `onHold`, `completed`, `dropped`).
64
48
  - `tags`: An array of tag IDs to assign to the note. Each must start with 'tag:'.
65
- 6. **`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 an existing note in the database. Only the fields you provide will be updated; omitted fields remain unchanged.
66
50
  - Required inputs:
67
51
  - `_id`: The note ID. Must start with 'note:'.
68
52
  - `_rev`: The revision ID (CouchDB MVCC-token).
69
53
  - Optional inputs:
70
- - `bookId`: The notebook ID. Must start with 'book:' or be 'trash'.
54
+ - `bookId`: The notebook ID. Must start with 'book:' or be 'trash' or 'template'.
71
55
  - `title`: The note title.
72
56
  - `body`: The content of the note in Markdown.
73
57
  - `status`: The note status (`none`, `active`, `onHold`, `completed`, `dropped`).
74
58
  - `tags`: An array of tag IDs to assign to the note. Each must start with 'tag:'.
75
- 7. **`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.
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.
76
60
  - Required inputs:
77
61
  - `_id`: The note ID. Must start with 'note:'.
78
62
  - `_rev`: The revision ID (CouchDB MVCC-token).
79
63
  - `old_string`: The exact text to find in the note body. Must match exactly one occurrence. Include enough surrounding context to ensure a unique match.
80
64
  - `new_string`: The text to replace `old_string` with. Use an empty string to delete the matched text.
81
- 8. **`list-notebooks`**: Retrieve a list of all notebooks.
82
- 9. **`read-book`**: Retrieve a single notebook by its ID.
83
- - Required inputs:
84
- - `bookId`: The notebook ID. Must start with 'book:'.
85
- 10. **`list-tags`**: Retrieve a list of all tags.
86
- 11. **`read-tag`**: Retrieve a single tag by its ID.
65
+ 9. **`list-notebooks`**: Retrieve a list of all notebooks.
66
+ 10. **`read-book`**: Retrieve a single notebook by its ID.
67
+ - Required inputs:
68
+ - `bookId`: The notebook ID. Must start with 'book:'.
69
+ 11. **`create-book`**: Create a new notebook in the database.
70
+ - Required inputs:
71
+ - `name`: The notebook name.
72
+ - Optional inputs:
73
+ - `parentBookId`: The ID of the parent notebook. Must start with 'book:'. Omit it to create the notebook at the root level.
74
+ 12. **`update-book`**: Update an existing notebook in the database. Only the fields you provide will be updated; omitted fields remain unchanged, so you don't need to read the notebook first.
75
+ - Required inputs:
76
+ - `_id`: The notebook ID. Must start with 'book:'.
77
+ - Optional inputs:
78
+ - `_rev`: The revision ID (CouchDB MVCC-token). Only needed as an optimistic-concurrency guard — pass it to make the update fail on a conflicting concurrent edit.
79
+ - `name`: The notebook name.
80
+ - `parentBookId`: The ID of the parent notebook. Pass `null` to move the notebook to the root level.
81
+ 13. **`list-tags`**: Retrieve a list of all tags.
82
+ 14. **`read-tag`**: Retrieve a single tag by its ID.
87
83
  - Required inputs:
88
84
  - `tagId`: The tag ID. Must start with 'tag:'.
89
- 12. **`create-tag`**: Create a new tag in the database.
85
+ 15. **`create-tag`**: Create a new tag in the database.
90
86
  - Required inputs:
91
87
  - `name`: The name of the tag.
92
88
  - Optional inputs:
93
89
  - `color`: The color type of the tag (`default`, `red`, `orange`, `yellow`, `olive`, `green`, `teal`, `blue`, `violet`, `purple`, `pink`, `brown`, `grey`, `black`). Default: `default`.
94
- 13. **`update-tag`**: Update an existing tag in the database.
90
+ 16. **`update-tag`**: Update an existing tag in the database. Only the fields you provide will be updated; omitted fields remain unchanged, so you don't need to read the tag first.
95
91
  - Required inputs:
96
92
  - `_id`: The tag ID. Must start with 'tag:'.
97
- - `_rev`: The revision ID (CouchDB MVCC-token).
93
+ - Optional inputs:
94
+ - `_rev`: The revision ID (CouchDB MVCC-token). Only needed as an optimistic-concurrency guard — pass it to make the update fail on a conflicting concurrent edit.
98
95
  - `name`: The name of the tag.
96
+ - `color`: The color type of the tag. Omit it to keep the tag's current color.
97
+ 17. **`create-file`**: Create a new attachment file in the database from a local image file or from base64 image data. Returns the Markdown to embed the attachment in a note body.
98
+ - Required inputs: exactly one of
99
+ - `filePath`: Absolute path to a local image file to attach. Preferred — it keeps the image bytes out of the conversation.
100
+ - `data`: Base64-encoded image data, without a `data:` URI prefix.
101
+ - Optional inputs:
102
+ - `name`: The file name. Defaults to the file name of `filePath`, or `image.<ext>` when `data` is given.
103
+ - `contentType`: The MIME type (`image/png`, `image/jpeg`, `image/jpg`, `image/svg+xml`, `image/gif`, `image/heic`, `image/heif`). Inferred from the `filePath` extension when omitted, so it is required with `data`.
104
+ - `publicIn`: An array of note IDs where the attachment is included. Each must start with 'note:'.
105
+ - Note: Attachments are limited to 10MB.
106
+ 18. **`read-file`**: Retrieve an attachment file by its ID. Returns the file metadata, and the image itself when it is a PNG, JPEG or GIF.
107
+ - Required inputs:
108
+ - `fileId`: The attachment ID. Must start with 'file:'.
99
109
  - Optional inputs:
100
- - `color`: The color type of the tag. Default: `default`.
110
+ - `outputPath`: Absolute path to write the attachment to. When given, the file is saved there and its bytes are not returned inline. Required to get at SVG, HEIC and HEIF attachments, which cannot be displayed inline.
111
+ - `includeImage`: Whether to return the image alongside the metadata. Default: `true`. Set to `false` to fetch only the metadata of a large attachment.
101
112
 
102
113
  ## Debugging
103
114
 
package/dist/api.js CHANGED
@@ -6,10 +6,10 @@ exports.postJSON = postJSON;
6
6
  const config = {
7
7
  baseUrl: process.env.INKDROP_LOCAL_SERVER_URL,
8
8
  username: process.env.INKDROP_LOCAL_USERNAME,
9
- password: process.env.INKDROP_LOCAL_PASSWORD,
9
+ password: process.env.INKDROP_LOCAL_PASSWORD
10
10
  };
11
11
  function getAuthHeaders() {
12
- const token = Buffer.from(`${config.username}:${config.password}`).toString("base64");
12
+ const token = Buffer.from(`${config.username}:${config.password}`).toString('base64');
13
13
  return {
14
14
  Authorization: `Basic ${token}`
15
15
  };
@@ -28,20 +28,20 @@ async function fetchJSON(path, qs = {}) {
28
28
  if (!resp.ok) {
29
29
  throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
30
30
  }
31
- return await resp.json();
31
+ return (await resp.json());
32
32
  }
33
33
  async function postJSON(path, body) {
34
34
  const url = buildUrl(path);
35
35
  const resp = await fetch(url, {
36
- method: "POST",
36
+ method: 'POST',
37
37
  headers: {
38
38
  ...getAuthHeaders(),
39
- "Content-Type": "application/json"
39
+ 'Content-Type': 'application/json'
40
40
  },
41
41
  body: JSON.stringify(body)
42
42
  });
43
43
  if (!resp.ok) {
44
44
  throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
45
45
  }
46
- return await resp.json();
46
+ return (await resp.json());
47
47
  }
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
+ const node_crypto_1 = require("node:crypto");
5
+ const promises_1 = require("node:fs/promises");
6
+ const node_path_1 = require("node:path");
4
7
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
5
8
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
6
9
  const inkdrop_model_1 = require("inkdrop-model");
@@ -75,9 +78,7 @@ server.registerTool('read-note', {
75
78
  }
76
79
  ]
77
80
  : []),
78
- ...(templateBlockText
79
- ? [{ type: 'text', text: templateBlockText }]
80
- : [])
81
+ ...(templateBlockText ? [{ type: 'text', text: templateBlockText }] : [])
81
82
  ]
82
83
  };
83
84
  });
@@ -214,7 +215,7 @@ You have to retrieve the full note content by calling \`read-note\`.
214
215
  bookId: zod_1.z
215
216
  .string()
216
217
  .optional()
217
- .describe(`ID of the notebook. It always starts with 'book:'. You can retrieve a list of notebooks with \`list-notebooks\``),
218
+ .describe(`ID of the notebook. It always starts with 'book:'. You can retrieve a list of notebooks with \`list-notebooks\`. The pseudo-notebooks 'trash' and 'template' are not supported here; use \`list-templates\` for templates`),
218
219
  tagIds: zod_1.z
219
220
  .array(zod_1.z.string())
220
221
  .optional()
@@ -231,11 +232,7 @@ You have to retrieve the full note content by calling \`read-note\`.
231
232
  .optional()
232
233
  .default(true)
233
234
  .describe(`Reverse the order of the output documents`),
234
- limit: zod_1.z
235
- .number()
236
- .optional()
237
- .default(100)
238
- .describe(`Limit the number of results returned`)
235
+ limit: zod_1.z.number().optional().default(100).describe(`Limit the number of results returned`)
239
236
  }
240
237
  }, async ({ bookId, tagIds, keyword, sort, descending, limit }) => {
241
238
  const bookFilter = bookId ? `bookId:${bookId.split(':')[1]}` : '';
@@ -262,6 +259,35 @@ You have to retrieve the full note content by calling \`read-note\`.
262
259
  ]
263
260
  };
264
261
  });
262
+ server.registerTool('list-templates', {
263
+ description: `List note templates: your custom templates, followed by the official ones bundled with Inkdrop.
264
+ Templates are notes whose \`bookId\` is \`template\`. Official templates are read-only.
265
+ The result does not include entire template bodies as they are truncated in 200 characters.
266
+ You have to retrieve the full template content by calling \`read-note\`.
267
+ `,
268
+ inputSchema: {
269
+ keyword: zod_1.z
270
+ .string()
271
+ .optional()
272
+ .describe('Filter templates by fuzzy-matching their titles. Search qualifiers such as `book:` or `tag:` are not supported.')
273
+ }
274
+ }, async ({ keyword }) => {
275
+ const templates = await (0, api_1.fetchJSON)('/templates', { keyword });
276
+ const summaries = templates.map(template => {
277
+ return {
278
+ ...template,
279
+ body: template.body.substring(0, 200)
280
+ };
281
+ });
282
+ return {
283
+ content: [
284
+ {
285
+ type: 'text',
286
+ text: JSON.stringify(summaries, null, 2)
287
+ }
288
+ ]
289
+ };
290
+ });
265
291
  server.registerTool('create-note', {
266
292
  description: 'Create a new note in the database',
267
293
  inputSchema: {
@@ -269,13 +295,10 @@ server.registerTool('create-note', {
269
295
  .string()
270
296
  .min(5)
271
297
  .max(128)
272
- .regex(/^(book:|trash$)/)
273
- .describe('The notebook ID'),
298
+ .regex(/^(book:|trash$|template$)/)
299
+ .describe('The notebook ID. Specify `template` to create a custom note template'),
274
300
  title: zod_1.z.string().max(128).describe('The note title'),
275
- body: zod_1.z
276
- .string()
277
- .max(1048576)
278
- .describe('The content of the note represented with Markdown'),
301
+ body: zod_1.z.string().max(1048576).describe('The content of the note represented with Markdown'),
279
302
  status: zod_1.z
280
303
  .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
281
304
  .optional()
@@ -312,9 +335,9 @@ server.registerTool('update-note', {
312
335
  .string()
313
336
  .min(5)
314
337
  .max(128)
315
- .regex(/^(book:|trash$)/)
338
+ .regex(/^(book:|trash$|template$)/)
316
339
  .optional()
317
- .describe('The notebook ID'),
340
+ .describe('The notebook ID. Specify `template` to turn the note into a custom note template'),
318
341
  title: zod_1.z.string().max(128).optional().describe('The note title'),
319
342
  body: zod_1.z
320
343
  .string()
@@ -394,9 +417,7 @@ server.registerTool('patch-note', {
394
417
  isError: true
395
418
  };
396
419
  }
397
- const patched = body.slice(0, firstIndex) +
398
- new_string +
399
- body.slice(firstIndex + old_string.length);
420
+ const patched = body.slice(0, firstIndex) + new_string + body.slice(firstIndex + old_string.length);
400
421
  const res = await (0, api_1.postJSON)('/notes', {
401
422
  ...existingNote,
402
423
  body: patched,
@@ -446,10 +467,7 @@ const TagColors = Object.values(inkdrop_model_1.TAG_COLOR);
446
467
  server.registerTool('create-tag', {
447
468
  description: 'Create a new tag in the database',
448
469
  inputSchema: {
449
- color: zod_1.z
450
- .enum(TagColors)
451
- .default('default')
452
- .describe('The color type of the tag'),
470
+ color: zod_1.z.enum(TagColors).default('default').describe('The color type of the tag'),
453
471
  name: zod_1.z.string().max(64).describe('The name of the tag')
454
472
  }
455
473
  }, async (tagData) => {
@@ -464,7 +482,7 @@ server.registerTool('create-tag', {
464
482
  };
465
483
  });
466
484
  server.registerTool('update-tag', {
467
- description: 'Update the existing tag in the database. You should retrieve the existing tag with \`list-tags\` first. When updating the tag, you must specify not only the changed fields but also all the un-changed fields.',
485
+ description: 'Update the existing tag in the database. Only the fields you provide will be updated; omitted fields remain unchanged, so you do not need to read the tag first. Call `list-tags` or `read-tag` to find the tag ID.',
468
486
  inputSchema: {
469
487
  _id: zod_1.z
470
488
  .string()
@@ -474,15 +492,13 @@ server.registerTool('update-tag', {
474
492
  .describe('The unique document ID which should start with `tag:` and the remains are randomly generated string'),
475
493
  _rev: zod_1.z
476
494
  .string()
477
- .describe('This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'),
478
- color: zod_1.z
479
- .enum(TagColors)
480
- .default('default')
481
- .describe('The color type of the tag'),
482
- name: zod_1.z.string().max(64).describe('The name of the tag')
495
+ .optional()
496
+ .describe('This is a CouchDB specific field. The current MVCC-token/revision of this document. Optional: the server merges your fields into the stored tag, so it is only needed as an optimistic-concurrency guard. Pass it when you have read the tag first and want the update to fail on a conflicting concurrent edit.'),
497
+ color: zod_1.z.enum(TagColors).optional().describe('The color type of the tag'),
498
+ name: zod_1.z.string().max(64).optional().describe('The name of the tag')
483
499
  }
484
- }, async (tagData) => {
485
- const res = await (0, api_1.postJSON)(`/tags`, tagData);
500
+ }, async ({ _id, ...updateFields }) => {
501
+ const res = await (0, api_1.postJSON)(`/${_id}`, updateFields);
486
502
  return {
487
503
  content: [
488
504
  {
@@ -523,46 +539,240 @@ server.registerTool('read-book', {
523
539
  ]
524
540
  };
525
541
  });
526
- server.registerPrompt('inkdrop-prompt', { description: 'Instructions for using the Inkdrop MCP server effectively' }, () => ({
527
- messages: [
528
- {
529
- role: 'assistant',
530
- content: {
542
+ server.registerTool('create-book', {
543
+ description: 'Create a new notebook in the database. To create a nested notebook, pass the parent notebook ID as `parentBookId`. Call `list-notebooks` first to find it.',
544
+ inputSchema: {
545
+ name: zod_1.z.string().min(1).max(64).describe('The notebook name'),
546
+ parentBookId: zod_1.z
547
+ .string()
548
+ .min(6)
549
+ .max(128)
550
+ .regex(/^book:/)
551
+ .optional()
552
+ .describe('The ID of the parent notebook. Omit it to create the notebook at the root level.')
553
+ }
554
+ }, async (bookData) => {
555
+ const res = await (0, api_1.postJSON)(`/books`, bookData);
556
+ return {
557
+ content: [
558
+ {
531
559
  type: 'text',
532
- text: `Inkdrop is a Markdown note-taking app designed for programmers to help their coding workflow.
533
- This server provides access to the Inkdrop database. Use it to search notes, create new notes, and track issues written in the notes.
534
-
535
- Key capabilities:
536
- - Search notes by keyword
537
- - Get a note by its ID
538
- - Get a list of all notebooks
539
- - Create a new note
540
- - Update an existing note
541
-
542
- Best practices:
543
- - When searching:
544
- - Use specific, targeted queries for better results (e.g., "auth mobile app" rather than just "auth")
545
- - Apply relevant filters when asked or when you can infer the appropriate filters to narrow results
546
- - Use \`read-note\` to get the full note content
547
-
548
- Model schemas:
549
-
550
- \`\`\`json
551
- ${JSON.stringify(inkdrop_model_1.NoteSchema, null, 2)}
552
- \`\`\`
553
-
554
- \`\`\`json
555
- ${JSON.stringify(inkdrop_model_1.BookSchema, null, 2)}
556
- \`\`\`
557
-
558
- \`\`\`json
559
- ${JSON.stringify(inkdrop_model_1.TagSchema, null, 2)}
560
- \`\`\`
561
- `
560
+ text: JSON.stringify(res, null, 2)
561
+ }
562
+ ]
563
+ };
564
+ });
565
+ server.registerTool('update-book', {
566
+ description: 'Update the existing notebook in the database. Only the fields you provide will be updated; omitted fields remain unchanged, so you do not need to read the notebook first. Call `list-notebooks` or `read-book` to find the notebook ID.',
567
+ inputSchema: {
568
+ _id: zod_1.z
569
+ .string()
570
+ .min(6)
571
+ .max(128)
572
+ .regex(/^book:/)
573
+ .describe('The unique document ID which should start with `book:` and the remains are randomly generated string'),
574
+ _rev: zod_1.z
575
+ .string()
576
+ .optional()
577
+ .describe('This is a CouchDB specific field. The current MVCC-token/revision of this document. Optional: the server merges your fields into the stored notebook, so it is only needed as an optimistic-concurrency guard. Pass it when you have read the notebook first and want the update to fail on a conflicting concurrent edit.'),
578
+ name: zod_1.z.string().min(1).max(64).optional().describe('The notebook name'),
579
+ parentBookId: zod_1.z
580
+ .string()
581
+ .min(6)
582
+ .max(128)
583
+ .regex(/^book:/)
584
+ .nullable()
585
+ .optional()
586
+ .describe('The ID of the parent notebook. Pass `null` to move the notebook to the root level.')
587
+ }
588
+ }, async ({ _id, ...updateFields }) => {
589
+ const res = await (0, api_1.postJSON)(`/${_id}`, {
590
+ ...updateFields,
591
+ updatedAt: +new Date()
592
+ });
593
+ return {
594
+ content: [
595
+ {
596
+ type: 'text',
597
+ text: JSON.stringify(res, null, 2)
598
+ }
599
+ ]
600
+ };
601
+ });
602
+ const ImageFileTypes = [...inkdrop_model_1.supportedImageFileTypes];
603
+ server.registerTool('create-file', {
604
+ description: 'Create a new attachment file in the database from a local image file or from base64 image data. ' +
605
+ 'Returns the Markdown to embed the attachment in a note body. ' +
606
+ 'Prefer `filePath` over `data`: it keeps the image bytes out of the conversation.',
607
+ inputSchema: {
608
+ filePath: zod_1.z
609
+ .string()
610
+ .optional()
611
+ .describe('Absolute path to a local image file to attach. Either this or `data` must be given.'),
612
+ data: zod_1.z
613
+ .string()
614
+ .optional()
615
+ .describe('Base64-encoded image data, without a `data:` URI prefix. Use `filePath` instead whenever the image is already on disk.'),
616
+ name: zod_1.z
617
+ .string()
618
+ .min(1)
619
+ .max(128)
620
+ .optional()
621
+ .describe('The file name. Defaults to the file name of `filePath`, or `image.<ext>` when `data` is given.'),
622
+ contentType: zod_1.z
623
+ .enum(ImageFileTypes)
624
+ .optional()
625
+ .describe('The MIME type of the image. Inferred from the `filePath` extension when omitted, so it is required with `data`.')
626
+ }
627
+ }, async ({ filePath, data, name, contentType }) => {
628
+ if ((filePath === undefined) === (data === undefined)) {
629
+ return {
630
+ content: [
631
+ {
632
+ type: 'text',
633
+ text: 'Failed to create the attachment: provide exactly one of `filePath` or `data`.'
634
+ }
635
+ ],
636
+ isError: true
637
+ };
638
+ }
639
+ let buffer;
640
+ if (filePath !== undefined) {
641
+ try {
642
+ buffer = await (0, promises_1.readFile)(filePath);
643
+ }
644
+ catch (e) {
645
+ return {
646
+ content: [
647
+ {
648
+ type: 'text',
649
+ text: `Failed to read the file at ${filePath}: ${e.message}`
650
+ }
651
+ ],
652
+ isError: true
653
+ };
654
+ }
655
+ contentType ??= (0, utils_1.inferImageContentType)(filePath);
656
+ name ??= (0, node_path_1.basename)(filePath);
657
+ }
658
+ else {
659
+ buffer = Buffer.from(data, 'base64');
660
+ }
661
+ if (!contentType) {
662
+ return {
663
+ content: [
664
+ {
665
+ type: 'text',
666
+ text: `Failed to create the attachment: could not infer the content type${filePath ? ` from ${filePath}` : ''}. Pass \`contentType\` explicitly. Supported types: ${inkdrop_model_1.supportedImageFileTypes.join(', ')}.`
667
+ }
668
+ ],
669
+ isError: true
670
+ };
671
+ }
672
+ const base64 = buffer.toString('base64');
673
+ const contentLength = Math.floor((base64.length * 3) / 4);
674
+ if (contentLength > inkdrop_model_1.maxAttachmentFileSize) {
675
+ return {
676
+ content: [
677
+ {
678
+ type: 'text',
679
+ text: `Failed to create the attachment: the file is ${contentLength} bytes, over the ${inkdrop_model_1.maxAttachmentFileSize} byte limit.`
680
+ }
681
+ ],
682
+ isError: true
683
+ };
684
+ }
685
+ const res = await (0, api_1.postJSON)('/files', {
686
+ name: name ?? `image.${contentType.replace(/^image\//, '')}`,
687
+ contentType,
688
+ contentLength,
689
+ publicIn: [],
690
+ md5digest: (0, node_crypto_1.createHash)('md5').update(buffer).digest('hex'),
691
+ _attachments: {
692
+ index: {
693
+ content_type: contentType,
694
+ data: base64
562
695
  }
563
696
  }
564
- ]
565
- }));
697
+ });
698
+ return {
699
+ content: [
700
+ {
701
+ type: 'text',
702
+ text: JSON.stringify(res, null, 2)
703
+ },
704
+ {
705
+ type: 'text',
706
+ text: `Markdown to embed this attachment in a note body:\n\n![${name}](${(0, utils_1.getFileUri)(res.id)})`
707
+ }
708
+ ]
709
+ };
710
+ });
711
+ server.registerTool('read-file', {
712
+ description: 'Retrieve an attachment file by its ID. Returns the file metadata, and the image itself when it is a PNG, JPEG or GIF. ' +
713
+ 'Pass `outputPath` to write the attachment to disk instead — required to get at SVG, HEIC and HEIF attachments, which cannot be displayed inline.',
714
+ inputSchema: {
715
+ fileId: zod_1.z
716
+ .string()
717
+ .describe('ID of the attachment to retrieve. It can be found as `_id` in the file docs. It always starts with \`file:\`.'),
718
+ outputPath: zod_1.z
719
+ .string()
720
+ .optional()
721
+ .describe('Absolute path to write the attachment to. When given, the file is saved there and its bytes are not returned inline.'),
722
+ includeImage: zod_1.z
723
+ .boolean()
724
+ .optional()
725
+ .default(true)
726
+ .describe('Whether to return the image itself alongside the metadata. Set to false to fetch only the metadata of a large attachment.')
727
+ }
728
+ }, async ({ fileId, outputPath, includeImage }) => {
729
+ if (!fileId.startsWith('file:'))
730
+ fileId = `file:${fileId}`;
731
+ const needsData = includeImage || outputPath !== undefined;
732
+ const file = await (0, api_1.fetchJSON)(`/${fileId}`, {
733
+ attachments: needsData ? true : undefined
734
+ });
735
+ const { _attachments, ...metadata } = file;
736
+ const base64 = typeof _attachments?.index?.data === 'string' ? _attachments.index.data : undefined;
737
+ const attachmentBlock = async () => {
738
+ if (!needsData)
739
+ return [];
740
+ if (!base64) {
741
+ return [
742
+ {
743
+ type: 'text',
744
+ text: 'The attachment data could not be read from the document.'
745
+ }
746
+ ];
747
+ }
748
+ if (outputPath !== undefined) {
749
+ await (0, promises_1.writeFile)(outputPath, Buffer.from(base64, 'base64'));
750
+ return [{ type: 'text', text: `Attachment written to ${outputPath}` }];
751
+ }
752
+ if (!(0, utils_1.isViewableImageType)(file.contentType)) {
753
+ return [
754
+ {
755
+ type: 'text',
756
+ text: `The attachment is a ${file.contentType} file, which cannot be displayed inline. Pass \`outputPath\` to write it to disk.`
757
+ }
758
+ ];
759
+ }
760
+ return [
761
+ {
762
+ type: 'image',
763
+ data: base64,
764
+ // `image/jpg` is not a real MIME type; the image block expects `image/jpeg`.
765
+ mimeType: file.contentType === 'image/jpg' ? 'image/jpeg' : file.contentType
766
+ }
767
+ ];
768
+ };
769
+ return {
770
+ content: [
771
+ { type: 'text', text: JSON.stringify(metadata, null, 2) },
772
+ ...(await attachmentBlock())
773
+ ]
774
+ };
775
+ });
566
776
  async function runServer() {
567
777
  const transport = new stdio_js_1.StdioServerTransport();
568
778
  await server.connect(transport);