-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
385 lines (347 loc) · 10 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import * as lancedb from "@lancedb/lancedb";
import { runJxa } from "run-jxa";
import path from "node:path";
import os from "node:os";
import TurndownService from "turndown";
import {
EmbeddingFunction,
LanceSchema,
register,
} from "@lancedb/lancedb/embedding";
import { type Float, Float32, Utf8 } from "apache-arrow";
import { pipeline } from "@huggingface/transformers";
const { turndown } = new TurndownService();
const db = await lancedb.connect(
path.join(os.homedir(), ".mcp-apple-notes", "data")
);
const extractor = await pipeline(
"feature-extraction",
"Xenova/all-MiniLM-L6-v2"
);
@register("openai")
export class OnDeviceEmbeddingFunction extends EmbeddingFunction<string> {
toJSON(): object {
return {};
}
ndims() {
return 384;
}
embeddingDataType(): Float {
return new Float32();
}
async computeQueryEmbeddings(data: string) {
const output = await extractor(data, { pooling: "mean" });
return output.data as number[];
}
async computeSourceEmbeddings(data: string[]) {
return await Promise.all(
data.map(async (item) => {
const output = await extractor(item, { pooling: "mean" });
return output.data as number[];
})
);
}
}
const func = new OnDeviceEmbeddingFunction();
const notesTableSchema = LanceSchema({
title: func.sourceField(new Utf8()),
content: func.sourceField(new Utf8()),
creation_date: func.sourceField(new Utf8()),
modification_date: func.sourceField(new Utf8()),
vector: func.vectorField(),
});
const QueryNotesSchema = z.object({
query: z.string(),
});
const GetNoteSchema = z.object({
title: z.string(),
});
const server = new Server(
{
name: "my-apple-notes-mcp",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "list-notes",
description: "Lists just the titles of all my Apple Notes",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "index-notes",
description:
"Index all my Apple Notes for Semantic Search. Please tell the user that the sync takes couple of seconds up to couple of minutes depending on how many notes you have.",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "get-note",
description: "Get a note full content and details by title",
inputSchema: {
type: "object",
properties: {
title: z.string(),
},
required: ["title"],
},
},
{
name: "search-notes",
description: "Search for notes by title or content",
inputSchema: {
type: "object",
properties: {
query: z.string(),
},
required: ["query"],
},
},
{
name: "create-note",
description:
"Create a new Apple Note with specified title and content. Must be in HTML format WITHOUT newlines",
inputSchema: {
type: "object",
properties: {
title: { type: "string" },
content: { type: "string" },
},
required: ["title", "content"],
},
},
],
};
});
const getNotes = async () => {
const notes = await runJxa(`
const app = Application('Notes');
app.includeStandardAdditions = true;
const notes = Array.from(app.notes());
const titles = notes.map(note => note.properties().name);
return titles;
`);
return notes as string[];
};
const getNoteDetailsByTitle = async (title: string) => {
const note = await runJxa(
`const app = Application('Notes');
const title = "${title}"
try {
const note = app.notes.whose({name: title})[0];
const noteInfo = {
title: note.name(),
content: note.body(),
creation_date: note.creationDate().toLocaleString(),
modification_date: note.modificationDate().toLocaleString()
};
return JSON.stringify(noteInfo);
} catch (error) {
return "{}";
}`
);
return JSON.parse(note as string) as {
title: string;
content: string;
creation_date: string;
modification_date: string;
};
};
export const indexNotes = async (notesTable: any) => {
const start = performance.now();
let report = "";
const allNotes = (await getNotes()) || [];
const notesDetails = await Promise.all(
allNotes.map((note) => {
try {
return getNoteDetailsByTitle(note);
} catch (error) {
report += `Error getting note details for ${note}: ${error.message}\n`;
return {} as any;
}
})
);
const chunks = notesDetails
.filter((n) => n.title)
.map((node) => {
try {
return {
...node,
content: turndown(node.content || ""), // this sometimes fails
};
} catch (error) {
return node;
}
})
.map((note, index) => ({
id: index.toString(),
title: note.title,
content: note.content, // turndown(note.content || ""),
creation_date: note.creation_date,
modification_date: note.modification_date,
}));
await notesTable.add(chunks);
return {
chunks: chunks.length,
report,
allNotes: allNotes.length,
time: performance.now() - start,
};
};
export const createNotesTable = async (overrideName?: string) => {
const start = performance.now();
const notesTable = await db.createEmptyTable(
overrideName || "notes",
notesTableSchema,
{
mode: "create",
existOk: true,
}
);
const indices = await notesTable.listIndices();
if (!indices.find((index) => index.name === "content_idx")) {
await notesTable.createIndex("content", {
config: lancedb.Index.fts(),
replace: true,
});
}
return { notesTable, time: performance.now() - start };
};
const createNote = async (title: string, content: string) => {
// Escape special characters and convert newlines to \n
const escapedTitle = title.replace(/[\\'"]/g, "\\$&");
const escapedContent = content
.replace(/[\\'"]/g, "\\$&")
.replace(/\n/g, "\\n")
.replace(/\r/g, "");
await runJxa(`
const app = Application('Notes');
const note = app.make({new: 'note', withProperties: {
name: "${escapedTitle}",
body: "${escapedContent}"
}});
return true
`);
return true;
};
// Handle tool execution
server.setRequestHandler(CallToolRequestSchema, async (request, c) => {
const { notesTable } = await createNotesTable();
const { name, arguments: args } = request.params;
try {
if (name === "create-note") {
const { title, content } = CreateNoteSchema.parse(args);
await createNote(title, content);
return createTextResponse(`Created note "${title}" successfully.`);
} else if (name === "list-notes") {
return createTextResponse(
`There are ${await notesTable.countRows()} notes in your Apple Notes database.`
);
} else if (name == "get-note") {
try {
const { title } = GetNoteSchema.parse(args);
const note = await getNoteDetailsByTitle(title);
return createTextResponse(`${note}`);
} catch (error) {
return createTextResponse(error.message);
}
} else if (name === "index-notes") {
const { time, chunks, report, allNotes } = await indexNotes(notesTable);
return createTextResponse(
`Indexed ${chunks} notes chunks in ${time}ms. You can now search for them using the "search-notes" tool.`
);
} else if (name === "search-notes") {
const { query } = QueryNotesSchema.parse(args);
const combinedResults = await searchAndCombineResults(notesTable, query);
return createTextResponse(JSON.stringify(combinedResults));
} else {
throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
if (error instanceof z.ZodError) {
throw new Error(
`Invalid arguments: ${error.errors
.map((e) => `${e.path.join(".")}: ${e.message}`)
.join(", ")}`
);
}
throw error;
}
});
// Start the server
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Local Machine MCP Server running on stdio");
const createTextResponse = (text: string) => ({
content: [{ type: "text", text }],
});
/**
* Search for notes by title or content using both vector and FTS search.
* The results are combined using RRF
*/
export const searchAndCombineResults = async (
notesTable: lancedb.Table,
query: string,
limit = 20
) => {
const [vectorResults, ftsSearchResults] = await Promise.all([
(async () => {
const results = await notesTable
.search(query, "vector")
.limit(limit)
.toArray();
return results;
})(),
(async () => {
const results = await notesTable
.search(query, "fts", "content")
.limit(limit)
.toArray();
return results;
})(),
]);
const k = 60;
const scores = new Map<string, number>();
const processResults = (results: any[], startRank: number) => {
results.forEach((result, idx) => {
const key = `${result.title}::${result.content}`;
const score = 1 / (k + startRank + idx);
scores.set(key, (scores.get(key) || 0) + score);
});
};
processResults(vectorResults, 0);
processResults(ftsSearchResults, 0);
const results = Array.from(scores.entries())
.sort(([, a], [, b]) => b - a)
.slice(0, limit)
.map(([key]) => {
const [title, content] = key.split("::");
return { title, content };
});
return results;
};
const CreateNoteSchema = z.object({
title: z.string(),
content: z.string(),
});