@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
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/**
|
|
3
|
+
* Builds the ID schema for one kind of Inkdrop document.
|
|
4
|
+
*
|
|
5
|
+
* @param idPrefix - The prefix every ID of that kind starts with, e.g. `note:`
|
|
6
|
+
* @returns A schema that accepts an ID with that prefix, within the length Inkdrop allows
|
|
7
|
+
*/
|
|
8
|
+
export function documentIdSchema(idPrefix) {
|
|
9
|
+
return z
|
|
10
|
+
.string()
|
|
11
|
+
.min(6)
|
|
12
|
+
.max(128)
|
|
13
|
+
.regex(new RegExp(`^${idPrefix}`));
|
|
14
|
+
}
|
|
15
|
+
/** A CouchDB revision token of a document. */
|
|
16
|
+
export const revisionSchema = z.string();
|
|
17
|
+
/** A point in time as a Unix timestamp in milliseconds. */
|
|
18
|
+
export const timestampSchema = z.number().int().nonnegative();
|
package/mise.toml
ADDED
package/oxlint.config.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import nkzw from '@nkzw/oxlint-config'
|
|
2
|
+
import { defineConfig } from 'oxlint'
|
|
3
|
+
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
extends: [nkzw],
|
|
6
|
+
ignorePatterns: ['node_modules/**', 'dist/**'],
|
|
7
|
+
overrides: [
|
|
8
|
+
{
|
|
9
|
+
// The stdio transport owns stdout, so stderr is the server's only log channel.
|
|
10
|
+
files: ['src/index.ts'],
|
|
11
|
+
rules: {
|
|
12
|
+
'no-console': ['error', { allow: ['error'] }]
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
files: ['src/features/**'],
|
|
17
|
+
rules: {
|
|
18
|
+
'no-restricted-imports': [
|
|
19
|
+
'error',
|
|
20
|
+
{
|
|
21
|
+
patterns: [
|
|
22
|
+
{
|
|
23
|
+
regex: String.raw`^(\.\./[^./][^/]*/|(\.\./)+features/)`,
|
|
24
|
+
message:
|
|
25
|
+
'A feature must not import another feature. Move what both need to src/utils if it is domain-free, or pass it in from src/index.ts.'
|
|
26
|
+
}
|
|
27
|
+
]
|
|
28
|
+
}
|
|
29
|
+
]
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
files: ['src/utils/**', 'src/client/**'],
|
|
34
|
+
rules: {
|
|
35
|
+
'no-restricted-imports': [
|
|
36
|
+
'error',
|
|
37
|
+
{
|
|
38
|
+
patterns: [
|
|
39
|
+
{
|
|
40
|
+
regex: String.raw`^(\.\.?/)+features(/|$)`,
|
|
41
|
+
message:
|
|
42
|
+
'Shared code must not import a feature. Keep feature-specific code in its folder under src/features.'
|
|
43
|
+
}
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
]
|
|
50
|
+
})
|
package/package.json
CHANGED
|
@@ -1,10 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inkdropapp/mcp-server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.0-beta.0",
|
|
4
4
|
"description": "Inkdrop Model Context Protocol Server",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"Claude",
|
|
7
|
+
"Inkdrop",
|
|
8
|
+
"MCP"
|
|
9
|
+
],
|
|
10
|
+
"license": "Apache-2.0",
|
|
11
|
+
"author": "Takuya Matsuyama<contact@inkdrop.app>",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "https://github.com/inkdropapp/mcp-server.git"
|
|
15
|
+
},
|
|
5
16
|
"bin": {
|
|
6
17
|
"inkdrop-mcp-server": "dist/index.js"
|
|
7
18
|
},
|
|
19
|
+
"type": "module",
|
|
8
20
|
"scripts": {
|
|
9
21
|
"start": "bun src/index.ts",
|
|
10
22
|
"build": "tsc && chmod +x dist/*.js",
|
|
@@ -12,28 +24,24 @@
|
|
|
12
24
|
"watch": "tsc --watch",
|
|
13
25
|
"format": "oxfmt",
|
|
14
26
|
"format:check": "oxfmt --check",
|
|
15
|
-
"
|
|
27
|
+
"lint": "oxlint",
|
|
28
|
+
"typecheck": "tsc --noEmit",
|
|
29
|
+
"test": "bun test"
|
|
16
30
|
},
|
|
17
|
-
"repository": {
|
|
18
|
-
"type": "git",
|
|
19
|
-
"url": "https://github.com/inkdropapp/mcp-server.git"
|
|
20
|
-
},
|
|
21
|
-
"keywords": [
|
|
22
|
-
"Inkdrop",
|
|
23
|
-
"MCP",
|
|
24
|
-
"Claude"
|
|
25
|
-
],
|
|
26
|
-
"author": "Takuya Matsuyama<contact@inkdrop.app>",
|
|
27
|
-
"license": "Apache-2.0",
|
|
28
31
|
"dependencies": {
|
|
32
|
+
"@inkdropapp/protocol-utils": "^1.0.1",
|
|
29
33
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
30
34
|
"ajv": "^8.20.0",
|
|
35
|
+
"inkdrop-consts": "^3.2.3",
|
|
31
36
|
"inkdrop-model": "^3.0.1",
|
|
32
37
|
"zod": "^4.6.7"
|
|
33
38
|
},
|
|
34
39
|
"devDependencies": {
|
|
40
|
+
"@nkzw/oxlint-config": "^3.0.0",
|
|
35
41
|
"@types/node": "^26.6.6",
|
|
36
|
-
"oxfmt": "^0.
|
|
42
|
+
"oxfmt": "^0.78.0",
|
|
43
|
+
"oxlint": "^1.94.0",
|
|
44
|
+
"tsrs": "7.1.0-beta.tsrs3",
|
|
37
45
|
"typescript": "^7.0.2"
|
|
38
46
|
}
|
|
39
47
|
}
|
package/pnpm-workspace.yaml
CHANGED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
import { AGENT_HEADERS } from 'inkdrop-consts'
|
|
4
|
+
|
|
5
|
+
const MAX_VALUE_LENGTH = 128
|
|
6
|
+
|
|
7
|
+
export type AgentClient = {
|
|
8
|
+
name: string
|
|
9
|
+
title?: string
|
|
10
|
+
version?: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type AgentIdentity = {
|
|
14
|
+
sessionId: string
|
|
15
|
+
client?: AgentClient
|
|
16
|
+
/** A display name of the folder the client works in. */
|
|
17
|
+
workspace?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type Root = { uri: string; name?: string }
|
|
21
|
+
|
|
22
|
+
function encodeHeaderValue(value: string): string {
|
|
23
|
+
return encodeURIComponent(value.slice(0, MAX_VALUE_LENGTH).toWellFormed())
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Builds the identity headers of a request.
|
|
28
|
+
*
|
|
29
|
+
* Each value is cut to 128 UTF-16 code units and percent-encoded, since a header value cannot carry
|
|
30
|
+
* line breaks or characters outside Latin-1.
|
|
31
|
+
*/
|
|
32
|
+
export function buildAgentHeaders(identity: AgentIdentity): Record<string, string> {
|
|
33
|
+
const values: Array<[string, string | undefined]> = [
|
|
34
|
+
[AGENT_HEADERS.session, identity.sessionId],
|
|
35
|
+
[AGENT_HEADERS.clientName, identity.client?.name],
|
|
36
|
+
[AGENT_HEADERS.clientTitle, identity.client?.title],
|
|
37
|
+
[AGENT_HEADERS.clientVersion, identity.client?.version],
|
|
38
|
+
[AGENT_HEADERS.workspace, identity.workspace]
|
|
39
|
+
]
|
|
40
|
+
return Object.fromEntries(
|
|
41
|
+
values.flatMap(([header, value]) => (value ? [[header, encodeHeaderValue(value)]] : []))
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Picks a display name for an MCP root: the name the client gave it, or the last folder of its URI.
|
|
47
|
+
*
|
|
48
|
+
* @returns `undefined` when the URI is malformed or names no folder
|
|
49
|
+
*/
|
|
50
|
+
export function workspaceNameFromRoot(root: Root): string | undefined {
|
|
51
|
+
if (root.name) {
|
|
52
|
+
return root.name
|
|
53
|
+
}
|
|
54
|
+
if (!URL.canParse(root.uri)) {
|
|
55
|
+
return undefined
|
|
56
|
+
}
|
|
57
|
+
const lastSegment = new URL(root.uri).pathname.split('/').findLast(segment => segment !== '')
|
|
58
|
+
return lastSegment ? decodeURIComponent(lastSegment) : undefined
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let currentIdentity: AgentIdentity = { sessionId: randomUUID() }
|
|
62
|
+
|
|
63
|
+
export function getAgentIdentity(): AgentIdentity {
|
|
64
|
+
return currentIdentity
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Adds what the MCP handshake told about the client to the identity of this process. */
|
|
68
|
+
export function updateAgentIdentity(update: Pick<AgentIdentity, 'client' | 'workspace'>): void {
|
|
69
|
+
currentIdentity = { ...currentIdentity, ...update }
|
|
70
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
2
|
+
|
|
3
|
+
import { updateAgentIdentity, workspaceNameFromRoot } from './agent-identity.js'
|
|
4
|
+
import { sendAgentSessionSignal } from './local-server.js'
|
|
5
|
+
|
|
6
|
+
const HEARTBEAT_INTERVAL_MS = 60_000
|
|
7
|
+
|
|
8
|
+
async function readWorkspaceName(server: Server): Promise<string | undefined> {
|
|
9
|
+
if (!server.getClientCapabilities()?.roots) {
|
|
10
|
+
return undefined
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
const { roots } = await server.listRoots()
|
|
14
|
+
const firstRoot = roots[0]
|
|
15
|
+
return firstRoot ? workspaceNameFromRoot(firstRoot) : undefined
|
|
16
|
+
} catch {
|
|
17
|
+
return undefined
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function handleInitialized(server: Server): Promise<void> {
|
|
22
|
+
const client = server.getClientVersion()
|
|
23
|
+
if (client) {
|
|
24
|
+
updateAgentIdentity({
|
|
25
|
+
client: { name: client.name, title: client.title, version: client.version }
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
await sendAgentSessionSignal('POST')
|
|
29
|
+
|
|
30
|
+
const workspace = await readWorkspaceName(server)
|
|
31
|
+
if (workspace) {
|
|
32
|
+
updateAgentIdentity({ workspace })
|
|
33
|
+
await sendAgentSessionSignal('POST')
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Tells the Inkdrop app when this agent session starts and ends, and that it is still alive in
|
|
39
|
+
* between.
|
|
40
|
+
*
|
|
41
|
+
* Call it before the server connects to its transport. A signal that fails is dropped: the app may
|
|
42
|
+
* not be running, or may be a version without agent sessions.
|
|
43
|
+
*
|
|
44
|
+
* @param server - The MCP server whose client is the agent
|
|
45
|
+
* @param stdin - The stream whose end means the client has gone. A termination signal ends the
|
|
46
|
+
* session too, and then exits the process.
|
|
47
|
+
*/
|
|
48
|
+
export function trackAgentSession(server: Server, stdin: NodeJS.ReadableStream): void {
|
|
49
|
+
server.oninitialized = () => {
|
|
50
|
+
void handleInitialized(server)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const heartbeat = setInterval(() => {
|
|
54
|
+
void sendAgentSessionSignal('POST')
|
|
55
|
+
}, HEARTBEAT_INTERVAL_MS)
|
|
56
|
+
heartbeat.unref()
|
|
57
|
+
|
|
58
|
+
let ended = false
|
|
59
|
+
const endSession = async () => {
|
|
60
|
+
if (ended) {
|
|
61
|
+
return
|
|
62
|
+
}
|
|
63
|
+
ended = true
|
|
64
|
+
clearInterval(heartbeat)
|
|
65
|
+
await sendAgentSessionSignal('DELETE')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
stdin.once('end', () => void endSession())
|
|
69
|
+
stdin.once('close', () => void endSession())
|
|
70
|
+
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
|
|
71
|
+
process.once(signal, () => {
|
|
72
|
+
void endSession().finally(() => process.exit(0))
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { buildAgentHeaders, getAgentIdentity } from './agent-identity.js'
|
|
2
|
+
|
|
3
|
+
const config = {
|
|
4
|
+
baseUrl: process.env.INKDROP_LOCAL_SERVER_URL,
|
|
5
|
+
username: process.env.INKDROP_LOCAL_USERNAME,
|
|
6
|
+
password: process.env.INKDROP_LOCAL_PASSWORD
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const AGENT_SESSION_PATH = '/agent/session'
|
|
10
|
+
const AGENT_SESSION_SIGNAL_TIMEOUT_MS = 3000
|
|
11
|
+
|
|
12
|
+
function getRequestHeaders() {
|
|
13
|
+
const token = Buffer.from(`${config.username}:${config.password}`).toString('base64')
|
|
14
|
+
return {
|
|
15
|
+
Authorization: `Basic ${token}`,
|
|
16
|
+
...buildAgentHeaders(getAgentIdentity())
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Query string parameters. A `null` or `undefined` value leaves the parameter out. */
|
|
21
|
+
export type QueryParams = Record<string, string | number | boolean | null | undefined>
|
|
22
|
+
|
|
23
|
+
export function buildUrl(path: string, qs: QueryParams = {}): string {
|
|
24
|
+
const url = new URL(path, config.baseUrl)
|
|
25
|
+
for (const [k, v] of Object.entries(qs)) {
|
|
26
|
+
if (v !== undefined && v !== null) {
|
|
27
|
+
url.searchParams.set(k, String(v))
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return url.toString()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function fetchJSON<T = unknown>(path: string, qs: QueryParams = {}): Promise<T> {
|
|
34
|
+
const url = buildUrl(path, qs)
|
|
35
|
+
const resp = await fetch(url, { headers: getRequestHeaders() })
|
|
36
|
+
if (!resp.ok) {
|
|
37
|
+
throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`)
|
|
38
|
+
}
|
|
39
|
+
return (await resp.json()) as T
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function postJSON<T = unknown>(path: string, body: unknown): Promise<T> {
|
|
43
|
+
const url = buildUrl(path)
|
|
44
|
+
const resp = await fetch(url, {
|
|
45
|
+
method: 'POST',
|
|
46
|
+
headers: {
|
|
47
|
+
...getRequestHeaders(),
|
|
48
|
+
'Content-Type': 'application/json'
|
|
49
|
+
},
|
|
50
|
+
body: JSON.stringify(body)
|
|
51
|
+
})
|
|
52
|
+
if (!resp.ok) {
|
|
53
|
+
throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`)
|
|
54
|
+
}
|
|
55
|
+
return (await resp.json()) as T
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Tells the app that this agent session is connected (`POST`) or has ended (`DELETE`).
|
|
60
|
+
*
|
|
61
|
+
* It never rejects: a failed signal is dropped, since the app may not be running.
|
|
62
|
+
*/
|
|
63
|
+
export async function sendAgentSessionSignal(method: 'POST' | 'DELETE'): Promise<void> {
|
|
64
|
+
try {
|
|
65
|
+
await fetch(buildUrl(AGENT_SESSION_PATH), {
|
|
66
|
+
method,
|
|
67
|
+
headers: getRequestHeaders(),
|
|
68
|
+
signal: AbortSignal.timeout(AGENT_SESSION_SIGNAL_TIMEOUT_MS)
|
|
69
|
+
})
|
|
70
|
+
} catch {
|
|
71
|
+
// The app is not running, or its server is off.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { extname } from 'node:path'
|
|
2
|
+
|
|
3
|
+
import { SUPPORTED_IMAGE_MIME_TYPES, type ImageFileType } from 'inkdrop-model'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Infers the attachment content type from a file name or path extension.
|
|
7
|
+
*
|
|
8
|
+
* `SUPPORTED_IMAGE_MIME_TYPES` is keyed by MIME subtype, which doubles as the file
|
|
9
|
+
* extension for every supported type except SVG, whose subtype is `svg+xml`.
|
|
10
|
+
*
|
|
11
|
+
* @returns The matching image MIME type, or `undefined` when the extension is
|
|
12
|
+
* missing or not a supported attachment type
|
|
13
|
+
*/
|
|
14
|
+
export function inferImageContentType(filePath: string): ImageFileType | undefined {
|
|
15
|
+
const ext = extname(filePath).toLowerCase().replace(/^\./, '')
|
|
16
|
+
return SUPPORTED_IMAGE_MIME_TYPES[ext === 'svg' ? 'svg+xml' : ext]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Content types the MCP `image` content block can carry. Inkdrop also accepts
|
|
21
|
+
* SVG and HEIC/HEIF attachments, which have to be written to disk instead.
|
|
22
|
+
*/
|
|
23
|
+
const VIEWABLE_IMAGE_TYPES = new Set<ImageFileType>([
|
|
24
|
+
'image/png',
|
|
25
|
+
'image/jpeg',
|
|
26
|
+
'image/jpg',
|
|
27
|
+
'image/gif'
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Whether an attachment can be returned as an MCP `image` content block.
|
|
32
|
+
*/
|
|
33
|
+
export function isViewableImageType(contentType: ImageFileType | undefined): boolean {
|
|
34
|
+
return contentType !== undefined && VIEWABLE_IMAGE_TYPES.has(contentType)
|
|
35
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { readFile, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { basename } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import { getFileUri } from '@inkdropapp/protocol-utils'
|
|
6
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
|
7
|
+
import { maxAttachmentFileSize, supportedImageFileTypes, type File as IDFile } from 'inkdrop-model'
|
|
8
|
+
import { z } from 'zod'
|
|
9
|
+
|
|
10
|
+
import { fetchJSON, postJSON } from '../../client/local-server.js'
|
|
11
|
+
import { inferImageContentType, isViewableImageType } from './image-type.js'
|
|
12
|
+
|
|
13
|
+
const ImageFileTypes = [...supportedImageFileTypes] as [string, ...Array<string>]
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Registers the tools that create and read attachment files.
|
|
17
|
+
*
|
|
18
|
+
* @param server - The MCP server to register on
|
|
19
|
+
*/
|
|
20
|
+
export function registerFileTools(server: McpServer): void {
|
|
21
|
+
server.registerTool(
|
|
22
|
+
'create-file',
|
|
23
|
+
{
|
|
24
|
+
description:
|
|
25
|
+
'Create a new attachment file in the database from a local image file or from base64 image data. ' +
|
|
26
|
+
'Returns the Markdown to embed the attachment in a note body. ' +
|
|
27
|
+
'Prefer `filePath` over `data`: it keeps the image bytes out of the conversation.',
|
|
28
|
+
inputSchema: {
|
|
29
|
+
filePath: z
|
|
30
|
+
.string()
|
|
31
|
+
.optional()
|
|
32
|
+
.describe(
|
|
33
|
+
'Absolute path to a local image file to attach. Either this or `data` must be given.'
|
|
34
|
+
),
|
|
35
|
+
data: z
|
|
36
|
+
.string()
|
|
37
|
+
.optional()
|
|
38
|
+
.describe(
|
|
39
|
+
'Base64-encoded image data, without a `data:` URI prefix. Use `filePath` instead whenever the image is already on disk.'
|
|
40
|
+
),
|
|
41
|
+
name: z
|
|
42
|
+
.string()
|
|
43
|
+
.min(1)
|
|
44
|
+
.max(128)
|
|
45
|
+
.optional()
|
|
46
|
+
.describe(
|
|
47
|
+
'The file name. Defaults to the file name of `filePath`, or `image.<ext>` when `data` is given.'
|
|
48
|
+
),
|
|
49
|
+
contentType: z
|
|
50
|
+
.enum(ImageFileTypes)
|
|
51
|
+
.optional()
|
|
52
|
+
.describe(
|
|
53
|
+
'The MIME type of the image. Inferred from the `filePath` extension when omitted, so it is required with `data`.'
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
async ({ filePath, data, name, contentType }) => {
|
|
58
|
+
if ((filePath === undefined) === (data === undefined)) {
|
|
59
|
+
return {
|
|
60
|
+
content: [
|
|
61
|
+
{
|
|
62
|
+
type: 'text',
|
|
63
|
+
text: 'Failed to create the attachment: provide exactly one of `filePath` or `data`.'
|
|
64
|
+
}
|
|
65
|
+
],
|
|
66
|
+
isError: true
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
let buffer: Buffer
|
|
71
|
+
if (filePath !== undefined) {
|
|
72
|
+
try {
|
|
73
|
+
buffer = await readFile(filePath)
|
|
74
|
+
} catch (error) {
|
|
75
|
+
return {
|
|
76
|
+
content: [
|
|
77
|
+
{
|
|
78
|
+
type: 'text',
|
|
79
|
+
text: `Failed to read the file at ${filePath}: ${(error as Error).message}`
|
|
80
|
+
}
|
|
81
|
+
],
|
|
82
|
+
isError: true
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
contentType ??= inferImageContentType(filePath)
|
|
86
|
+
name ??= basename(filePath)
|
|
87
|
+
} else {
|
|
88
|
+
buffer = Buffer.from(data!, 'base64')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (!contentType) {
|
|
92
|
+
return {
|
|
93
|
+
content: [
|
|
94
|
+
{
|
|
95
|
+
type: 'text',
|
|
96
|
+
text: `Failed to create the attachment: could not infer the content type${
|
|
97
|
+
filePath ? ` from ${filePath}` : ''
|
|
98
|
+
}. Pass \`contentType\` explicitly. Supported types: ${supportedImageFileTypes.join(', ')}.`
|
|
99
|
+
}
|
|
100
|
+
],
|
|
101
|
+
isError: true
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const base64 = buffer.toString('base64')
|
|
106
|
+
const contentLength = Math.floor((base64.length * 3) / 4)
|
|
107
|
+
if (contentLength > maxAttachmentFileSize) {
|
|
108
|
+
return {
|
|
109
|
+
content: [
|
|
110
|
+
{
|
|
111
|
+
type: 'text',
|
|
112
|
+
text: `Failed to create the attachment: the file is ${contentLength} bytes, over the ${maxAttachmentFileSize} byte limit.`
|
|
113
|
+
}
|
|
114
|
+
],
|
|
115
|
+
isError: true
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const res = await postJSON<{ id: string; ok: boolean; rev: string }>('/files', {
|
|
120
|
+
name: name ?? `image.${contentType.replace(/^image\//, '')}`,
|
|
121
|
+
contentType,
|
|
122
|
+
contentLength,
|
|
123
|
+
publicIn: [],
|
|
124
|
+
md5digest: createHash('md5').update(buffer).digest('hex'),
|
|
125
|
+
_attachments: {
|
|
126
|
+
index: {
|
|
127
|
+
content_type: contentType,
|
|
128
|
+
data: base64
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
content: [
|
|
135
|
+
{
|
|
136
|
+
type: 'text',
|
|
137
|
+
text: JSON.stringify(res, null, 2)
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
type: 'text',
|
|
141
|
+
text: `Markdown to embed this attachment in a note body:\n\n})`
|
|
142
|
+
}
|
|
143
|
+
]
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
server.registerTool(
|
|
149
|
+
'read-file',
|
|
150
|
+
{
|
|
151
|
+
description:
|
|
152
|
+
'Retrieve an attachment file by its ID. Returns the file metadata, and the image itself when it is a PNG, JPEG or GIF. ' +
|
|
153
|
+
'Pass `outputPath` to write the attachment to disk instead — required to get at SVG, HEIC and HEIF attachments, which cannot be displayed inline.',
|
|
154
|
+
inputSchema: {
|
|
155
|
+
fileId: z
|
|
156
|
+
.string()
|
|
157
|
+
.describe(
|
|
158
|
+
'ID of the attachment to retrieve. It can be found as `_id` in the file docs. It always starts with `file:`.'
|
|
159
|
+
),
|
|
160
|
+
outputPath: z
|
|
161
|
+
.string()
|
|
162
|
+
.optional()
|
|
163
|
+
.describe(
|
|
164
|
+
'Absolute path to write the attachment to. When given, the file is saved there and its bytes are not returned inline.'
|
|
165
|
+
),
|
|
166
|
+
includeImage: z
|
|
167
|
+
.boolean()
|
|
168
|
+
.optional()
|
|
169
|
+
.default(true)
|
|
170
|
+
.describe(
|
|
171
|
+
'Whether to return the image itself alongside the metadata. Set to false to fetch only the metadata of a large attachment.'
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
async ({ fileId, outputPath, includeImage }) => {
|
|
176
|
+
if (!fileId.startsWith('file:')) {
|
|
177
|
+
fileId = `file:${fileId}`
|
|
178
|
+
}
|
|
179
|
+
const needsData = includeImage || outputPath !== undefined
|
|
180
|
+
const file = await fetchJSON<IDFile>(`/${fileId}`, {
|
|
181
|
+
attachments: needsData ? true : undefined
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
const { _attachments, ...metadata } = file
|
|
185
|
+
const base64 =
|
|
186
|
+
typeof _attachments?.index?.data === 'string' ? _attachments.index.data : undefined
|
|
187
|
+
|
|
188
|
+
const attachmentBlock = async () => {
|
|
189
|
+
if (!needsData) {
|
|
190
|
+
return []
|
|
191
|
+
}
|
|
192
|
+
if (!base64) {
|
|
193
|
+
return [
|
|
194
|
+
{
|
|
195
|
+
type: 'text' as const,
|
|
196
|
+
text: 'The attachment data could not be read from the document.'
|
|
197
|
+
}
|
|
198
|
+
]
|
|
199
|
+
}
|
|
200
|
+
if (outputPath !== undefined) {
|
|
201
|
+
await writeFile(outputPath, Buffer.from(base64, 'base64'))
|
|
202
|
+
return [{ type: 'text' as const, text: `Attachment written to ${outputPath}` }]
|
|
203
|
+
}
|
|
204
|
+
if (!isViewableImageType(file.contentType)) {
|
|
205
|
+
return [
|
|
206
|
+
{
|
|
207
|
+
type: 'text' as const,
|
|
208
|
+
text: `The attachment is a ${file.contentType} file, which cannot be displayed inline. Pass \`outputPath\` to write it to disk.`
|
|
209
|
+
}
|
|
210
|
+
]
|
|
211
|
+
}
|
|
212
|
+
return [
|
|
213
|
+
{
|
|
214
|
+
type: 'image' as const,
|
|
215
|
+
data: base64,
|
|
216
|
+
// `image/jpg` is not a real MIME type; the image block expects `image/jpeg`.
|
|
217
|
+
mimeType: file.contentType === 'image/jpg' ? 'image/jpeg' : file.contentType
|
|
218
|
+
}
|
|
219
|
+
]
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
content: [
|
|
224
|
+
{ type: 'text' as const, text: JSON.stringify(metadata, null, 2) },
|
|
225
|
+
...(await attachmentBlock())
|
|
226
|
+
]
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
)
|
|
230
|
+
}
|