@inkdropapp/mcp-server 1.9.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.
@@ -54,7 +54,13 @@ jobs:
54
54
 
55
55
  - name: Publish
56
56
  # prepublishOnly builds dist/ with tsc, so the typecheck runs here.
57
- run: npm publish
57
+ run: |
58
+ if [[ "$TAG" == *-* ]]; then
59
+ npm publish --tag beta
60
+ else
61
+ npm publish
62
+ fi
58
63
  env:
64
+ TAG: ${{ github.ref_name }}
59
65
  # The token setup-node configures must be empty, or npm uses it instead of OIDC.
60
66
  NODE_AUTH_TOKEN: ''
@@ -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
+ }
@@ -1,12 +1,16 @@
1
+ import { buildAgentHeaders, getAgentIdentity } from './agent-identity.js';
1
2
  const config = {
2
3
  baseUrl: process.env.INKDROP_LOCAL_SERVER_URL,
3
4
  username: process.env.INKDROP_LOCAL_USERNAME,
4
5
  password: process.env.INKDROP_LOCAL_PASSWORD
5
6
  };
6
- function getAuthHeaders() {
7
+ const AGENT_SESSION_PATH = '/agent/session';
8
+ const AGENT_SESSION_SIGNAL_TIMEOUT_MS = 3000;
9
+ function getRequestHeaders() {
7
10
  const token = Buffer.from(`${config.username}:${config.password}`).toString('base64');
8
11
  return {
9
- Authorization: `Basic ${token}`
12
+ Authorization: `Basic ${token}`,
13
+ ...buildAgentHeaders(getAgentIdentity())
10
14
  };
11
15
  }
12
16
  export function buildUrl(path, qs = {}) {
@@ -20,7 +24,7 @@ export function buildUrl(path, qs = {}) {
20
24
  }
21
25
  export async function fetchJSON(path, qs = {}) {
22
26
  const url = buildUrl(path, qs);
23
- const resp = await fetch(url, { headers: getAuthHeaders() });
27
+ const resp = await fetch(url, { headers: getRequestHeaders() });
24
28
  if (!resp.ok) {
25
29
  throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`);
26
30
  }
@@ -31,7 +35,7 @@ export async function postJSON(path, body) {
31
35
  const resp = await fetch(url, {
32
36
  method: 'POST',
33
37
  headers: {
34
- ...getAuthHeaders(),
38
+ ...getRequestHeaders(),
35
39
  'Content-Type': 'application/json'
36
40
  },
37
41
  body: JSON.stringify(body)
@@ -41,3 +45,20 @@ export async function postJSON(path, body) {
41
45
  }
42
46
  return (await resp.json());
43
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
+ }
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
3
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { trackAgentSession } from './client/agent-session.js';
4
5
  import { registerFileTools } from './features/files/tools.js';
5
6
  import { registerNotebookTools } from './features/notebooks/tools.js';
6
7
  import { registerNoteResource } from './features/notes/resource.js';
@@ -15,6 +16,7 @@ registerNoteTools(server);
15
16
  registerTagTools(server);
16
17
  registerNotebookTools(server);
17
18
  registerFileTools(server);
19
+ trackAgentSession(server.server, process.stdin);
18
20
  try {
19
21
  await server.connect(new StdioServerTransport());
20
22
  console.error('Secure MCP Inkdrop Server running on stdio');
package/mise.toml ADDED
@@ -0,0 +1,5 @@
1
+ [env]
2
+ INKDROP_MCP_ENTRY = "{{config_root}}/dist/index.js"
3
+ INKDROP_LOCAL_SERVER_URL = "http://localhost:19841"
4
+ INKDROP_LOCAL_USERNAME = "foo@bar.com"
5
+ INKDROP_LOCAL_PASSWORD = "bar"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkdropapp/mcp-server",
3
- "version": "1.9.0",
3
+ "version": "1.10.0-beta.0",
4
4
  "description": "Inkdrop Model Context Protocol Server",
5
5
  "keywords": [
6
6
  "Claude",
@@ -32,6 +32,7 @@
32
32
  "@inkdropapp/protocol-utils": "^1.0.1",
33
33
  "@modelcontextprotocol/sdk": "^1.32.2",
34
34
  "ajv": "^8.20.0",
35
+ "inkdrop-consts": "^3.2.3",
35
36
  "inkdrop-model": "^3.0.1",
36
37
  "zod": "^4.6.7"
37
38
  },
@@ -1,6 +1,7 @@
1
1
  minimumReleaseAgeExclude:
2
2
  - '@inkdropapp/*'
3
3
  - inkdrop-model
4
+ - inkdrop-consts
4
5
  - '@nkzw/oxlint-config'
5
6
  - 'oxlint'
6
7
  - '@oxlint/*'
@@ -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
+ }
@@ -1,13 +1,19 @@
1
+ import { buildAgentHeaders, getAgentIdentity } from './agent-identity.js'
2
+
1
3
  const config = {
2
4
  baseUrl: process.env.INKDROP_LOCAL_SERVER_URL,
3
5
  username: process.env.INKDROP_LOCAL_USERNAME,
4
6
  password: process.env.INKDROP_LOCAL_PASSWORD
5
7
  }
6
8
 
7
- function getAuthHeaders() {
9
+ const AGENT_SESSION_PATH = '/agent/session'
10
+ const AGENT_SESSION_SIGNAL_TIMEOUT_MS = 3000
11
+
12
+ function getRequestHeaders() {
8
13
  const token = Buffer.from(`${config.username}:${config.password}`).toString('base64')
9
14
  return {
10
- Authorization: `Basic ${token}`
15
+ Authorization: `Basic ${token}`,
16
+ ...buildAgentHeaders(getAgentIdentity())
11
17
  }
12
18
  }
13
19
 
@@ -26,7 +32,7 @@ export function buildUrl(path: string, qs: QueryParams = {}): string {
26
32
 
27
33
  export async function fetchJSON<T = unknown>(path: string, qs: QueryParams = {}): Promise<T> {
28
34
  const url = buildUrl(path, qs)
29
- const resp = await fetch(url, { headers: getAuthHeaders() })
35
+ const resp = await fetch(url, { headers: getRequestHeaders() })
30
36
  if (!resp.ok) {
31
37
  throw new Error(`Fetch error [${resp.status}] ${resp.statusText}`)
32
38
  }
@@ -38,7 +44,7 @@ export async function postJSON<T = unknown>(path: string, body: unknown): Promis
38
44
  const resp = await fetch(url, {
39
45
  method: 'POST',
40
46
  headers: {
41
- ...getAuthHeaders(),
47
+ ...getRequestHeaders(),
42
48
  'Content-Type': 'application/json'
43
49
  },
44
50
  body: JSON.stringify(body)
@@ -48,3 +54,20 @@ export async function postJSON<T = unknown>(path: string, body: unknown): Promis
48
54
  }
49
55
  return (await resp.json()) as T
50
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
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
4
4
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
5
5
 
6
+ import { trackAgentSession } from './client/agent-session.js'
6
7
  import { registerFileTools } from './features/files/tools.js'
7
8
  import { registerNotebookTools } from './features/notebooks/tools.js'
8
9
  import { registerNoteResource } from './features/notes/resource.js'
@@ -20,6 +21,8 @@ registerTagTools(server)
20
21
  registerNotebookTools(server)
21
22
  registerFileTools(server)
22
23
 
24
+ trackAgentSession(server.server, process.stdin)
25
+
23
26
  try {
24
27
  await server.connect(new StdioServerTransport())
25
28
  console.error('Secure MCP Inkdrop Server running on stdio')
@@ -0,0 +1,98 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+
3
+ import { AGENT_HEADERS } from 'inkdrop-consts'
4
+
5
+ import { buildAgentHeaders, workspaceNameFromRoot } from '../../src/client/agent-identity'
6
+
7
+ const SESSION_ID = '3f0c1c3e-6f0a-4d0e-9f5b-0a4f2d6f7b11'
8
+
9
+ describe('buildAgentHeaders', () => {
10
+ test('sends only the session ID before the client is known', () => {
11
+ expect(buildAgentHeaders({ sessionId: SESSION_ID })).toEqual({
12
+ [AGENT_HEADERS.session]: SESSION_ID
13
+ })
14
+ })
15
+
16
+ test('sends the client name, title, version and the workspace', () => {
17
+ const headers = buildAgentHeaders({
18
+ sessionId: SESSION_ID,
19
+ client: { name: 'claude-code', title: 'Claude Code', version: '2.1.0' },
20
+ workspace: 'inkdrop'
21
+ })
22
+
23
+ expect(headers).toEqual({
24
+ [AGENT_HEADERS.session]: SESSION_ID,
25
+ [AGENT_HEADERS.clientName]: 'claude-code',
26
+ [AGENT_HEADERS.clientTitle]: 'Claude%20Code',
27
+ [AGENT_HEADERS.clientVersion]: '2.1.0',
28
+ [AGENT_HEADERS.workspace]: 'inkdrop'
29
+ })
30
+ })
31
+
32
+ test('percent-encodes values that a header cannot carry as they are', () => {
33
+ const headers = buildAgentHeaders({
34
+ sessionId: SESSION_ID,
35
+ client: { name: 'client', version: '1' },
36
+ workspace: 'ノート\r\nInjected: 1'
37
+ })
38
+
39
+ expect(headers[AGENT_HEADERS.workspace]).toBe(encodeURIComponent('ノート\r\nInjected: 1'))
40
+ })
41
+
42
+ test('leaves out an empty value', () => {
43
+ const headers = buildAgentHeaders({
44
+ sessionId: SESSION_ID,
45
+ client: { name: 'client', title: '', version: '1' }
46
+ })
47
+
48
+ expect(AGENT_HEADERS.clientTitle in headers).toBe(false)
49
+ })
50
+
51
+ test('cuts a long value', () => {
52
+ const headers = buildAgentHeaders({
53
+ sessionId: SESSION_ID,
54
+ client: { name: 'a'.repeat(500), version: '1' }
55
+ })
56
+
57
+ expect(headers[AGENT_HEADERS.clientName]).toBe('a'.repeat(128))
58
+ })
59
+
60
+ test('cuts a long value in the middle of an emoji without throwing', () => {
61
+ const headers = buildAgentHeaders({
62
+ sessionId: SESSION_ID,
63
+ workspace: `${'a'.repeat(127)}😀`
64
+ })
65
+
66
+ expect(headers[AGENT_HEADERS.workspace]).toBe(
67
+ `${'a'.repeat(127)}${encodeURIComponent('\uFFFD')}`
68
+ )
69
+ })
70
+ })
71
+
72
+ describe('workspaceNameFromRoot', () => {
73
+ test('prefers the name the client gives the root', () => {
74
+ expect(workspaceNameFromRoot({ uri: 'file:///Users/me/dev/inkdrop', name: 'Inkdrop' })).toBe(
75
+ 'Inkdrop'
76
+ )
77
+ })
78
+
79
+ test('falls back to the last folder of a file URI', () => {
80
+ expect(workspaceNameFromRoot({ uri: 'file:///Users/me/dev/inkdrop' })).toBe('inkdrop')
81
+ })
82
+
83
+ test('ignores a trailing slash', () => {
84
+ expect(workspaceNameFromRoot({ uri: 'file:///Users/me/dev/inkdrop/' })).toBe('inkdrop')
85
+ })
86
+
87
+ test('decodes an encoded folder name', () => {
88
+ expect(workspaceNameFromRoot({ uri: 'file:///Users/me/my%20notes' })).toBe('my notes')
89
+ })
90
+
91
+ test('returns undefined for a URI with no folder', () => {
92
+ expect(workspaceNameFromRoot({ uri: 'file:///' })).toBeUndefined()
93
+ })
94
+
95
+ test('returns undefined for a malformed URI', () => {
96
+ expect(workspaceNameFromRoot({ uri: 'not a uri' })).toBeUndefined()
97
+ })
98
+ })