@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
@@ -0,0 +1,95 @@
1
+ import { BOOK_DOCID_PREFIX } from 'inkdrop-model';
2
+ import { z } from 'zod';
3
+ import { fetchJSON, postJSON } from '../../client/local-server.js';
4
+ import { documentIdSchema, revisionSchema, timestampSchema } from '../../utils/document-fields.js';
5
+ /**
6
+ * Registers the tools that read, create and update notebooks.
7
+ *
8
+ * @param server - The MCP server to register on
9
+ */
10
+ export function registerNotebookTools(server) {
11
+ server.registerTool('list-notebooks', { description: 'Retrieve a list of all notebooks' }, async () => {
12
+ const books = await fetchJSON('/books');
13
+ return {
14
+ content: [
15
+ {
16
+ type: 'text',
17
+ text: JSON.stringify(books, null, 2)
18
+ }
19
+ ]
20
+ };
21
+ });
22
+ server.registerTool('read-book', {
23
+ description: 'Retrieve a single book',
24
+ inputSchema: {
25
+ bookId: z
26
+ .string()
27
+ .describe('ID of the book to retrieve. It can be found as `_id` in the book docs. It always starts with `book:`.')
28
+ }
29
+ }, async ({ bookId }) => {
30
+ if (!bookId.startsWith('book:')) {
31
+ bookId = `book:${bookId}`;
32
+ }
33
+ const book = await fetchJSON(`/${bookId}`, {});
34
+ return {
35
+ content: [
36
+ {
37
+ type: 'text',
38
+ text: JSON.stringify(book, null, 2)
39
+ }
40
+ ]
41
+ };
42
+ });
43
+ server.registerTool('create-book', {
44
+ 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.',
45
+ inputSchema: {
46
+ name: z.string().min(1).max(64).describe('The notebook name'),
47
+ parentBookId: documentIdSchema(BOOK_DOCID_PREFIX)
48
+ .optional()
49
+ .describe('The ID of the parent notebook. Omit it to create the notebook at the root level.')
50
+ }
51
+ }, async (bookData) => {
52
+ const res = await postJSON(`/books`, bookData);
53
+ return {
54
+ content: [
55
+ {
56
+ type: 'text',
57
+ text: JSON.stringify(res, null, 2)
58
+ }
59
+ ]
60
+ };
61
+ });
62
+ server.registerTool('update-book', {
63
+ 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.',
64
+ inputSchema: {
65
+ _id: documentIdSchema(BOOK_DOCID_PREFIX).describe('The unique document ID which should start with `book:` and the remains are randomly generated string'),
66
+ _rev: revisionSchema
67
+ .optional()
68
+ .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.'),
69
+ name: z.string().min(1).max(64).optional().describe('The notebook name'),
70
+ parentBookId: documentIdSchema(BOOK_DOCID_PREFIX)
71
+ .nullable()
72
+ .optional()
73
+ .describe('The ID of the parent notebook. Pass `null` to move the notebook to the root level.'),
74
+ createdAt: timestampSchema
75
+ .optional()
76
+ .describe('The date time when the notebook was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.'),
77
+ updatedAt: timestampSchema
78
+ .optional()
79
+ .describe('The date time when the notebook was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.')
80
+ }
81
+ }, async ({ _id, ...updateFields }) => {
82
+ const res = await postJSON(`/${_id}`, {
83
+ ...updateFields,
84
+ updatedAt: updateFields.updatedAt ?? +new Date()
85
+ });
86
+ return {
87
+ content: [
88
+ {
89
+ type: 'text',
90
+ text: JSON.stringify(res, null, 2)
91
+ }
92
+ ]
93
+ };
94
+ });
95
+ }
@@ -0,0 +1,58 @@
1
+ import { parseInkdropUri } from '@inkdropapp/protocol-utils';
2
+ const INKDROP_URI_PREFIX = 'inkdrop://';
3
+ const LINE_BREAK_PATTERN = /\r\n?|\n/;
4
+ /**
5
+ * Parses what a tool received as a note ID: a document ID with or without the
6
+ * `note:` prefix, or a note link such as `inkdrop://note/abc123#L5-L8`.
7
+ *
8
+ * @param noteIdOrUri - The note ID or note URI
9
+ * @returns The note ID, plus the anchor when the URI has one
10
+ * @throws {Error} If the input is an Inkdrop URI that doesn't point to a note
11
+ */
12
+ export function parseNoteReference(noteIdOrUri) {
13
+ if (!noteIdOrUri.startsWith(INKDROP_URI_PREFIX)) {
14
+ return { noteId: noteIdOrUri.startsWith('note:') ? noteIdOrUri : `note:${noteIdOrUri}` };
15
+ }
16
+ const parsedUri = parseInkdropUri(noteIdOrUri);
17
+ if (parsedUri?.resourceType !== 'note') {
18
+ throw new Error(`\`${noteIdOrUri}\` is not a note URI. Expected \`inkdrop://note/<id>\`.`);
19
+ }
20
+ return parsedUri.anchor
21
+ ? { noteId: parsedUri.resourceId, anchor: parsedUri.anchor }
22
+ : { noteId: parsedUri.resourceId };
23
+ }
24
+ /**
25
+ * Picks a line range out of a note body.
26
+ *
27
+ * The range is clamped to the body the same way the editor clamps a line anchor,
28
+ * so a link to lines that no longer exist lands on the last line.
29
+ *
30
+ * @param body - The note body
31
+ * @param lineRange - The lines to pick
32
+ * @returns The lines that were picked, their actual range, and the body's line count
33
+ */
34
+ export function extractNoteLines(body, lineRange) {
35
+ const lines = body.split(LINE_BREAK_PATTERN);
36
+ const totalLines = lines.length;
37
+ const clampLine = (line) => Math.min(Math.max(line, 1), totalLines);
38
+ const startLine = clampLine(lineRange.startLine);
39
+ const endLine = clampLine(lineRange.endLine);
40
+ return {
41
+ text: lines.slice(startLine - 1, endLine).join('\n'),
42
+ startLine,
43
+ endLine,
44
+ totalLines
45
+ };
46
+ }
47
+ /**
48
+ * Words the notice `read-note` adds when `body` is an excerpt, so the excerpt
49
+ * isn't mistaken for the whole note.
50
+ *
51
+ * @param noteLines - The lines that were picked out of the note body
52
+ * @returns The notice text
53
+ */
54
+ export function describeNoteLines({ startLine, endLine, totalLines }) {
55
+ const lineLabel = startLine === endLine ? `line ${startLine}` : `lines ${startLine}-${endLine}`;
56
+ return (`\`body\` holds only ${lineLabel} of this note's ${totalLines} lines, as the link's anchor asks for. ` +
57
+ 'Call `read-note` with the note ID alone to get the whole body.');
58
+ }
@@ -0,0 +1,38 @@
1
+ import { NOTE_DOCID_PREFIX, NOTE_TITLE_MAX_LENGTH, TAG_DOCID_PREFIX } from 'inkdrop-model';
2
+ import { z } from 'zod';
3
+ import { documentIdSchema, revisionSchema, timestampSchema } from '../../utils/document-fields.js';
4
+ const noteIdFormatSchema = documentIdSchema(NOTE_DOCID_PREFIX);
5
+ /** The ID of a note document. */
6
+ export const noteIdSchema = noteIdFormatSchema.describe('The unique document ID which should start with `note:` and the remains are randomly generated string');
7
+ /** The revision a write must be based on. */
8
+ export const noteRevSchema = revisionSchema.describe('This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).');
9
+ /**
10
+ * A notebook ID, or one of the `trash` and `template` pseudo-notebooks.
11
+ * It has no description because each tool explains what `template` does there.
12
+ */
13
+ export const noteBookIdSchema = z
14
+ .string()
15
+ .min(5)
16
+ .max(128)
17
+ .regex(/^(book:|trash$|template$)/);
18
+ /** The title of a note. */
19
+ export const noteTitleSchema = z.string().max(NOTE_TITLE_MAX_LENGTH).describe('The note title');
20
+ /** The Markdown body of a note. It has no description because each tool words it differently. */
21
+ export const noteBodySchema = z.string().max(1_048_576);
22
+ /** The task status of a note. */
23
+ export const noteStatusSchema = z
24
+ .enum(['none', 'active', 'onHold', 'completed', 'dropped'])
25
+ .describe('The status of the note');
26
+ /** The IDs of the tags assigned to a note. */
27
+ export const noteTagsSchema = z
28
+ .array(documentIdSchema(TAG_DOCID_PREFIX))
29
+ .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.');
30
+ /** The creation time of a note, which a write keeps unless it is given. */
31
+ export const noteCreatedAtSchema = timestampSchema.describe('The date time when the note was created, represented with Unix timestamps in milliseconds. Omit it to keep the current value.');
32
+ /** The last update time of a note, which a write sets to now unless it is given. */
33
+ export const noteUpdatedAtSchema = timestampSchema.describe('The date time when the note was last updated, represented with Unix timestamps in milliseconds. Defaults to the current time.');
34
+ /**
35
+ * The ID of the template a note was created from.
36
+ * It has no description because only `update-note` can clear it, so each tool words it differently.
37
+ */
38
+ export const sourceTemplateIdSchema = noteIdFormatSchema;
@@ -0,0 +1,16 @@
1
+ import { fetchJSON, postJSON } from '../../client/local-server.js';
2
+ /**
3
+ * Merges the given fields into the stored note and saves it.
4
+ *
5
+ * @param noteUpdate - The note ID, its current revision, and the fields to change
6
+ * @returns The response of the local server for the saved note
7
+ * @throws If the note can't be fetched at that revision or the save is rejected
8
+ */
9
+ export async function updateNote(noteUpdate) {
10
+ const existingNote = await fetchJSON(`/${noteUpdate._id}`, { rev: noteUpdate._rev });
11
+ return postJSON('/notes', {
12
+ ...existingNote,
13
+ ...noteUpdate,
14
+ updatedAt: noteUpdate.updatedAt ?? +new Date()
15
+ });
16
+ }
@@ -0,0 +1,26 @@
1
+ import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { fetchJSON } from '../../client/local-server.js';
3
+ /**
4
+ * Registers the `inkdrop://note/{noteId}` resource.
5
+ *
6
+ * @param server - The MCP server to register on
7
+ */
8
+ export function registerNoteResource(server) {
9
+ server.registerResource('note', new ResourceTemplate('inkdrop://note/{noteId}', { list: undefined }), {
10
+ description: 'A note data',
11
+ mimeType: 'application/json'
12
+ }, async (uri, { noteId }) => {
13
+ const id = Array.isArray(noteId) ? noteId[0] : noteId;
14
+ const normalizedId = id.startsWith('note:') ? id : `note:${id}`;
15
+ const note = await fetchJSON(`/${normalizedId}`, {});
16
+ return {
17
+ contents: [
18
+ {
19
+ uri: uri.href,
20
+ text: JSON.stringify(note, null, 2),
21
+ mimeType: 'application/json'
22
+ }
23
+ ]
24
+ };
25
+ });
26
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Applies exact string replacements in order, each against the result of the
3
+ * previous one, so a later edit can match text an earlier edit produced.
4
+ *
5
+ * Every `old_string` must match exactly one location at the time it is applied.
6
+ * Processing stops at the first edit that does not, so callers never see a
7
+ * partially patched text.
8
+ *
9
+ * @param text - The text to patch
10
+ * @param edits - The replacements to perform
11
+ * @returns The patched text, or an error naming the 1-based position of the failing edit
12
+ */
13
+ export function applyTextEdits(text, edits) {
14
+ let patchedText = text;
15
+ for (const [editIndex, { old_string, new_string }] of edits.entries()) {
16
+ const editLabel = `edit ${editIndex + 1} of ${edits.length}`;
17
+ const firstMatchIndex = patchedText.indexOf(old_string);
18
+ if (firstMatchIndex === -1) {
19
+ return {
20
+ ok: false,
21
+ error: `\`old_string\` of ${editLabel} was not found in the note body.`
22
+ };
23
+ }
24
+ if (patchedText.indexOf(old_string, firstMatchIndex + 1) !== -1) {
25
+ return {
26
+ ok: false,
27
+ error: `\`old_string\` of ${editLabel} matches multiple locations in the note body. Provide more surrounding context to make it unique.`
28
+ };
29
+ }
30
+ patchedText =
31
+ patchedText.slice(0, firstMatchIndex) +
32
+ new_string +
33
+ patchedText.slice(firstMatchIndex + old_string.length);
34
+ }
35
+ return { ok: true, text: patchedText };
36
+ }
@@ -0,0 +1,405 @@
1
+ import { getNoteUri } from '@inkdropapp/protocol-utils';
2
+ import { z } from 'zod';
3
+ import { fetchJSON, postJSON } from '../../client/local-server.js';
4
+ import { describeNoteLines, extractNoteLines, parseNoteReference } from './note-anchor.js';
5
+ import { noteBodySchema, noteBookIdSchema, noteCreatedAtSchema, noteIdSchema, noteRevSchema, noteStatusSchema, noteTagsSchema, noteTitleSchema, noteUpdatedAtSchema, sourceTemplateIdSchema } from './note-schemas.js';
6
+ import { updateNote } from './note-update.js';
7
+ import { applyTextEdits } from './text-edits.js';
8
+ /**
9
+ * Registers the tools that read, search, create and update notes and templates.
10
+ *
11
+ * @param server - The MCP server to register on
12
+ */
13
+ export function registerNoteTools(server) {
14
+ server.registerTool('read-note', {
15
+ description: 'Retrieve the complete contents of the note by its ID or its note link from the database. ' +
16
+ 'A note link can carry a line anchor (`inkdrop://note/<id>#L5` or `#L5-L8`); ' +
17
+ 'the returned `body` then holds only those lines. ' +
18
+ 'A note created from a template has a `sourceTemplateId`; when present, the response ' +
19
+ 'includes a resource link to that source template, whose body holds the fill-out ' +
20
+ 'instructions and examples. Read the template (or pass `includeTemplate: true`) before ' +
21
+ 'completing the note.',
22
+ inputSchema: {
23
+ noteId: z
24
+ .string()
25
+ .describe('ID of the note to retrieve, or a note link. The ID can be found as `_id` in the note docs and always starts with `note:`. ' +
26
+ 'A note link looks like `inkdrop://note/<id>`, optionally followed by `#L5` (one line) or `#L5-L8` (a line range) to read only those lines.'),
27
+ includeTemplate: z
28
+ .boolean()
29
+ .optional()
30
+ .default(false)
31
+ .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.')
32
+ }
33
+ }, async ({ noteId: noteIdOrUri, includeTemplate }) => {
34
+ const { noteId, anchor } = parseNoteReference(noteIdOrUri);
35
+ const storedNote = await fetchJSON(`/${noteId}`, {});
36
+ const anchoredLines = anchor?.type === 'lines' ? extractNoteLines(storedNote.body, anchor) : undefined;
37
+ const note = anchoredLines ? { ...storedNote, body: anchoredLines.text } : storedNote;
38
+ let templateBlockText = null;
39
+ if (includeTemplate && note.sourceTemplateId) {
40
+ try {
41
+ const template = await fetchJSON(`/${note.sourceTemplateId}`, {});
42
+ templateBlockText = `# Source template: ${template.title}\n\n${template.body}`;
43
+ }
44
+ catch {
45
+ // Template unavailable (e.g. deleted → 404). Skip the embed; the note read still succeeds.
46
+ }
47
+ }
48
+ return {
49
+ content: [
50
+ {
51
+ type: 'text',
52
+ text: JSON.stringify(note, null, 2)
53
+ },
54
+ ...(anchoredLines
55
+ ? [{ type: 'text', text: describeNoteLines(anchoredLines) }]
56
+ : []),
57
+ ...(anchor?.type === 'heading'
58
+ ? [
59
+ {
60
+ type: 'text',
61
+ text: `The link points to the heading whose slug is \`${anchor.slug}\`. Heading anchors are not resolved by this tool, so \`body\` holds the whole note.`
62
+ }
63
+ ]
64
+ : []),
65
+ ...(note.sourceTemplateId
66
+ ? [
67
+ {
68
+ type: 'resource_link',
69
+ uri: getNoteUri(note.sourceTemplateId),
70
+ name: 'Source template',
71
+ mimeType: 'application/json',
72
+ description: 'The template this note was created from. Read it to get the fill-out instructions and examples before completing this note.'
73
+ }
74
+ ]
75
+ : []),
76
+ ...(templateBlockText ? [{ type: 'text', text: templateBlockText }] : [])
77
+ ]
78
+ };
79
+ });
80
+ server.registerTool('read-backlinks', {
81
+ description: `Retrieve backlinks for a note — the notes that link to it.
82
+ Each result is returned as a resource link (\`inkdrop://note/<id>\`) pointing to the referring note.
83
+ Backlinks are found by searching all note bodies for the note's link URI.`,
84
+ inputSchema: {
85
+ noteId: z
86
+ .string()
87
+ .describe('ID of the note to find backlinks for. It can be found as `_id` in the note docs. It always starts with `note:`.')
88
+ }
89
+ }, async ({ noteId }) => {
90
+ if (!noteId.startsWith('note:')) {
91
+ noteId = `note:${noteId}`;
92
+ }
93
+ const noteLink = getNoteUri(noteId);
94
+ const backlinks = await fetchJSON('/notes', {
95
+ keyword: noteLink,
96
+ limit: 100
97
+ });
98
+ if (backlinks.length === 0) {
99
+ return {
100
+ content: [
101
+ {
102
+ type: 'text',
103
+ text: `No backlinks found for ${noteLink}.`
104
+ }
105
+ ]
106
+ };
107
+ }
108
+ return {
109
+ content: backlinks.map(note => ({
110
+ type: 'resource_link',
111
+ uri: getNoteUri(note._id),
112
+ name: note.title || 'Untitled note',
113
+ mimeType: 'application/json'
114
+ }))
115
+ };
116
+ });
117
+ server.registerTool('search-notes', {
118
+ description: `List all notes that contain a given keyword.
119
+ The result does not include entire note bodies as they are truncated in 200 characters.
120
+ You have to retrieve the full note content by calling \`read-note\`.
121
+ Here are tips to specify keywords effectively:
122
+
123
+ ## Use special qualifiers to narrow down results
124
+
125
+ You can use special qualifiers to get more accurate results. See the qualifiers and their usage examples:
126
+
127
+ - **book**
128
+ \`book:Blog\`: Searches for notes in the 'Blog' notebook.
129
+ \`book:"Desktop App"\`: Searches for notes in the 'Desktop App' notebook.
130
+ \`book:kGlLniaV\`: Searches for notes in the notebook with the ID 'book:kGlLniaV'.
131
+ - **tag**
132
+ \`tag:JavaScript\`: Searches for all notes having the 'JavaScript' tag. Read more about [tags](https://docs.inkdrop.app/manual/write-notes#tag-notes).
133
+ \`tag:pQ7xYt2R\`: Searches for all notes having the tag with the ID 'tag:pQ7xYt2R'.
134
+ - **status**
135
+ \`status:onHold\`: Searches for all notes with the 'On hold' status. Read more about [statuses](/reference/note-statuses).
136
+ - **title**
137
+ \`title:"JavaScript setTimeout"\`: Searches for the note with the specified title.
138
+ - **body**
139
+ \`body:KEYWORD\`: Searches for a specific word in all notes. Equivalent to a [global search](#search-for-notes-across-all-notebooks).
140
+
141
+ ### Combine qualifiers
142
+
143
+ You can combine the filter qualifiers to refine data even more.
144
+
145
+ **Find notes that contain the word 'Hello' and have the 'Issue' tag.**
146
+
147
+ \`\`\`text
148
+ Hello tag:Issue
149
+ \`\`\`
150
+
151
+ **Find notes that contain the word 'Typescript,' have the 'Contribution' tag, and the 'Completed' status**
152
+
153
+ \`\`\`text
154
+ Typescript tag:Contribution status:Completed
155
+ \`\`\`
156
+
157
+ ## Search for text with spaces
158
+
159
+ To find the text that includes spaces, put the text into the double quotation marks ("):
160
+
161
+ \`\`\`text
162
+ "database associations"
163
+ \`\`\`
164
+
165
+ ## Exclude text from search
166
+
167
+ 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:
168
+
169
+ - \`-book:Backend "closure functions"\`: Ignores the 'Backend' notebook while searching for the 'closure functions' phrase.
170
+ - \`-tag:JavaScript\`: Ignores all notes having the 'JavaScript' tag.
171
+ - \`-book:Typescript tag:work "Data types"\`: Ignores the 'Typescript' notebook and the 'work' tag while searching for the 'Data types' phrase.
172
+ - \`-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.
173
+ - \`-"Phrase to ignore" "in the rest of a sentence"\`: Ignores the 'Phrase to ignore' part while searching for 'in the rest of a sentence'.
174
+
175
+ Note that you can't specify excluding modifiers only without including conditions.
176
+
177
+ **WARNING**: Make sure to enter a text to search for after the exclusion modifier.
178
+
179
+ - ✅ Will work
180
+ \`-book:Backend "closure functions"\`
181
+
182
+ - ⛔️ Won't work
183
+ \`-book:Backend\`. There's no query. Inkdrop doesn't understand what to search for.
184
+ `,
185
+ inputSchema: {
186
+ keyword: z.string().describe(`Keyword to search for.`)
187
+ }
188
+ }, async ({ keyword }) => {
189
+ const notes = await fetchJSON('/notes', { keyword, limit: 10 });
190
+ const summaries = notes.map(note => {
191
+ return {
192
+ ...note,
193
+ body: note.body.slice(0, 200)
194
+ };
195
+ });
196
+ return {
197
+ content: [
198
+ {
199
+ type: 'text',
200
+ text: JSON.stringify(summaries, null, 2)
201
+ }
202
+ ]
203
+ };
204
+ });
205
+ server.registerTool('list-notes', {
206
+ description: `List all notes with specified conditions.
207
+ The result does not include entire note bodies as they are truncated in 200 characters.
208
+ You have to retrieve the full note content by calling \`read-note\`.
209
+ `,
210
+ inputSchema: {
211
+ bookId: z
212
+ .string()
213
+ .optional()
214
+ .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`),
215
+ tagIds: z
216
+ .array(z.string())
217
+ .optional()
218
+ .default([])
219
+ .describe(`An array of tag IDs to filter. It always starts with 'tag:'. You can retrieve a list of available tags from \`list-tags\`.`),
220
+ keyword: z.string().optional().describe(`Keyword to filter notes`),
221
+ sort: z
222
+ .enum(['updatedAt', 'createdAt', 'title'])
223
+ .optional()
224
+ .default('updatedAt')
225
+ .describe(`Sort the documents by the specified field`),
226
+ descending: z
227
+ .boolean()
228
+ .optional()
229
+ .default(true)
230
+ .describe(`Reverse the order of the output documents`),
231
+ limit: z.number().optional().default(100).describe(`Limit the number of results returned`)
232
+ }
233
+ }, async ({ bookId, tagIds, keyword, sort, descending, limit }) => {
234
+ const bookFilter = bookId ?? '';
235
+ const tagFilter = tagIds?.join(' ') ?? '';
236
+ keyword = `${bookFilter} ${tagFilter} ${keyword || ''}`.trim();
237
+ const notes = await fetchJSON('/notes', {
238
+ keyword,
239
+ sort,
240
+ descending,
241
+ limit
242
+ });
243
+ const summaries = notes.map(note => {
244
+ return {
245
+ ...note,
246
+ body: note.body.slice(0, 200)
247
+ };
248
+ });
249
+ return {
250
+ content: [
251
+ {
252
+ type: 'text',
253
+ text: JSON.stringify(summaries, null, 2)
254
+ }
255
+ ]
256
+ };
257
+ });
258
+ server.registerTool('list-templates', {
259
+ description: `List note templates: your custom templates, followed by the official ones bundled with Inkdrop.
260
+ Templates are notes whose \`bookId\` is \`template\`. Official templates are read-only.
261
+ The result does not include entire template bodies as they are truncated in 200 characters.
262
+ You have to retrieve the full template content by calling \`read-note\`.
263
+ When you create a note from a template, pass the template's \`_id\` as \`sourceTemplateId\` to \`create-note\`.
264
+ `,
265
+ inputSchema: {
266
+ keyword: z
267
+ .string()
268
+ .optional()
269
+ .describe('Filter templates by fuzzy-matching their titles. Search qualifiers such as `book:` or `tag:` are not supported.')
270
+ }
271
+ }, async ({ keyword }) => {
272
+ const templates = await fetchJSON('/templates', { keyword });
273
+ const summaries = templates.map(template => {
274
+ return {
275
+ ...template,
276
+ body: template.body.slice(0, 200)
277
+ };
278
+ });
279
+ return {
280
+ content: [
281
+ {
282
+ type: 'text',
283
+ text: JSON.stringify(summaries, null, 2)
284
+ }
285
+ ]
286
+ };
287
+ });
288
+ server.registerTool('create-note', {
289
+ description: 'Create a new note in the database',
290
+ inputSchema: {
291
+ bookId: noteBookIdSchema.describe('The notebook ID. Specify `template` to create a custom note template'),
292
+ title: noteTitleSchema,
293
+ body: noteBodySchema.describe('The content of the note represented with Markdown'),
294
+ status: noteStatusSchema.optional(),
295
+ tags: noteTagsSchema.optional(),
296
+ sourceTemplateId: sourceTemplateIdSchema
297
+ .optional()
298
+ .describe('The ID of the template the note is created from, as returned by `list-templates`. It always starts with `note:`. Pass it when you create a note from a template, so that `read-note` can link the note back to its fill-out instructions.')
299
+ }
300
+ }, async (noteData) => {
301
+ const res = await postJSON(`/notes`, noteData);
302
+ return {
303
+ content: [
304
+ {
305
+ type: 'text',
306
+ text: JSON.stringify(res, null, 2)
307
+ }
308
+ ]
309
+ };
310
+ });
311
+ server.registerTool('update-note', {
312
+ 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.',
313
+ inputSchema: {
314
+ notes: z
315
+ .array(z.object({
316
+ _id: noteIdSchema,
317
+ _rev: noteRevSchema,
318
+ bookId: noteBookIdSchema
319
+ .optional()
320
+ .describe('The notebook ID. Specify `template` to turn the note into a custom note template'),
321
+ title: noteTitleSchema.optional(),
322
+ body: noteBodySchema
323
+ .optional()
324
+ .describe('The content of the note in Markdown. NOTE: Do not escape special characters like `\\n`.'),
325
+ status: noteStatusSchema.optional(),
326
+ tags: noteTagsSchema.optional(),
327
+ sourceTemplateId: sourceTemplateIdSchema
328
+ .nullable()
329
+ .optional()
330
+ .describe('The ID of the template the note was created from, as returned by `list-templates`. It always starts with `note:`. Pass `null` to remove the link to the template. Omit it to keep the current value.'),
331
+ createdAt: noteCreatedAtSchema.optional(),
332
+ updatedAt: noteUpdatedAtSchema.optional()
333
+ }))
334
+ .min(1)
335
+ .describe('The notes to update.')
336
+ }
337
+ }, async ({ notes }) => {
338
+ const settledUpdates = await Promise.allSettled(notes.map(updateNote));
339
+ const results = settledUpdates.map((settledUpdate, noteIndex) => settledUpdate.status === 'fulfilled'
340
+ ? settledUpdate.value
341
+ : {
342
+ ok: false,
343
+ id: notes[noteIndex]._id,
344
+ error: settledUpdate.reason.message
345
+ });
346
+ return {
347
+ content: [
348
+ {
349
+ type: 'text',
350
+ text: JSON.stringify(results, null, 2)
351
+ }
352
+ ],
353
+ isError: settledUpdates.some(settledUpdate => settledUpdate.status === 'rejected')
354
+ };
355
+ });
356
+ server.registerTool('patch-note', {
357
+ 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.',
358
+ inputSchema: {
359
+ _id: noteIdSchema,
360
+ _rev: noteRevSchema,
361
+ edits: z
362
+ .array(z.object({
363
+ old_string: z
364
+ .string()
365
+ .min(1)
366
+ .describe('The exact text to find in the note body. Must match exactly one occurrence. Include enough surrounding context to ensure a unique match.'),
367
+ new_string: z
368
+ .string()
369
+ .describe('The text to replace `old_string` with. Use an empty string to delete the matched text.')
370
+ }))
371
+ .min(1)
372
+ .describe('The replacements to perform, applied in order.'),
373
+ createdAt: noteCreatedAtSchema.optional(),
374
+ updatedAt: noteUpdatedAtSchema.optional()
375
+ }
376
+ }, async ({ _id, _rev, edits, createdAt, updatedAt }) => {
377
+ const existingNote = await fetchJSON(`/${_id}`, { rev: _rev });
378
+ const patchResult = applyTextEdits(existingNote.body, edits);
379
+ if (!patchResult.ok) {
380
+ return {
381
+ content: [
382
+ {
383
+ type: 'text',
384
+ text: `Failed to patch: ${patchResult.error} No edits were saved.`
385
+ }
386
+ ],
387
+ isError: true
388
+ };
389
+ }
390
+ const res = await postJSON('/notes', {
391
+ ...existingNote,
392
+ body: patchResult.text,
393
+ createdAt: createdAt ?? existingNote.createdAt,
394
+ updatedAt: updatedAt ?? +new Date()
395
+ });
396
+ return {
397
+ content: [
398
+ {
399
+ type: 'text',
400
+ text: JSON.stringify(res, null, 2)
401
+ }
402
+ ]
403
+ };
404
+ });
405
+ }