@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.
- package/.github/workflows/actions.lock +10 -0
- package/.github/workflows/ci.yml +65 -0
- package/.github/workflows/publish.yml +10 -1
- package/.oxfmtrc.json +2 -1
- package/README.md +16 -6
- package/dist/client/agent-identity.js +45 -0
- package/dist/client/agent-session.js +66 -0
- package/dist/client/local-server.js +64 -0
- package/dist/features/files/image-type.js +31 -0
- package/dist/features/files/tools.js +191 -0
- package/dist/features/notebooks/tools.js +95 -0
- package/dist/features/notes/note-anchor.js +58 -0
- package/dist/features/notes/note-schemas.js +38 -0
- package/dist/features/notes/note-update.js +16 -0
- package/dist/features/notes/resource.js +26 -0
- package/dist/features/notes/text-edits.js +36 -0
- package/dist/features/notes/tools.js +405 -0
- package/dist/features/tags/tools.js +82 -0
- package/dist/index.js +19 -826
- package/dist/utils/document-fields.js +18 -0
- package/mise.toml +5 -0
- package/oxlint.config.ts +50 -0
- package/package.json +22 -14
- package/pnpm-workspace.yaml +6 -0
- package/src/client/agent-identity.ts +70 -0
- package/src/client/agent-session.ts +75 -0
- package/src/client/local-server.ts +73 -0
- package/src/features/files/image-type.ts +35 -0
- package/src/features/files/tools.ts +230 -0
- package/src/features/notebooks/tools.ts +133 -0
- package/src/features/notes/note-anchor.ts +85 -0
- package/src/features/notes/note-schemas.ts +60 -0
- package/src/features/notes/note-update.ts +27 -0
- package/src/features/notes/resource.ts +34 -0
- package/src/features/notes/text-edits.ts +48 -0
- package/src/features/notes/tools.ts +499 -0
- package/src/features/tags/tools.ts +109 -0
- package/src/index.ts +17 -1049
- package/src/utils/document-fields.ts +21 -0
- package/tests/client/agent-identity.test.ts +98 -0
- package/tests/features/notes/note-anchor.test.ts +125 -0
- package/tests/features/notes/note-schemas.test.ts +27 -0
- package/tests/utils/document-fields.test.ts +41 -0
- package/tsconfig.json +1 -1
- package/dist/api.js +0 -47
- package/dist/utils.js +0 -100
- package/src/api.ts +0 -45
- package/src/utils.ts +0 -112
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
# Docs: https://gh.io/actions-lockfile
|
|
4
4
|
version: 'v0.0.3'
|
|
5
5
|
workflows:
|
|
6
|
+
'.github/workflows/ci.yml':
|
|
7
|
+
- 'actions/checkout@v7.0.1'
|
|
8
|
+
- 'actions/setup-node@v7.1.0'
|
|
9
|
+
- 'oven-sh/setup-bun@v2.2.0'
|
|
10
|
+
- 'pnpm/action-setup@v6.1.1'
|
|
6
11
|
'.github/workflows/publish.yml':
|
|
7
12
|
- 'actions/checkout@v7.0.1'
|
|
8
13
|
- 'actions/setup-node@v7.1.0'
|
|
@@ -18,6 +23,11 @@ dependencies:
|
|
|
18
23
|
commit: 'sha1-949feb2413d6458794dcd2491c4babbbce0c15c1'
|
|
19
24
|
owner_id: 44036562
|
|
20
25
|
repo_id: 189476904
|
|
26
|
+
'oven-sh/setup-bun@v2.2.0':
|
|
27
|
+
ref: 'v2.2.0'
|
|
28
|
+
commit: 'sha1-0c5077e51419868618aeaa5fe8019c62421857d6'
|
|
29
|
+
owner_id: 108928776
|
|
30
|
+
repo_id: 512644635
|
|
21
31
|
'pnpm/action-setup@v6.1.1':
|
|
22
32
|
ref: 'v6.1.1'
|
|
23
33
|
commit: 'sha1-73e46992e05b19abd31f2f3c20e0e7370d762115'
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
concurrency:
|
|
12
|
+
group: ci-${{ github.ref }}
|
|
13
|
+
cancel-in-progress: true
|
|
14
|
+
|
|
15
|
+
jobs:
|
|
16
|
+
test:
|
|
17
|
+
runs-on: ubuntu-latest
|
|
18
|
+
timeout-minutes: 10
|
|
19
|
+
steps:
|
|
20
|
+
- name: Checkout
|
|
21
|
+
uses: actions/checkout@v7.0.1
|
|
22
|
+
|
|
23
|
+
- name: Install pnpm
|
|
24
|
+
uses: pnpm/action-setup@v6.1.1
|
|
25
|
+
with:
|
|
26
|
+
version: 12
|
|
27
|
+
|
|
28
|
+
- name: Set up Node.js
|
|
29
|
+
uses: actions/setup-node@v7.1.0
|
|
30
|
+
with:
|
|
31
|
+
node-version: 24
|
|
32
|
+
cache: pnpm
|
|
33
|
+
|
|
34
|
+
- name: Set up Bun
|
|
35
|
+
uses: oven-sh/setup-bun@v2.2.0
|
|
36
|
+
|
|
37
|
+
- name: Install dependencies
|
|
38
|
+
run: pnpm install --frozen-lockfile
|
|
39
|
+
|
|
40
|
+
- name: Check formatting
|
|
41
|
+
run: pnpm format:check
|
|
42
|
+
|
|
43
|
+
- name: Lint
|
|
44
|
+
run: pnpm lint
|
|
45
|
+
|
|
46
|
+
- name: Typecheck
|
|
47
|
+
run: pnpm typecheck
|
|
48
|
+
|
|
49
|
+
- name: Test
|
|
50
|
+
run: pnpm test
|
|
51
|
+
|
|
52
|
+
actions-lock:
|
|
53
|
+
name: Verify the actions lockfile
|
|
54
|
+
runs-on: ubuntu-latest
|
|
55
|
+
timeout-minutes: 5
|
|
56
|
+
steps:
|
|
57
|
+
- name: Checkout
|
|
58
|
+
uses: actions/checkout@v7.0.1
|
|
59
|
+
|
|
60
|
+
- name: Verify
|
|
61
|
+
env:
|
|
62
|
+
GH_TOKEN: ${{ github.token }}
|
|
63
|
+
run: |
|
|
64
|
+
gh extension install github/gh-actions-lock --pin v0.4.1
|
|
65
|
+
gh actions-lock --verify
|
|
@@ -49,9 +49,18 @@ jobs:
|
|
|
49
49
|
- name: Check formatting
|
|
50
50
|
run: pnpm format:check
|
|
51
51
|
|
|
52
|
+
- name: Lint
|
|
53
|
+
run: pnpm lint
|
|
54
|
+
|
|
52
55
|
- name: Publish
|
|
53
56
|
# prepublishOnly builds dist/ with tsc, so the typecheck runs here.
|
|
54
|
-
run:
|
|
57
|
+
run: |
|
|
58
|
+
if [[ "$TAG" == *-* ]]; then
|
|
59
|
+
npm publish --tag beta
|
|
60
|
+
else
|
|
61
|
+
npm publish
|
|
62
|
+
fi
|
|
55
63
|
env:
|
|
64
|
+
TAG: ${{ github.ref_name }}
|
|
56
65
|
# The token setup-node configures must be empty, or npm uses it instead of OIDC.
|
|
57
66
|
NODE_AUTH_TOKEN: ''
|
package/.oxfmtrc.json
CHANGED
package/README.md
CHANGED
|
@@ -10,12 +10,13 @@ Read [the docs here](https://docs.inkdrop.app/reference/mcp-server).
|
|
|
10
10
|
|
|
11
11
|
### Tools
|
|
12
12
|
|
|
13
|
-
1. **`read-note`**: Retrieve the complete contents of the note by its ID from the database.
|
|
13
|
+
1. **`read-note`**: Retrieve the complete contents of the note by its ID or its note link from the database.
|
|
14
14
|
- Required inputs:
|
|
15
|
-
- `noteId`: The ID of the note to retrieve.
|
|
15
|
+
- `noteId`: The 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:`. A note link looks like `inkdrop://note/<id>`, optionally followed by a line anchor: `#L5` (one line) or `#L5-L8` (a line range).
|
|
16
16
|
- Optional inputs:
|
|
17
17
|
- `includeTemplate`: When `true` and the note has a `sourceTemplateId`, also fetch that template and embed its body (fill-out instructions and examples) as an extra text block. Default: `false`.
|
|
18
18
|
- Note: If the note was created from a template, the response includes a resource link to its source template, whose body holds the fill-out instructions and examples.
|
|
19
|
+
- Note: With a line anchor, the returned `body` holds only those lines, and an extra text block says which lines they are. Lines past the end of the note are clamped to the last line. A heading anchor (`#slug`) is not resolved: the whole note is returned.
|
|
19
20
|
2. **`read-backlinks`**: Retrieve backlinks for a note — the notes that link to it.
|
|
20
21
|
- Required inputs:
|
|
21
22
|
- `noteId`: The ID of the note to find backlinks for. It always starts with `note:`.
|
|
@@ -26,18 +27,19 @@ Read [the docs here](https://docs.inkdrop.app/reference/mcp-server).
|
|
|
26
27
|
- Note: Results include truncated note bodies (200 characters). Use `read-note` to get full content.
|
|
27
28
|
- Supports advanced search qualifiers like `book:`, `tag:`, `status:`, `title:`, etc.
|
|
28
29
|
4. **`list-notes`**: List all notes with specified conditions.
|
|
29
|
-
- Required inputs:
|
|
30
|
-
- `bookId`: The notebook ID. It always starts with 'book:'.
|
|
31
30
|
- Optional inputs:
|
|
31
|
+
- `bookId`: The notebook ID. It always starts with 'book:'.
|
|
32
32
|
- `tagIds`: An array of tag IDs to filter. Each starts with 'tag:'.
|
|
33
33
|
- `keyword`: Keyword to filter notes.
|
|
34
34
|
- `sort`: Sort field (`updatedAt`, `createdAt`, or `title`). Default: `updatedAt`.
|
|
35
35
|
- `descending`: Reverse the order of output. Default: `true`.
|
|
36
|
+
- `limit`: The maximum number of notes to return. Default: `100`.
|
|
36
37
|
- Note: Results include truncated note bodies (200 characters). Use `read-note` to get full content.
|
|
37
38
|
5. **`list-templates`**: List note templates — your custom templates, followed by the official ones bundled with Inkdrop.
|
|
38
39
|
- Optional inputs:
|
|
39
40
|
- `keyword`: Filter templates by fuzzy-matching their titles.
|
|
40
41
|
- Note: Results include truncated template bodies (200 characters). Use `read-note` to get full content.
|
|
42
|
+
- Note: When creating a note from a template, pass the template's `_id` as `sourceTemplateId` to `create-note`.
|
|
41
43
|
6. **`create-note`**: Create a new note in the database.
|
|
42
44
|
- Required inputs:
|
|
43
45
|
- `bookId`: The notebook ID. Must start with 'book:' or be 'trash' or 'template'. Specify 'template' to create a custom note template.
|
|
@@ -46,6 +48,7 @@ Read [the docs here](https://docs.inkdrop.app/reference/mcp-server).
|
|
|
46
48
|
- Optional inputs:
|
|
47
49
|
- `status`: The note status (`none`, `active`, `onHold`, `completed`, `dropped`).
|
|
48
50
|
- `tags`: An array of tag IDs to assign to the note. Each must start with 'tag:'.
|
|
51
|
+
- `sourceTemplateId`: The ID of the template the note is created from. Must start with 'note:'.
|
|
49
52
|
7. **`update-note`**: Update one or more existing notes in the database. Only the fields you provide will be updated; omitted fields remain unchanged. Each note is saved independently, so a failed update does not roll back the others.
|
|
50
53
|
- Required inputs:
|
|
51
54
|
- `notes`: An array of notes to update. Each item takes:
|
|
@@ -56,14 +59,19 @@ Read [the docs here](https://docs.inkdrop.app/reference/mcp-server).
|
|
|
56
59
|
- `body`: The content of the note in Markdown.
|
|
57
60
|
- `status`: The note status (`none`, `active`, `onHold`, `completed`, `dropped`).
|
|
58
61
|
- `tags`: An array of tag IDs to assign to the note. Each must start with 'tag:'.
|
|
62
|
+
- `sourceTemplateId`: The ID of the template the note was created from. Must start with 'note:'. Pass `null` to remove the link.
|
|
59
63
|
- `createdAt`: The creation time as a Unix timestamp in milliseconds. Omit it to keep the current value.
|
|
60
64
|
- `updatedAt`: The last update time as a Unix timestamp in milliseconds. Defaults to the current time.
|
|
61
65
|
8. **`patch-note`**: Update the body of an existing note by performing one or more exact string replacements in a single call. More efficient than `update-note` for small edits to large notes as it saves tokens. You must first read the note with `read-note` to get the current body.
|
|
62
66
|
- Required inputs:
|
|
63
67
|
- `_id`: The note ID. Must start with 'note:'.
|
|
64
68
|
- `_rev`: The revision ID (CouchDB MVCC-token).
|
|
65
|
-
- `
|
|
66
|
-
|
|
69
|
+
- `edits`: An array of replacements, applied in order, each against the result of the previous one. The note is saved only if all of them succeed. Each item takes:
|
|
70
|
+
- `old_string` (required): The exact text to find in the note body. Must match exactly one occurrence. Include enough surrounding context to ensure a unique match.
|
|
71
|
+
- `new_string` (required): The text to replace `old_string` with. Use an empty string to delete the matched text.
|
|
72
|
+
- Optional inputs:
|
|
73
|
+
- `createdAt`: The creation time as a Unix timestamp in milliseconds. Omit it to keep the current value.
|
|
74
|
+
- `updatedAt`: The last update time as a Unix timestamp in milliseconds. Defaults to the current time.
|
|
67
75
|
9. **`list-notebooks`**: Retrieve a list of all notebooks.
|
|
68
76
|
10. **`read-book`**: Retrieve a single notebook by its ID.
|
|
69
77
|
- Required inputs:
|
|
@@ -80,6 +88,8 @@ Read [the docs here](https://docs.inkdrop.app/reference/mcp-server).
|
|
|
80
88
|
- `_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.
|
|
81
89
|
- `name`: The notebook name.
|
|
82
90
|
- `parentBookId`: The ID of the parent notebook. Pass `null` to move the notebook to the root level.
|
|
91
|
+
- `createdAt`: The creation time as a Unix timestamp in milliseconds. Omit it to keep the current value.
|
|
92
|
+
- `updatedAt`: The last update time as a Unix timestamp in milliseconds. Defaults to the current time.
|
|
83
93
|
13. **`list-tags`**: Retrieve a list of all tags.
|
|
84
94
|
14. **`read-tag`**: Retrieve a single tag by its ID.
|
|
85
95
|
- Required inputs:
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { AGENT_HEADERS } from 'inkdrop-consts';
|
|
3
|
+
const MAX_VALUE_LENGTH = 128;
|
|
4
|
+
function encodeHeaderValue(value) {
|
|
5
|
+
return encodeURIComponent(value.slice(0, MAX_VALUE_LENGTH).toWellFormed());
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Builds the identity headers of a request.
|
|
9
|
+
*
|
|
10
|
+
* Each value is cut to 128 UTF-16 code units and percent-encoded, since a header value cannot carry
|
|
11
|
+
* line breaks or characters outside Latin-1.
|
|
12
|
+
*/
|
|
13
|
+
export function buildAgentHeaders(identity) {
|
|
14
|
+
const values = [
|
|
15
|
+
[AGENT_HEADERS.session, identity.sessionId],
|
|
16
|
+
[AGENT_HEADERS.clientName, identity.client?.name],
|
|
17
|
+
[AGENT_HEADERS.clientTitle, identity.client?.title],
|
|
18
|
+
[AGENT_HEADERS.clientVersion, identity.client?.version],
|
|
19
|
+
[AGENT_HEADERS.workspace, identity.workspace]
|
|
20
|
+
];
|
|
21
|
+
return Object.fromEntries(values.flatMap(([header, value]) => (value ? [[header, encodeHeaderValue(value)]] : [])));
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Picks a display name for an MCP root: the name the client gave it, or the last folder of its URI.
|
|
25
|
+
*
|
|
26
|
+
* @returns `undefined` when the URI is malformed or names no folder
|
|
27
|
+
*/
|
|
28
|
+
export function workspaceNameFromRoot(root) {
|
|
29
|
+
if (root.name) {
|
|
30
|
+
return root.name;
|
|
31
|
+
}
|
|
32
|
+
if (!URL.canParse(root.uri)) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
const lastSegment = new URL(root.uri).pathname.split('/').findLast(segment => segment !== '');
|
|
36
|
+
return lastSegment ? decodeURIComponent(lastSegment) : undefined;
|
|
37
|
+
}
|
|
38
|
+
let currentIdentity = { sessionId: randomUUID() };
|
|
39
|
+
export function getAgentIdentity() {
|
|
40
|
+
return currentIdentity;
|
|
41
|
+
}
|
|
42
|
+
/** Adds what the MCP handshake told about the client to the identity of this process. */
|
|
43
|
+
export function updateAgentIdentity(update) {
|
|
44
|
+
currentIdentity = { ...currentIdentity, ...update };
|
|
45
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { updateAgentIdentity, workspaceNameFromRoot } from './agent-identity.js';
|
|
2
|
+
import { sendAgentSessionSignal } from './local-server.js';
|
|
3
|
+
const HEARTBEAT_INTERVAL_MS = 60_000;
|
|
4
|
+
async function readWorkspaceName(server) {
|
|
5
|
+
if (!server.getClientCapabilities()?.roots) {
|
|
6
|
+
return undefined;
|
|
7
|
+
}
|
|
8
|
+
try {
|
|
9
|
+
const { roots } = await server.listRoots();
|
|
10
|
+
const firstRoot = roots[0];
|
|
11
|
+
return firstRoot ? workspaceNameFromRoot(firstRoot) : undefined;
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function handleInitialized(server) {
|
|
18
|
+
const client = server.getClientVersion();
|
|
19
|
+
if (client) {
|
|
20
|
+
updateAgentIdentity({
|
|
21
|
+
client: { name: client.name, title: client.title, version: client.version }
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
await sendAgentSessionSignal('POST');
|
|
25
|
+
const workspace = await readWorkspaceName(server);
|
|
26
|
+
if (workspace) {
|
|
27
|
+
updateAgentIdentity({ workspace });
|
|
28
|
+
await sendAgentSessionSignal('POST');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Tells the Inkdrop app when this agent session starts and ends, and that it is still alive in
|
|
33
|
+
* between.
|
|
34
|
+
*
|
|
35
|
+
* Call it before the server connects to its transport. A signal that fails is dropped: the app may
|
|
36
|
+
* not be running, or may be a version without agent sessions.
|
|
37
|
+
*
|
|
38
|
+
* @param server - The MCP server whose client is the agent
|
|
39
|
+
* @param stdin - The stream whose end means the client has gone. A termination signal ends the
|
|
40
|
+
* session too, and then exits the process.
|
|
41
|
+
*/
|
|
42
|
+
export function trackAgentSession(server, stdin) {
|
|
43
|
+
server.oninitialized = () => {
|
|
44
|
+
void handleInitialized(server);
|
|
45
|
+
};
|
|
46
|
+
const heartbeat = setInterval(() => {
|
|
47
|
+
void sendAgentSessionSignal('POST');
|
|
48
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
49
|
+
heartbeat.unref();
|
|
50
|
+
let ended = false;
|
|
51
|
+
const endSession = async () => {
|
|
52
|
+
if (ended) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
ended = true;
|
|
56
|
+
clearInterval(heartbeat);
|
|
57
|
+
await sendAgentSessionSignal('DELETE');
|
|
58
|
+
};
|
|
59
|
+
stdin.once('end', () => void endSession());
|
|
60
|
+
stdin.once('close', () => void endSession());
|
|
61
|
+
for (const signal of ['SIGTERM', 'SIGINT']) {
|
|
62
|
+
process.once(signal, () => {
|
|
63
|
+
void endSession().finally(() => process.exit(0));
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { buildAgentHeaders, getAgentIdentity } from './agent-identity.js';
|
|
2
|
+
const config = {
|
|
3
|
+
baseUrl: process.env.INKDROP_LOCAL_SERVER_URL,
|
|
4
|
+
username: process.env.INKDROP_LOCAL_USERNAME,
|
|
5
|
+
password: process.env.INKDROP_LOCAL_PASSWORD
|
|
6
|
+
};
|
|
7
|
+
const AGENT_SESSION_PATH = '/agent/session';
|
|
8
|
+
const AGENT_SESSION_SIGNAL_TIMEOUT_MS = 3000;
|
|
9
|
+
function getRequestHeaders() {
|
|
10
|
+
const token = Buffer.from(`${config.username}:${config.password}`).toString('base64');
|
|
11
|
+
return {
|
|
12
|
+
Authorization: `Basic ${token}`,
|
|
13
|
+
...buildAgentHeaders(getAgentIdentity())
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function buildUrl(path, qs = {}) {
|
|
17
|
+
const url = new URL(path, config.baseUrl);
|
|
18
|
+
for (const [k, v] of Object.entries(qs)) {
|
|
19
|
+
if (v !== undefined && v !== null) {
|
|
20
|
+
url.searchParams.set(k, String(v));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return url.toString();
|
|
24
|
+
}
|
|
25
|
+
export async function fetchJSON(path, qs = {}) {
|
|
26
|
+
const url = buildUrl(path, qs);
|
|
27
|
+
const resp = await fetch(url, { headers: getRequestHeaders() });
|
|
28
|
+
if (!resp.ok) {
|
|
29
|
+
throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
|
|
30
|
+
}
|
|
31
|
+
return (await resp.json());
|
|
32
|
+
}
|
|
33
|
+
export async function postJSON(path, body) {
|
|
34
|
+
const url = buildUrl(path);
|
|
35
|
+
const resp = await fetch(url, {
|
|
36
|
+
method: 'POST',
|
|
37
|
+
headers: {
|
|
38
|
+
...getRequestHeaders(),
|
|
39
|
+
'Content-Type': 'application/json'
|
|
40
|
+
},
|
|
41
|
+
body: JSON.stringify(body)
|
|
42
|
+
});
|
|
43
|
+
if (!resp.ok) {
|
|
44
|
+
throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
|
|
45
|
+
}
|
|
46
|
+
return (await resp.json());
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Tells the app that this agent session is connected (`POST`) or has ended (`DELETE`).
|
|
50
|
+
*
|
|
51
|
+
* It never rejects: a failed signal is dropped, since the app may not be running.
|
|
52
|
+
*/
|
|
53
|
+
export async function sendAgentSessionSignal(method) {
|
|
54
|
+
try {
|
|
55
|
+
await fetch(buildUrl(AGENT_SESSION_PATH), {
|
|
56
|
+
method,
|
|
57
|
+
headers: getRequestHeaders(),
|
|
58
|
+
signal: AbortSignal.timeout(AGENT_SESSION_SIGNAL_TIMEOUT_MS)
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// The app is not running, or its server is off.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { extname } from 'node:path';
|
|
2
|
+
import { SUPPORTED_IMAGE_MIME_TYPES } from 'inkdrop-model';
|
|
3
|
+
/**
|
|
4
|
+
* Infers the attachment content type from a file name or path extension.
|
|
5
|
+
*
|
|
6
|
+
* `SUPPORTED_IMAGE_MIME_TYPES` is keyed by MIME subtype, which doubles as the file
|
|
7
|
+
* extension for every supported type except SVG, whose subtype is `svg+xml`.
|
|
8
|
+
*
|
|
9
|
+
* @returns The matching image MIME type, or `undefined` when the extension is
|
|
10
|
+
* missing or not a supported attachment type
|
|
11
|
+
*/
|
|
12
|
+
export function inferImageContentType(filePath) {
|
|
13
|
+
const ext = extname(filePath).toLowerCase().replace(/^\./, '');
|
|
14
|
+
return SUPPORTED_IMAGE_MIME_TYPES[ext === 'svg' ? 'svg+xml' : ext];
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Content types the MCP `image` content block can carry. Inkdrop also accepts
|
|
18
|
+
* SVG and HEIC/HEIF attachments, which have to be written to disk instead.
|
|
19
|
+
*/
|
|
20
|
+
const VIEWABLE_IMAGE_TYPES = new Set([
|
|
21
|
+
'image/png',
|
|
22
|
+
'image/jpeg',
|
|
23
|
+
'image/jpg',
|
|
24
|
+
'image/gif'
|
|
25
|
+
]);
|
|
26
|
+
/**
|
|
27
|
+
* Whether an attachment can be returned as an MCP `image` content block.
|
|
28
|
+
*/
|
|
29
|
+
export function isViewableImageType(contentType) {
|
|
30
|
+
return contentType !== undefined && VIEWABLE_IMAGE_TYPES.has(contentType);
|
|
31
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename } from 'node:path';
|
|
4
|
+
import { getFileUri } from '@inkdropapp/protocol-utils';
|
|
5
|
+
import { maxAttachmentFileSize, supportedImageFileTypes } from 'inkdrop-model';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { fetchJSON, postJSON } from '../../client/local-server.js';
|
|
8
|
+
import { inferImageContentType, isViewableImageType } from './image-type.js';
|
|
9
|
+
const ImageFileTypes = [...supportedImageFileTypes];
|
|
10
|
+
/**
|
|
11
|
+
* Registers the tools that create and read attachment files.
|
|
12
|
+
*
|
|
13
|
+
* @param server - The MCP server to register on
|
|
14
|
+
*/
|
|
15
|
+
export function registerFileTools(server) {
|
|
16
|
+
server.registerTool('create-file', {
|
|
17
|
+
description: 'Create a new attachment file in the database from a local image file or from base64 image data. ' +
|
|
18
|
+
'Returns the Markdown to embed the attachment in a note body. ' +
|
|
19
|
+
'Prefer `filePath` over `data`: it keeps the image bytes out of the conversation.',
|
|
20
|
+
inputSchema: {
|
|
21
|
+
filePath: z
|
|
22
|
+
.string()
|
|
23
|
+
.optional()
|
|
24
|
+
.describe('Absolute path to a local image file to attach. Either this or `data` must be given.'),
|
|
25
|
+
data: z
|
|
26
|
+
.string()
|
|
27
|
+
.optional()
|
|
28
|
+
.describe('Base64-encoded image data, without a `data:` URI prefix. Use `filePath` instead whenever the image is already on disk.'),
|
|
29
|
+
name: z
|
|
30
|
+
.string()
|
|
31
|
+
.min(1)
|
|
32
|
+
.max(128)
|
|
33
|
+
.optional()
|
|
34
|
+
.describe('The file name. Defaults to the file name of `filePath`, or `image.<ext>` when `data` is given.'),
|
|
35
|
+
contentType: z
|
|
36
|
+
.enum(ImageFileTypes)
|
|
37
|
+
.optional()
|
|
38
|
+
.describe('The MIME type of the image. Inferred from the `filePath` extension when omitted, so it is required with `data`.')
|
|
39
|
+
}
|
|
40
|
+
}, async ({ filePath, data, name, contentType }) => {
|
|
41
|
+
if ((filePath === undefined) === (data === undefined)) {
|
|
42
|
+
return {
|
|
43
|
+
content: [
|
|
44
|
+
{
|
|
45
|
+
type: 'text',
|
|
46
|
+
text: 'Failed to create the attachment: provide exactly one of `filePath` or `data`.'
|
|
47
|
+
}
|
|
48
|
+
],
|
|
49
|
+
isError: true
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
let buffer;
|
|
53
|
+
if (filePath !== undefined) {
|
|
54
|
+
try {
|
|
55
|
+
buffer = await readFile(filePath);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
return {
|
|
59
|
+
content: [
|
|
60
|
+
{
|
|
61
|
+
type: 'text',
|
|
62
|
+
text: `Failed to read the file at ${filePath}: ${error.message}`
|
|
63
|
+
}
|
|
64
|
+
],
|
|
65
|
+
isError: true
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
contentType ??= inferImageContentType(filePath);
|
|
69
|
+
name ??= basename(filePath);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
buffer = Buffer.from(data, 'base64');
|
|
73
|
+
}
|
|
74
|
+
if (!contentType) {
|
|
75
|
+
return {
|
|
76
|
+
content: [
|
|
77
|
+
{
|
|
78
|
+
type: 'text',
|
|
79
|
+
text: `Failed to create the attachment: could not infer the content type${filePath ? ` from ${filePath}` : ''}. Pass \`contentType\` explicitly. Supported types: ${supportedImageFileTypes.join(', ')}.`
|
|
80
|
+
}
|
|
81
|
+
],
|
|
82
|
+
isError: true
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const base64 = buffer.toString('base64');
|
|
86
|
+
const contentLength = Math.floor((base64.length * 3) / 4);
|
|
87
|
+
if (contentLength > maxAttachmentFileSize) {
|
|
88
|
+
return {
|
|
89
|
+
content: [
|
|
90
|
+
{
|
|
91
|
+
type: 'text',
|
|
92
|
+
text: `Failed to create the attachment: the file is ${contentLength} bytes, over the ${maxAttachmentFileSize} byte limit.`
|
|
93
|
+
}
|
|
94
|
+
],
|
|
95
|
+
isError: true
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const res = await postJSON('/files', {
|
|
99
|
+
name: name ?? `image.${contentType.replace(/^image\//, '')}`,
|
|
100
|
+
contentType,
|
|
101
|
+
contentLength,
|
|
102
|
+
publicIn: [],
|
|
103
|
+
md5digest: createHash('md5').update(buffer).digest('hex'),
|
|
104
|
+
_attachments: {
|
|
105
|
+
index: {
|
|
106
|
+
content_type: contentType,
|
|
107
|
+
data: base64
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
return {
|
|
112
|
+
content: [
|
|
113
|
+
{
|
|
114
|
+
type: 'text',
|
|
115
|
+
text: JSON.stringify(res, null, 2)
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
type: 'text',
|
|
119
|
+
text: `Markdown to embed this attachment in a note body:\n\n})`
|
|
120
|
+
}
|
|
121
|
+
]
|
|
122
|
+
};
|
|
123
|
+
});
|
|
124
|
+
server.registerTool('read-file', {
|
|
125
|
+
description: 'Retrieve an attachment file by its ID. Returns the file metadata, and the image itself when it is a PNG, JPEG or GIF. ' +
|
|
126
|
+
'Pass `outputPath` to write the attachment to disk instead — required to get at SVG, HEIC and HEIF attachments, which cannot be displayed inline.',
|
|
127
|
+
inputSchema: {
|
|
128
|
+
fileId: z
|
|
129
|
+
.string()
|
|
130
|
+
.describe('ID of the attachment to retrieve. It can be found as `_id` in the file docs. It always starts with `file:`.'),
|
|
131
|
+
outputPath: z
|
|
132
|
+
.string()
|
|
133
|
+
.optional()
|
|
134
|
+
.describe('Absolute path to write the attachment to. When given, the file is saved there and its bytes are not returned inline.'),
|
|
135
|
+
includeImage: z
|
|
136
|
+
.boolean()
|
|
137
|
+
.optional()
|
|
138
|
+
.default(true)
|
|
139
|
+
.describe('Whether to return the image itself alongside the metadata. Set to false to fetch only the metadata of a large attachment.')
|
|
140
|
+
}
|
|
141
|
+
}, async ({ fileId, outputPath, includeImage }) => {
|
|
142
|
+
if (!fileId.startsWith('file:')) {
|
|
143
|
+
fileId = `file:${fileId}`;
|
|
144
|
+
}
|
|
145
|
+
const needsData = includeImage || outputPath !== undefined;
|
|
146
|
+
const file = await fetchJSON(`/${fileId}`, {
|
|
147
|
+
attachments: needsData ? true : undefined
|
|
148
|
+
});
|
|
149
|
+
const { _attachments, ...metadata } = file;
|
|
150
|
+
const base64 = typeof _attachments?.index?.data === 'string' ? _attachments.index.data : undefined;
|
|
151
|
+
const attachmentBlock = async () => {
|
|
152
|
+
if (!needsData) {
|
|
153
|
+
return [];
|
|
154
|
+
}
|
|
155
|
+
if (!base64) {
|
|
156
|
+
return [
|
|
157
|
+
{
|
|
158
|
+
type: 'text',
|
|
159
|
+
text: 'The attachment data could not be read from the document.'
|
|
160
|
+
}
|
|
161
|
+
];
|
|
162
|
+
}
|
|
163
|
+
if (outputPath !== undefined) {
|
|
164
|
+
await writeFile(outputPath, Buffer.from(base64, 'base64'));
|
|
165
|
+
return [{ type: 'text', text: `Attachment written to ${outputPath}` }];
|
|
166
|
+
}
|
|
167
|
+
if (!isViewableImageType(file.contentType)) {
|
|
168
|
+
return [
|
|
169
|
+
{
|
|
170
|
+
type: 'text',
|
|
171
|
+
text: `The attachment is a ${file.contentType} file, which cannot be displayed inline. Pass \`outputPath\` to write it to disk.`
|
|
172
|
+
}
|
|
173
|
+
];
|
|
174
|
+
}
|
|
175
|
+
return [
|
|
176
|
+
{
|
|
177
|
+
type: 'image',
|
|
178
|
+
data: base64,
|
|
179
|
+
// `image/jpg` is not a real MIME type; the image block expects `image/jpeg`.
|
|
180
|
+
mimeType: file.contentType === 'image/jpg' ? 'image/jpeg' : file.contentType
|
|
181
|
+
}
|
|
182
|
+
];
|
|
183
|
+
};
|
|
184
|
+
return {
|
|
185
|
+
content: [
|
|
186
|
+
{ type: 'text', text: JSON.stringify(metadata, null, 2) },
|
|
187
|
+
...(await attachmentBlock())
|
|
188
|
+
]
|
|
189
|
+
};
|
|
190
|
+
});
|
|
191
|
+
}
|