@inkdropapp/mcp-server 1.4.0 → 1.5.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
  }
@@ -17,14 +17,14 @@ jobs:
17
17
  # github.event.pull_request.user.login == 'external-contributor' ||
18
18
  # github.event.pull_request.user.login == 'new-developer' ||
19
19
  # github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
20
-
20
+
21
21
  runs-on: ubuntu-latest
22
22
  permissions:
23
23
  contents: read
24
24
  pull-requests: read
25
25
  issues: read
26
26
  id-token: write
27
-
27
+
28
28
  steps:
29
29
  - name: Checkout repository
30
30
  uses: actions/checkout@v4
@@ -39,7 +39,7 @@ jobs:
39
39
 
40
40
  # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
41
41
  # model: "claude-opus-4-20250514"
42
-
42
+
43
43
  # Direct prompt for automated review (no @claude mention needed)
44
44
  direct_prompt: |
45
45
  Please review this pull request and provide feedback on:
@@ -48,12 +48,12 @@ jobs:
48
48
  - Performance considerations
49
49
  - Security concerns
50
50
  - Test coverage
51
-
51
+
52
52
  Be constructive and helpful in your feedback.
53
53
 
54
54
  # Optional: Use sticky comments to make Claude reuse the same comment on subsequent pushes to the same PR
55
55
  # use_sticky_comment: true
56
-
56
+
57
57
  # Optional: Customize review based on file types
58
58
  # direct_prompt: |
59
59
  # Review this PR focusing on:
@@ -61,18 +61,17 @@ jobs:
61
61
  # - For API endpoints: Security, input validation, and error handling
62
62
  # - For React components: Performance, accessibility, and best practices
63
63
  # - For tests: Coverage, edge cases, and test quality
64
-
64
+
65
65
  # Optional: Different prompts for different authors
66
66
  # direct_prompt: |
67
- # ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' &&
67
+ # ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' &&
68
68
  # 'Welcome! Please review this PR from a first-time contributor. Be encouraging and provide detailed explanations for any suggestions.' ||
69
69
  # 'Please provide a thorough code review focusing on our coding standards and best practices.' }}
70
-
70
+
71
71
  # Optional: Add specific tools for running tests or linting
72
72
  # allowed_tools: "Bash(npm run test),Bash(npm run lint),Bash(npm run typecheck)"
73
-
73
+
74
74
  # Optional: Skip review for certain conditions
75
75
  # if: |
76
76
  # !contains(github.event.pull_request.title, '[skip-review]') &&
77
77
  # !contains(github.event.pull_request.title, '[WIP]')
78
-
@@ -39,26 +39,25 @@ jobs:
39
39
  # This is an optional setting that allows Claude to read CI results on PRs
40
40
  additional_permissions: |
41
41
  actions: read
42
-
42
+
43
43
  # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
44
44
  # model: "claude-opus-4-20250514"
45
-
45
+
46
46
  # Optional: Customize the trigger phrase (default: @claude)
47
47
  # trigger_phrase: "/claude"
48
-
48
+
49
49
  # Optional: Trigger when specific user is assigned to an issue
50
50
  # assignee_trigger: "claude-bot"
51
-
51
+
52
52
  # Optional: Allow Claude to run specific commands
53
53
  # allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)"
54
-
54
+
55
55
  # Optional: Add custom instructions for Claude to customize its behavior for your project
56
56
  # custom_instructions: |
57
57
  # Follow our coding standards
58
58
  # Ensure all new code has tests
59
59
  # Use TypeScript for new files
60
-
60
+
61
61
  # Optional: Custom environment variables for Claude
62
62
  # claude_env: |
63
63
  # NODE_ENV: test
64
-
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
 
