@inkdropapp/mcp-server 1.8.0 → 1.10.0-beta.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.
Files changed (48) hide show
  1. package/.github/workflows/actions.lock +10 -0
  2. package/.github/workflows/ci.yml +65 -0
  3. package/.github/workflows/publish.yml +10 -1
  4. package/.oxfmtrc.json +2 -1
  5. package/README.md +16 -6
  6. package/dist/client/agent-identity.js +45 -0
  7. package/dist/client/agent-session.js +66 -0
  8. package/dist/client/local-server.js +64 -0
  9. package/dist/features/files/image-type.js +31 -0
  10. package/dist/features/files/tools.js +191 -0
  11. package/dist/features/notebooks/tools.js +95 -0
  12. package/dist/features/notes/note-anchor.js +58 -0
  13. package/dist/features/notes/note-schemas.js +38 -0
  14. package/dist/features/notes/note-update.js +16 -0
  15. package/dist/features/notes/resource.js +26 -0
  16. package/dist/features/notes/text-edits.js +36 -0
  17. package/dist/features/notes/tools.js +405 -0
  18. package/dist/features/tags/tools.js +82 -0
  19. package/dist/index.js +19 -826
  20. package/dist/utils/document-fields.js +18 -0
  21. package/mise.toml +5 -0
  22. package/oxlint.config.ts +50 -0
  23. package/package.json +22 -14
  24. package/pnpm-workspace.yaml +6 -0
  25. package/src/client/agent-identity.ts +70 -0
  26. package/src/client/agent-session.ts +75 -0
  27. package/src/client/local-server.ts +73 -0
  28. package/src/features/files/image-type.ts +35 -0
  29. package/src/features/files/tools.ts +230 -0
  30. package/src/features/notebooks/tools.ts +133 -0
  31. package/src/features/notes/note-anchor.ts +85 -0
  32. package/src/features/notes/note-schemas.ts +60 -0
  33. package/src/features/notes/note-update.ts +27 -0
  34. package/src/features/notes/resource.ts +34 -0
  35. package/src/features/notes/text-edits.ts +48 -0
  36. package/src/features/notes/tools.ts +499 -0
  37. package/src/features/tags/tools.ts +109 -0
  38. package/src/index.ts +17 -1049
  39. package/src/utils/document-fields.ts +21 -0
  40. package/tests/client/agent-identity.test.ts +98 -0
  41. package/tests/features/notes/note-anchor.test.ts +125 -0
  42. package/tests/features/notes/note-schemas.test.ts +27 -0
  43. package/tests/utils/document-fields.test.ts +41 -0
  44. package/tsconfig.json +1 -1
  45. package/dist/api.js +0 -47
  46. package/dist/utils.js +0 -100
  47. package/src/api.ts +0 -45
  48. package/src/utils.ts +0 -112