@@ -82,22 +62,49 @@ A [Model Context Protocol](https://github.com/modelcontextprotocol) server for t
82
62
  9. **`read-book`**: Retrieve a single notebook by its ID.
83
63
  - Required inputs:
84
64
  - `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
+ 10. **`create-book`**: Create a new notebook in the database.
66
+ - Required inputs:
67
+ - `name`: The notebook name.
68
+ - Optional inputs:
69
+ - `parentBookId`: The ID of the parent notebook. Must start with 'book:'. Omit it to create the notebook at the root level.
70
+ 11. **`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.
71
+ - Required inputs:
72
+ - `_id`: The notebook ID. Must start with 'book:'.
73
+ - Optional inputs:
74
+ - `_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.
75
+ - `name`: The notebook name.
76
+ - `parentBookId`: The ID of the parent notebook. Pass `null` to move the notebook to the root level.
77
+ 12. **`list-tags`**: Retrieve a list of all tags.
78
+ 13. **`read-tag`**: Retrieve a single tag by its ID.
87
79
  - Required inputs:
88
80
  - `tagId`: The tag ID. Must start with 'tag:'.
89
- 12. **`create-tag`**: Create a new tag in the database.
81
+ 14. **`create-tag`**: Create a new tag in the database.
90
82
  - Required inputs:
91
83
  - `name`: The name of the tag.
92
84
  - Optional inputs:
93
85
  - `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.
86
+ 15. **`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
87
  - Required inputs:
96
88
  - `_id`: The tag ID. Must start with 'tag:'.
97
- - `_rev`: The revision ID (CouchDB MVCC-token).
89
+ - Optional inputs:
90
+ - `_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
91
  - `name`: The name of the tag.
92
+ - `color`: The color type of the tag. Omit it to keep the tag's current color.
93
+ 16. **`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.
94
+ - Required inputs: exactly one of
95
+ - `filePath`: Absolute path to a local image file to attach. Preferred — it keeps the image bytes out of the conversation.
96
+ - `data`: Base64-encoded image data, without a `data:` URI prefix.
97
+ - Optional inputs:
98
+ - `name`: The file name. Defaults to the file name of `filePath`, or `image.<ext>` when `data` is given.
99
+ - `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`.
100
+ - `publicIn`: An array of note IDs where the attachment is included. Each must start with 'note:'.
101
+ - Note: Attachments are limited to 10MB.
102
+ 17. **`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.
103
+ - Required inputs:
104
+ - `fileId`: The attachment ID. Must start with 'file:'.
99
105
  - Optional inputs:
100
- - `color`: The color type of the tag. Default: `default`.
106
+ - `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.
107
+ - `includeImage`: Whether to return the image alongside the metadata. Default: `true`. Set to `false` to fetch only the metadata of a large attachment.
101
108
 
102
109
  ## Debugging
103
110
 
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
  });
@@ -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]}` : '';
@@ -272,10 +269,7 @@ server.registerTool('create-note', {
272
269
  .regex(/^(book:|trash$)/)
273
270
  .describe('The notebook ID'),
274
271
  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'),
272
+ body: zod_1.z.string().max(1048576).describe('The content of the note represented with Markdown'),
279
273
  status: zod_1.z
280
274
  .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
281
275
  .optional()
@@ -394,9 +388,7 @@ server.registerTool('patch-note', {
394
388
  isError: true
395
389
  };
396
390
  }
397
- const patched = body.slice(0, firstIndex) +
398
- new_string +
399
- body.slice(firstIndex + old_string.length);
391
+ const patched = body.slice(0, firstIndex) + new_string + body.slice(firstIndex + old_string.length);
400
392
  const res = await (0, api_1.postJSON)('/notes', {
401
393
  ...existingNote,
402
394
  body: patched,
@@ -446,10 +438,7 @@ const TagColors = Object.values(inkdrop_model_1.TAG_COLOR);
446
438
  server.registerTool('create-tag', {
447
439
  description: 'Create a new tag in the database',
448
440
  inputSchema: {
449
- color: zod_1.z
450
- .enum(TagColors)
451
- .default('default')
452
- .describe('The color type of the tag'),
441
+ color: zod_1.z.enum(TagColors).default('default').describe('The color type of the tag'),
453
442
  name: zod_1.z.string().max(64).describe('The name of the tag')
454
443
  }
455
444
  }, async (tagData) => {
@@ -464,7 +453,7 @@ server.registerTool('create-tag', {
464
453
  };
465
454
  });
466
455
  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.',
456
+ 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
457
  inputSchema: {
469
458
  _id: zod_1.z
470
459
  .string()
@@ -474,15 +463,13 @@ server.registerTool('update-tag', {
474
463
  .describe('The unique document ID which should start with `tag:` and the remains are randomly generated string'),
475
464
  _rev: zod_1.z
476
465
  .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')
466
+ .optional()
467
+ .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.'),
468
+ color: zod_1.z.enum(TagColors).optional().describe('The color type of the tag'),
469
+ name: zod_1.z.string().max(64).optional().describe('The name of the tag')
483
470
  }
484
- }, async (tagData) => {
485
- const res = await (0, api_1.postJSON)(`/tags`, tagData);
471
+ }, async ({ _id, ...updateFields }) => {
472
+ const res = await (0, api_1.postJSON)(`/${_id}`, updateFields);
486
473
  return {
487
474
  content: [
488
475
  {
@@ -523,46 +510,240 @@ server.registerTool('read-book', {
523
510
  ]
524
511
  };
525
512
  });
526
- server.registerPrompt('inkdrop-prompt', { description: 'Instructions for using the Inkdrop MCP server effectively' }, () => ({
527
- messages: [
528
- {
529
- role: 'assistant',
530
- content: {
513
+ server.registerTool('create-book', {
514
+ 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.',
515
+ inputSchema: {
516
+ name: zod_1.z.string().min(1).max(64).describe('The notebook name'),
517
+ parentBookId: zod_1.z
518
+ .string()
519
+ .min(6)
520
+ .max(128)
521
+ .regex(/^book:/)
522
+ .optional()
523
+ .describe('The ID of the parent notebook. Omit it to create the notebook at the root level.')
524
+ }
525
+ }, async (bookData) => {
526
+ const res = await (0, api_1.postJSON)(`/books`, bookData);
527
+ return {
528
+ content: [
529
+ {
531
530
  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
- `
531
+ text: JSON.stringify(res, null, 2)
532
+ }
533
+ ]
534
+ };
535
+ });
536
+ server.registerTool('update-book', {
537
+ 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.',
538
+ inputSchema: {
539
+ _id: zod_1.z
540
+ .string()
541
+ .min(6)
542
+ .max(128)
543
+ .regex(/^book:/)
544
+ .describe('The unique document ID which should start with `book:` and the remains are randomly generated string'),
545
+ _rev: zod_1.z
546
+ .string()
547
+ .optional()
548
+ .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.'),
549
+ name: zod_1.z.string().min(1).max(64).optional().describe('The notebook name'),
550
+ parentBookId: zod_1.z
551
+ .string()
552
+ .min(6)
553
+ .max(128)
554
+ .regex(/^book:/)
555
+ .nullable()
556
+ .optional()
557
+ .describe('The ID of the parent notebook. Pass `null` to move the notebook to the root level.')
558
+ }
559
+ }, async ({ _id, ...updateFields }) => {
560
+ const res = await (0, api_1.postJSON)(`/${_id}`, {
561
+ ...updateFields,
562
+ updatedAt: +new Date()
563
+ });
564
+ return {
565
+ content: [
566
+ {
567
+ type: 'text',
568
+ text: JSON.stringify(res, null, 2)
569
+ }
570
+ ]
571
+ };
572
+ });
573
+ const ImageFileTypes = [...inkdrop_model_1.supportedImageFileTypes];
574
+ server.registerTool('create-file', {
575
+ description: 'Create a new attachment file in the database from a local image file or from base64 image data. ' +
576
+ 'Returns the Markdown to embed the attachment in a note body. ' +
577
+ 'Prefer `filePath` over `data`: it keeps the image bytes out of the conversation.',
578
+ inputSchema: {
579
+ filePath: zod_1.z
580
+ .string()
581
+ .optional()
582
+ .describe('Absolute path to a local image file to attach. Either this or `data` must be given.'),
583
+ data: zod_1.z
584
+ .string()
585
+ .optional()
586
+ .describe('Base64-encoded image data, without a `data:` URI prefix. Use `filePath` instead whenever the image is already on disk.'),
587
+ name: zod_1.z
588
+ .string()
589
+ .min(1)
590
+ .max(128)
591
+ .optional()
592
+ .describe('The file name. Defaults to the file name of `filePath`, or `image.<ext>` when `data` is given.'),
593
+ contentType: zod_1.z
594
+ .enum(ImageFileTypes)
595
+ .optional()
596
+ .describe('The MIME type of the image. Inferred from the `filePath` extension when omitted, so it is required with `data`.')
597
+ }
598
+ }, async ({ filePath, data, name, contentType }) => {
599
+ if ((filePath === undefined) === (data === undefined)) {
600
+ return {
601
+ content: [
602
+ {
603
+ type: 'text',
604
+ text: 'Failed to create the attachment: provide exactly one of `filePath` or `data`.'
605
+ }
606
+ ],
607
+ isError: true
608
+ };
609
+ }
610
+ let buffer;
611
+ if (filePath !== undefined) {
612
+ try {
613
+ buffer = await (0, promises_1.readFile)(filePath);
614
+ }
615
+ catch (e) {
616
+ return {
617
+ content: [
618
+ {
619
+ type: 'text',
620
+ text: `Failed to read the file at ${filePath}: ${e.message}`
621
+ }
622
+ ],
623
+ isError: true
624
+ };
625
+ }
626
+ contentType ??= (0, utils_1.inferImageContentType)(filePath);
627
+ name ??= (0, node_path_1.basename)(filePath);
628
+ }
629
+ else {
630
+ buffer = Buffer.from(data, 'base64');
631
+ }
632
+ if (!contentType) {
633
+ return {
634
+ content: [
635
+ {
636
+ type: 'text',
637
+ 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(', ')}.`
638
+ }
639
+ ],
640
+ isError: true
641
+ };
642
+ }
643
+ const base64 = buffer.toString('base64');
644
+ const contentLength = Math.floor((base64.length * 3) / 4);
645
+ if (contentLength > inkdrop_model_1.maxAttachmentFileSize) {
646
+ return {
647
+ content: [
648
+ {
649
+ type: 'text',
650
+ text: `Failed to create the attachment: the file is ${contentLength} bytes, over the ${inkdrop_model_1.maxAttachmentFileSize} byte limit.`
651
+ }
652
+ ],
653
+ isError: true
654
+ };
655
+ }
656
+ const res = await (0, api_1.postJSON)('/files', {
657
+ name: name ?? `image.${contentType.replace(/^image\//, '')}`,
658
+ contentType,
659
+ contentLength,
660
+ publicIn: [],
661
+ md5digest: (0, node_crypto_1.createHash)('md5').update(buffer).digest('hex'),
662
+ _attachments: {
663
+ index: {
664
+ content_type: contentType,
665
+ data: base64
666
+ }
667
+ }
668
+ });
669
+ return {
670
+ content: [
671
+ {
672
+ type: 'text',
673
+ text: JSON.stringify(res, null, 2)
674
+ },
675
+ {
676
+ type: 'text',
677
+ text: `Markdown to embed this attachment in a note body:\n\n![${name}](${(0, utils_1.getFileUri)(res.id)})`
562
678
  }
679
+ ]
680
+ };
681
+ });
682
+ server.registerTool('read-file', {
683
+ description: 'Retrieve an attachment file by its ID. Returns the file metadata, and the image itself when it is a PNG, JPEG or GIF. ' +
684
+ 'Pass `outputPath` to write the attachment to disk instead — required to get at SVG, HEIC and HEIF attachments, which cannot be displayed inline.',
685
+ inputSchema: {
686
+ fileId: zod_1.z
687
+ .string()
688
+ .describe('ID of the attachment to retrieve. It can be found as `_id` in the file docs. It always starts with \`file:\`.'),
689
+ outputPath: zod_1.z
690
+ .string()
691
+ .optional()
692
+ .describe('Absolute path to write the attachment to. When given, the file is saved there and its bytes are not returned inline.'),
693
+ includeImage: zod_1.z
694
+ .boolean()
695
+ .optional()
696
+ .default(true)
697
+ .describe('Whether to return the image itself alongside the metadata. Set to false to fetch only the metadata of a large attachment.')
698
+ }
699
+ }, async ({ fileId, outputPath, includeImage }) => {
700
+ if (!fileId.startsWith('file:'))
701
+ fileId = `file:${fileId}`;
702
+ const needsData = includeImage || outputPath !== undefined;
703
+ const file = await (0, api_1.fetchJSON)(`/${fileId}`, {
704
+ attachments: needsData ? true : undefined
705
+ });
706
+ const { _attachments, ...metadata } = file;
707
+ const base64 = typeof _attachments?.index?.data === 'string' ? _attachments.index.data : undefined;
708
+ const attachmentBlock = async () => {
709
+ if (!needsData)
710
+ return [];
711
+ if (!base64) {
712
+ return [
713
+ {
714
+ type: 'text',
715
+ text: 'The attachment data could not be read from the document.'
716
+ }
717
+ ];
718
+ }
719
+ if (outputPath !== undefined) {
720
+ await (0, promises_1.writeFile)(outputPath, Buffer.from(base64, 'base64'));
721
+ return [{ type: 'text', text: `Attachment written to ${outputPath}` }];
722
+ }
723
+ if (!(0, utils_1.isViewableImageType)(file.contentType)) {
724
+ return [
725
+ {
726
+ type: 'text',
727
+ text: `The attachment is a ${file.contentType} file, which cannot be displayed inline. Pass \`outputPath\` to write it to disk.`
728
+ }
729
+ ];
563
730
  }
564
- ]
565
- }));
731
+ return [
732
+ {
733
+ type: 'image',
734
+ data: base64,
735
+ // `image/jpg` is not a real MIME type; the image block expects `image/jpeg`.
736
+ mimeType: file.contentType === 'image/jpg' ? 'image/jpeg' : file.contentType
737
+ }
738
+ ];
739
+ };
740
+ return {
741
+ content: [
742
+ { type: 'text', text: JSON.stringify(metadata, null, 2) },
743
+ ...(await attachmentBlock())
744
+ ]
745
+ };
746
+ });
566
747
  async function runServer() {
567
748
  const transport = new stdio_js_1.StdioServerTransport();
568
749
  await server.connect(transport);