package/dist/index.js CHANGED
@@ -1,834 +1,27 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
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");
7
- const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
8
- const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
9
- const inkdrop_model_1 = require("inkdrop-model");
10
- const zod_1 = require("zod");
11
- const api_1 = require("./api");
12
- const utils_1 = require("./utils");
13
- const server = new mcp_js_1.McpServer({
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { trackAgentSession } from './client/agent-session.js';
5
+ import { registerFileTools } from './features/files/tools.js';
6
+ import { registerNotebookTools } from './features/notebooks/tools.js';
7
+ import { registerNoteResource } from './features/notes/resource.js';
8
+ import { registerNoteTools } from './features/notes/tools.js';
9
+ import { registerTagTools } from './features/tags/tools.js';
10
+ const server = new McpServer({
14
11
  name: 'Inkdrop',
15
12
  version: '1.3.0'
16
13
  });
17
- server.registerResource('note', new mcp_js_1.ResourceTemplate('inkdrop://note/{noteId}', { list: undefined }), {
18
- description: 'A note data',
19
- mimeType: 'application/json'
20
- }, async (uri, { noteId }) => {
21
- const id = Array.isArray(noteId) ? noteId[0] : noteId;
22
- const normalizedId = id.startsWith('note:') ? id : `note:${id}`;
23
- const note = await (0, api_1.fetchJSON)(`/${normalizedId}`, {});
24
- return {
25
- contents: [
26
- {
27
- uri: uri.href,
28
- text: JSON.stringify(note, null, 2),
29
- mimeType: 'application/json'
30
- }
31
- ]
32
- };
33
- });
34
- server.registerTool('read-note', {
35
- description: 'Retrieve the complete contents of the note by its ID from the database. ' +
36
- 'A note created from a template has a `sourceTemplateId`; when present, the response ' +
37
- 'includes a resource link to that source template, whose body holds the fill-out ' +
38
- 'instructions and examples. Read the template (or pass `includeTemplate: true`) before ' +
39
- 'completing the note.',
40
- inputSchema: {
41
- noteId: zod_1.z
42
- .string()
43
- .describe('ID of the note to retrieve. It can be found as `_id` in the note docs. It always starts with \`note:\`.'),
44
- includeTemplate: zod_1.z
45
- .boolean()
46
- .optional()
47
- .default(false)
48
- .describe('When true and the note has a `sourceTemplateId`, also fetch that template and embed its body (the fill-out instructions and examples) as an extra text block, so you get the note and its template in one call.')
49
- }
50
- }, async ({ noteId, includeTemplate }) => {
51
- if (!noteId.startsWith('note:'))
52
- noteId = `note:${noteId}`;
53
- const note = await (0, api_1.fetchJSON)(`/${noteId}`, {});
54
- let templateBlockText = null;
55
- if (includeTemplate && note.sourceTemplateId) {
56
- try {
57
- const template = await (0, api_1.fetchJSON)(`/${note.sourceTemplateId}`, {});
58
- templateBlockText = `# Source template: ${template.title}\n\n${template.body}`;
59
- }
60
- catch {
61
- // Template unavailable (e.g. deleted → 404). Skip the embed; the note read still succeeds.
62
- }
63
- }
64
- return {
65
- content: [
66
- {
67
- type: 'text',
68
- text: JSON.stringify(note, null, 2)
69
- },
70
- ...(note.sourceTemplateId
71
- ? [
72
- {
73
- type: 'resource_link',
74
- uri: (0, utils_1.getNoteUri)(note.sourceTemplateId),
75
- name: 'Source template',
76
- mimeType: 'application/json',
77
- description: 'The template this note was created from. Read it to get the fill-out instructions and examples before completing this note.'
78
- }
79
- ]
80
- : []),
81
- ...(templateBlockText ? [{ type: 'text', text: templateBlockText }] : [])
82
- ]
83
- };
84
- });
85
- server.registerTool('read-backlinks', {
86
- description: `Retrieve backlinks for a note — the notes that link to it.
87
- Each result is returned as a resource link (\`inkdrop://note/<id>\`) pointing to the referring note.
88
- Backlinks are found by searching all note bodies for the note's link URI.`,
89
- inputSchema: {
90
- noteId: zod_1.z
91
- .string()
92
- .describe('ID of the note to find backlinks for. It can be found as `_id` in the note docs. It always starts with \`note:\`.')
93
- }
94
- }, async ({ noteId }) => {
95
- if (!noteId.startsWith('note:'))
96
- noteId = `note:${noteId}`;
97
- const noteLink = (0, utils_1.getNoteUri)(noteId);
98
- const backlinks = await (0, api_1.fetchJSON)('/notes', {
99
- keyword: noteLink,
100
- limit: 100
101
- });
102
- if (backlinks.length === 0) {
103
- return {
104
- content: [
105
- {
106
- type: 'text',
107
- text: `No backlinks found for ${noteLink}.`
108
- }
109
- ]
110
- };
111
- }
112
- return {
113
- content: backlinks.map(note => ({
114
- type: 'resource_link',
115
- uri: (0, utils_1.getNoteUri)(note._id),
116
- name: note.title || 'Untitled note',
117
- mimeType: 'application/json'
118
- }))
119
- };
120
- });
121
- server.registerTool('search-notes', {
122
- description: `List all notes that contain a given keyword.
123
- The result does not include entire note bodies as they are truncated in 200 characters.
124
- You have to retrieve the full note content by calling \`read-note\`.
125
- Here are tips to specify keywords effectively:
126
-
127
- ## Use special qualifiers to narrow down results
128
-
129
- You can use special qualifiers to get more accurate results. See the qualifiers and their usage examples:
130
-
131
- - **book**
132
- \`book:Blog\`: Searches for notes in the 'Blog' notebook.
133
- \`book:"Desktop App"\`: Searches for notes in the 'Desktop App' notebook.
134
- \`book:kGlLniaV\`: Searches for notes in the notebook with the ID 'book:kGlLniaV'.
135
- - **tag**
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
- - **status**
139
- \`status:onHold\`: Searches for all notes with the 'On hold' status. Read more about [statuses](/reference/note-statuses).
140
- - **title**
141
- \`title:"JavaScript setTimeout"\`: Searches for the note with the specified title.
142
- - **body**
143
- \`body:KEYWORD\`: Searches for a specific word in all notes. Equivalent to a [global search](#search-for-notes-across-all-notebooks).
144
-
145
- ### Combine qualifiers
146
-
147
- You can combine the filter qualifiers to refine data even more.
148
-
149
- **Find notes that contain the word 'Hello' and have the 'Issue' tag.**
150
-
151
- \`\`\`text
152
- Hello tag:Issue
153
- \`\`\`
154
-
155
- **Find notes that contain the word 'Typescript,' have the 'Contribution' tag, and the 'Completed' status**
156
-
157
- \`\`\`text
158
- Typescript tag:Contribution status:Completed
159
- \`\`\`
160
-
161
- ## Search for text with spaces
162
-
163
- To find the text that includes spaces, put the text into the double quotation marks ("):
164
-
165
- \`\`\`text
166
- "database associations"
167
- \`\`\`
168
-
169
- ## Exclude text from search
170
-
171
- To exclude text from the search results or ignore a specific qualifier, put the minus sign (-) before it. You can also combine the exclusions. See the examples:
172
-
173
- - \`-book:Backend "closure functions"\`: Ignores the 'Backend' notebook while searching for the 'closure functions' phrase.
174
- - \`-tag:JavaScript\`: Ignores all notes having the 'JavaScript' tag.
175
- - \`-book:Typescript tag:work "Data types"\`: Ignores the 'Typescript' notebook and the 'work' tag while searching for the 'Data types' phrase.
176
- - \`-status:dropped title:"Sprint 10.0" debounce\`: Ignores notes with the 'Dropped' status while searching for the 'debounce' word in the note with the 'Sprint 10.0' title.
177
- - \`-"Phrase to ignore" "in the rest of a sentence"\`: Ignores the 'Phrase to ignore' part while searching for 'in the rest of a sentence'.
178
-
179
- Note that you can't specify excluding modifiers only without including conditions.
180
-
181
- **WARNING**: Make sure to enter a text to search for after the exclusion modifier.
182
-
183
- - ✅ Will work
184
- \`-book:Backend "closure functions"\`
185
-
186
- - ⛔️ Won't work
187
- \`-book:Backend\`. There's no query. Inkdrop doesn't understand what to search for.
188
- `,
189
- inputSchema: {
190
- keyword: zod_1.z.string().describe(`Keyword to search for.`)
191
- }
192
- }, async ({ keyword }) => {
193
- const notes = await (0, api_1.fetchJSON)('/notes', { keyword, limit: 10 });
194
- const summaries = notes.map(note => {
195
- return {
196
- ...note,
197
- body: note.body.substring(0, 200)
198
- };
199
- });
200
- return {
201
- content: [
202
- {
203
- type: 'text',
204
- text: JSON.stringify(summaries, null, 2)
205
- }
206
- ]
207
- };
208
- });
209
- server.registerTool('list-notes', {
210
- description: `List all notes with specified conditions.
211
- The result does not include entire note bodies as they are truncated in 200 characters.
212
- You have to retrieve the full note content by calling \`read-note\`.
213
- `,
214
- inputSchema: {
215
- bookId: zod_1.z
216
- .string()
217
- .optional()
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`),
219
- tagIds: zod_1.z
220
- .array(zod_1.z.string())
221
- .optional()
222
- .default([])
223
- .describe(`An array of tag IDs to filter. It always starts with 'tag:'. You can retrieve a list of available tags from \`list-tags\`.`),
224
- keyword: zod_1.z.string().optional().describe(`Keyword to filter notes`),
225
- sort: zod_1.z
226
- .enum(['updatedAt', 'createdAt', 'title'])
227
- .optional()
228
- .default('updatedAt')
229
- .describe(`Sort the documents by the specified field`),
230
- descending: zod_1.z
231
- .boolean()
232
- .optional()
233
- .default(true)
234
- .describe(`Reverse the order of the output documents`),
235
- limit: zod_1.z.number().optional().default(100).describe(`Limit the number of results returned`)
236
- }
237
- }, async ({ bookId, tagIds, keyword, sort, descending, limit }) => {
238
- const bookFilter = bookId ?? '';
239
- const tagFilter = tagIds?.join(' ') ?? '';
240
- keyword = `${bookFilter} ${tagFilter} ${keyword || ''}`.trim();
241
- const notes = await (0, api_1.fetchJSON)('/notes', {
242
- keyword,
243
- sort,
244
- descending,
245
- limit
246
- });
247
- const summaries = notes.map(note => {
248
- return {
249
- ...note,
250
- body: note.body.substring(0, 200)
251
- };
252
- });
253
- return {
254
- content: [
255
- {
256
- type: 'text',
257
- text: JSON.stringify(summaries, null, 2)
258
- }
259
- ]
260
- };
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
- });
291
- server.registerTool('create-note', {
292
- description: 'Create a new note in the database',
293
- inputSchema: {
294
- bookId: zod_1.z
295
- .string()
296
- .min(5)
297
- .max(128)
298
- .regex(/^(book:|trash$|template$)/)
299
- .describe('The notebook ID. Specify `template` to create a custom note template'),
300
- title: zod_1.z.string().max(128).describe('The note title'),
301
- body: zod_1.z.string().max(1048576).describe('The content of the note represented with Markdown'),
302
- status: zod_1.z
303
- .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
304
- .optional()
305
- .describe('The status of the note'),
306
- tags: zod_1.z
307
- .array(zod_1.z.string().startsWith('tag:'))
308
- .optional()
309
- .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.')
310
- }
311
- }, async (noteData) => {
312
- const res = await (0, api_1.postJSON)(`/notes`, noteData);
313
- return {
314
- content: [
315
- {
316
- type: 'text',
317
- text: JSON.stringify(res, null, 2)
318
- }
319
- ]
320
- };
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
- }
337
- server.registerTool('update-note', {
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.',
339
- inputSchema: {
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.')
387
- }
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
- });
397
- return {
398
- content: [
399
- {
400
- type: 'text',
401
- text: JSON.stringify(results, null, 2)
402
- }
403
- ],
404
- isError: settledUpdates.some(settledUpdate => settledUpdate.status === 'rejected')
405
- };
406
- });
407
- server.registerTool('patch-note', {
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.',
409
- inputSchema: {
410
- _id: zod_1.z
411
- .string()
412
- .min(6)
413
- .max(128)
414
- .regex(/^note:/)
415
- .describe('The unique document ID which should start with `note:` and the remains are randomly generated string'),
416
- _rev: zod_1.z
417
- .string()
418
- .describe('This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).'),
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
- }))
429
- .min(1)
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.')
443
- }
444
- }, async ({ _id, _rev, edits, createdAt, updatedAt }) => {
445
- const existingNote = await (0, api_1.fetchJSON)(`/${_id}`, { rev: _rev });
446
- const patchResult = (0, utils_1.applyTextEdits)(existingNote.body, edits);
447
- if (!patchResult.ok) {
448
- return {
449
- content: [
450
- {
451
- type: 'text',
452
- text: `Failed to patch: ${patchResult.error} No edits were saved.`
453
- }
454
- ],
455
- isError: true
456
- };
457
- }
458
- const res = await (0, api_1.postJSON)('/notes', {
459
- ...existingNote,
460
- body: patchResult.text,
461
- createdAt: createdAt ?? existingNote.createdAt,
462
- updatedAt: updatedAt ?? +new Date()
463
- });
464
- return {
465
- content: [
466
- {
467
- type: 'text',
468
- text: JSON.stringify(res, null, 2)
469
- }
470
- ]
471
- };
472
- });
473
- server.registerTool('list-tags', { description: 'Retrieve a list of all tags' }, async () => {
474
- const tags = await (0, api_1.fetchJSON)('/tags');
475
- return {
476
- content: [
477
- {
478
- type: 'text',
479
- text: JSON.stringify(tags, null, 2)
480
- }
481
- ]
482
- };
483
- });
484
- server.registerTool('read-tag', {
485
- description: 'Retrieve a single tag',
486
- inputSchema: {
487
- tagId: zod_1.z
488
- .string()
489
- .describe('ID of the tag to retrieve. It can be found as `_id` in the tag docs. It always starts with \`tag:\`.')
490
- }
491
- }, async ({ tagId }) => {
492
- if (!tagId.startsWith('tag:'))
493
- tagId = `tag:${tagId}`;
494
- const tag = await (0, api_1.fetchJSON)(`/${tagId}`, {});
495
- return {
496
- content: [
497
- {
498
- type: 'text',
499
- text: JSON.stringify(tag, null, 2)
500
- }
501
- ]
502
- };
503
- });
504
- const TagColors = Object.values(inkdrop_model_1.TAG_COLOR);
505
- server.registerTool('create-tag', {
506
- description: 'Create a new tag in the database',
507
- inputSchema: {
508
- color: zod_1.z.enum(TagColors).default('default').describe('The color type of the tag'),
509
- name: zod_1.z.string().max(64).describe('The name of the tag')
510
- }
511
- }, async (tagData) => {
512
- const res = await (0, api_1.postJSON)(`/tags`, tagData);
513
- return {
514
- content: [
515
- {
516
- type: 'text',
517
- text: JSON.stringify(res, null, 2)
518
- }
519
- ]
520
- };
521
- });
522
- server.registerTool('update-tag', {
523
- 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.',
524
- inputSchema: {
525
- _id: zod_1.z
526
- .string()
527
- .min(6)
528
- .max(128)
529
- .regex(/^tag:/)
530
- .describe('The unique document ID which should start with `tag:` and the remains are randomly generated string'),
531
- _rev: zod_1.z
532
- .string()
533
- .optional()
534
- .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.'),
535
- color: zod_1.z.enum(TagColors).optional().describe('The color type of the tag'),
536
- name: zod_1.z.string().max(64).optional().describe('The name of the tag')
537
- }
538
- }, async ({ _id, ...updateFields }) => {
539
- const res = await (0, api_1.postJSON)(`/${_id}`, updateFields);
540
- return {
541
- content: [
542
- {
543
- type: 'text',
544
- text: JSON.stringify(res, null, 2)
545
- }
546
- ]
547
- };
548
- });
549
- server.registerTool('list-notebooks', { description: 'Retrieve a list of all notebooks' }, async () => {
550
- const books = await (0, api_1.fetchJSON)('/books');
551
- return {
552
- content: [
553
- {
554
- type: 'text',
555
- text: JSON.stringify(books, null, 2)
556
- }
557
- ]
558
- };
559
- });
560
- server.registerTool('read-book', {
561
- description: 'Retrieve a single book',
562
- inputSchema: {
563
- bookId: zod_1.z
564
- .string()
565
- .describe('ID of the book to retrieve. It can be found as `_id` in the book docs. It always starts with \`book:\`.')
566
- }
567
- }, async ({ bookId }) => {
568
- if (!bookId.startsWith('book:'))
569
- bookId = `book:${bookId}`;
570
- const book = await (0, api_1.fetchJSON)(`/${bookId}`, {});
571
- return {
572
- content: [
573
- {
574
- type: 'text',
575
- text: JSON.stringify(book, null, 2)
576
- }
577
- ]
578
- };
579
- });
580
- server.registerTool('create-book', {
581
- 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.',
582
- inputSchema: {
583
- name: zod_1.z.string().min(1).max(64).describe('The notebook name'),
584
- parentBookId: zod_1.z
585
- .string()
586
- .min(6)
587
- .max(128)
588
- .regex(/^book:/)
589
- .optional()
590
- .describe('The ID of the parent notebook. Omit it to create the notebook at the root level.')
591
- }
592
- }, async (bookData) => {
593
- const res = await (0, api_1.postJSON)(`/books`, bookData);
594
- return {
595
- content: [
596
- {
597
- type: 'text',
598
- text: JSON.stringify(res, null, 2)
599
- }
600
- ]
601
- };
602
- });
603
- server.registerTool('update-book', {
604
- 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.',
605
- inputSchema: {
606
- _id: zod_1.z
607
- .string()
608
- .min(6)
609
- .max(128)
610
- .regex(/^book:/)
611
- .describe('The unique document ID which should start with `book:` and the remains are randomly generated string'),
612
- _rev: zod_1.z
613
- .string()
614
- .optional()
615
- .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.'),
616
- name: zod_1.z.string().min(1).max(64).optional().describe('The notebook name'),
617
- parentBookId: zod_1.z
618
- .string()
619
- .min(6)
620
- .max(128)
621
- .regex(/^book:/)
622
- .nullable()
623
- .optional()
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.')
637
- }
638
- }, async ({ _id, ...updateFields }) => {
639
- const res = await (0, api_1.postJSON)(`/${_id}`, {
640
- ...updateFields,
641
- updatedAt: updateFields.updatedAt ?? +new Date()
642
- });
643
- return {
644
- content: [
645
- {
646
- type: 'text',
647
- text: JSON.stringify(res, null, 2)
648
- }
649
- ]
650
- };
651
- });
652
- const ImageFileTypes = [...inkdrop_model_1.supportedImageFileTypes];
653
- server.registerTool('create-file', {
654
- description: 'Create a new attachment file in the database from a local image file or from base64 image data. ' +
655
- 'Returns the Markdown to embed the attachment in a note body. ' +
656
- 'Prefer `filePath` over `data`: it keeps the image bytes out of the conversation.',
657
- inputSchema: {
658
- filePath: zod_1.z
659
- .string()
660
- .optional()
661
- .describe('Absolute path to a local image file to attach. Either this or `data` must be given.'),
662
- data: zod_1.z
663
- .string()
664
- .optional()
665
- .describe('Base64-encoded image data, without a `data:` URI prefix. Use `filePath` instead whenever the image is already on disk.'),
666
- name: zod_1.z
667
- .string()
668
- .min(1)
669
- .max(128)
670
- .optional()
671
- .describe('The file name. Defaults to the file name of `filePath`, or `image.<ext>` when `data` is given.'),
672
- contentType: zod_1.z
673
- .enum(ImageFileTypes)
674
- .optional()
675
- .describe('The MIME type of the image. Inferred from the `filePath` extension when omitted, so it is required with `data`.')
676
- }
677
- }, async ({ filePath, data, name, contentType }) => {
678
- if ((filePath === undefined) === (data === undefined)) {
679
- return {
680
- content: [
681
- {
682
- type: 'text',
683
- text: 'Failed to create the attachment: provide exactly one of `filePath` or `data`.'
684
- }
685
- ],
686
- isError: true
687
- };
688
- }
689
- let buffer;
690
- if (filePath !== undefined) {
691
- try {
692
- buffer = await (0, promises_1.readFile)(filePath);
693
- }
694
- catch (e) {
695
- return {
696
- content: [
697
- {
698
- type: 'text',
699
- text: `Failed to read the file at ${filePath}: ${e.message}`
700
- }
701
- ],
702
- isError: true
703
- };
704
- }
705
- contentType ??= (0, utils_1.inferImageContentType)(filePath);
706
- name ??= (0, node_path_1.basename)(filePath);
707
- }
708
- else {
709
- buffer = Buffer.from(data, 'base64');
710
- }
711
- if (!contentType) {
712
- return {
713
- content: [
714
- {
715
- type: 'text',
716
- 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(', ')}.`
717
- }
718
- ],
719
- isError: true
720
- };
721
- }
722
- const base64 = buffer.toString('base64');
723
- const contentLength = Math.floor((base64.length * 3) / 4);
724
- if (contentLength > inkdrop_model_1.maxAttachmentFileSize) {
725
- return {
726
- content: [
727
- {
728
- type: 'text',
729
- text: `Failed to create the attachment: the file is ${contentLength} bytes, over the ${inkdrop_model_1.maxAttachmentFileSize} byte limit.`
730
- }
731
- ],
732
- isError: true
733
- };
734
- }
735
- const res = await (0, api_1.postJSON)('/files', {
736
- name: name ?? `image.${contentType.replace(/^image\//, '')}`,
737
- contentType,
738
- contentLength,
739
- publicIn: [],
740
- md5digest: (0, node_crypto_1.createHash)('md5').update(buffer).digest('hex'),
741
- _attachments: {
742
- index: {
743
- content_type: contentType,
744
- data: base64
745
- }
746
- }
747
- });
748
- return {
749
- content: [
750
- {
751
- type: 'text',
752
- text: JSON.stringify(res, null, 2)
753
- },
754
- {
755
- type: 'text',
756
- text: `Markdown to embed this attachment in a note body:\n\n![${name}](${(0, utils_1.getFileUri)(res.id)})`
757
- }
758
- ]
759
- };
760
- });
761
- server.registerTool('read-file', {
762
- description: 'Retrieve an attachment file by its ID. Returns the file metadata, and the image itself when it is a PNG, JPEG or GIF. ' +
763
- 'Pass `outputPath` to write the attachment to disk instead — required to get at SVG, HEIC and HEIF attachments, which cannot be displayed inline.',
764
- inputSchema: {
765
- fileId: zod_1.z
766
- .string()
767
- .describe('ID of the attachment to retrieve. It can be found as `_id` in the file docs. It always starts with \`file:\`.'),
768
- outputPath: zod_1.z
769
- .string()
770
- .optional()
771
- .describe('Absolute path to write the attachment to. When given, the file is saved there and its bytes are not returned inline.'),
772
- includeImage: zod_1.z
773
- .boolean()
774
- .optional()
775
- .default(true)
776
- .describe('Whether to return the image itself alongside the metadata. Set to false to fetch only the metadata of a large attachment.')
777
- }
778
- }, async ({ fileId, outputPath, includeImage }) => {
779
- if (!fileId.startsWith('file:'))
780
- fileId = `file:${fileId}`;
781
- const needsData = includeImage || outputPath !== undefined;
782
- const file = await (0, api_1.fetchJSON)(`/${fileId}`, {
783
- attachments: needsData ? true : undefined
784
- });
785
- const { _attachments, ...metadata } = file;
786
- const base64 = typeof _attachments?.index?.data === 'string' ? _attachments.index.data : undefined;
787
- const attachmentBlock = async () => {
788
- if (!needsData)
789
- return [];
790
- if (!base64) {
791
- return [
792
- {
793
- type: 'text',
794
- text: 'The attachment data could not be read from the document.'
795
- }
796
- ];
797
- }
798
- if (outputPath !== undefined) {
799
- await (0, promises_1.writeFile)(outputPath, Buffer.from(base64, 'base64'));
800
- return [{ type: 'text', text: `Attachment written to ${outputPath}` }];
801
- }
802
- if (!(0, utils_1.isViewableImageType)(file.contentType)) {
803
- return [
804
- {
805
- type: 'text',
806
- text: `The attachment is a ${file.contentType} file, which cannot be displayed inline. Pass \`outputPath\` to write it to disk.`
807
- }
808
- ];
809
- }
810
- return [
811
- {
812
- type: 'image',
813
- data: base64,
814
- // `image/jpg` is not a real MIME type; the image block expects `image/jpeg`.
815
- mimeType: file.contentType === 'image/jpg' ? 'image/jpeg' : file.contentType
816
- }
817
- ];
818
- };
819
- return {
820
- content: [
821
- { type: 'text', text: JSON.stringify(metadata, null, 2) },
822
- ...(await attachmentBlock())
823
- ]
824
- };
825
- });
826
- async function runServer() {
827
- const transport = new stdio_js_1.StdioServerTransport();
828
- await server.connect(transport);
14
+ registerNoteResource(server);
15
+ registerNoteTools(server);
16
+ registerTagTools(server);
17
+ registerNotebookTools(server);
18
+ registerFileTools(server);
19
+ trackAgentSession(server.server, process.stdin);
20
+ try {
21
+ await server.connect(new StdioServerTransport());
829
22
  console.error('Secure MCP Inkdrop Server running on stdio');
830
23
  }
831
- runServer().catch(error => {
24
+ catch (error) {
832
25
  console.error('Fatal error running server:', error);
833
26
  process.exit(1);
834
- });
27
+ }