aboutsummaryrefslogtreecommitdiff
path: root/packages/mcp/src/index.ts
blob: e2abe5def233bf388a86d0fe8e167c4969222776 (plain) (blame)
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
#!/usr/bin/env node

import {
	createSupabaseClient,
	EdgeFunctionApiKeyValidator,
	type EmbeddingProvider,
	EmbeddingService,
	isValidApiKeyFormat,
	type LocalEmbeddingModel,
	LocalEmbeddingProvider,
	SupabaseProjectStore,
	SupabaseStore,
} from "@imemio/sdk";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

function getRequiredEnvironmentVariable(name: string): string {
	const environmentVariableValue = process.env[name];

	if (!environmentVariableValue) {
		throw new Error(`Missing required environment variable: ${name}`);
	}

	return environmentVariableValue;
}

function getOptionalEnvironmentVariable(name: string): string | undefined {
	return process.env[name];
}

function createEmbeddingProvider(): EmbeddingProvider | null {
	const embeddingType = getOptionalEnvironmentVariable("IMEMIO_EMBEDDING_TYPE");
	const openaiApiKey = getOptionalEnvironmentVariable("OPENAI_API_KEY");

	if (embeddingType === "local") {
		const model = getOptionalEnvironmentVariable(
			"IMEMIO_LOCAL_EMBEDDING_MODEL",
		) as LocalEmbeddingModel | undefined;

		return new LocalEmbeddingProvider({ model });
	}

	if (openaiApiKey) {
		return new EmbeddingService({ apiKey: openaiApiKey });
	}

	return null;
}

interface AuthResult {
	userId: string;
	useServiceRole: boolean;
}

async function resolveAuth(
	supabaseUrl: string,
	supabaseAnonKey: string,
): Promise<AuthResult> {
	const directUserId = getOptionalEnvironmentVariable("IMEMIO_USER_ID");

	if (directUserId) {
		return { userId: directUserId, useServiceRole: true };
	}

	const apiKey = getOptionalEnvironmentVariable("IMEMIO_API_KEY");

	if (apiKey) {
		if (!isValidApiKeyFormat(apiKey)) {
			throw new Error(
				"Invalid IMEMIO_API_KEY format. Expected: imemio_<32 hex chars>",
			);
		}

		const validator = new EdgeFunctionApiKeyValidator(
			supabaseUrl,
			supabaseAnonKey,
		);
		const result = await validator.validate(apiKey);

		if (!result.valid) {
			throw new Error(`API key validation failed: ${result.error}`);
		}

		console.error(`Authenticated via API key for user: ${result.userId}`);

		return { userId: result.userId, useServiceRole: true };
	}

	throw new Error(
		"Missing authentication. Set either IMEMIO_API_KEY or IMEMIO_USER_ID environment variable.",
	);
}

const supabaseUrl = getRequiredEnvironmentVariable("SUPABASE_URL");
const supabaseAnonKey = getRequiredEnvironmentVariable("SUPABASE_ANON_KEY");
const authResult = await resolveAuth(supabaseUrl, supabaseAnonKey);
const supabaseKey = authResult.useServiceRole
	? getRequiredEnvironmentVariable("SUPABASE_SERVICE_ROLE_KEY")
	: supabaseAnonKey;
const userId = authResult.userId;
const client = createSupabaseClient(supabaseUrl, supabaseKey);
const memoryStore = new SupabaseStore(client, userId);
const projectStore = new SupabaseProjectStore(client, userId);
const embeddingService = createEmbeddingProvider();
const tagSchema = z.object({
	id: z.string(),
	name: z.string(),
});
const metadataSchema = z.record(z.unknown());
const server = new McpServer({
	name: "imemio",
	version: "0.0.1",
});

server.tool(
	"create_memory",
	"Create a new memory",
	{
		content: z.string().describe("The content of the memory"),
		projectId: z.string().describe("The project ID this memory belongs to"),
		folderId: z.string().optional().describe("Optional folder ID"),
		tags: z.array(tagSchema).optional().describe("Optional tags"),
		metadata: metadataSchema.optional().describe("Optional metadata"),
	},
	async (parameters) => {
		const memory = await memoryStore.create({
			content: parameters.content,
			projectId: parameters.projectId,
			folderId: parameters.folderId,
			tags: parameters.tags,
			metadata: parameters.metadata,
		});

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(memory, null, 2),
				},
			],
		};
	},
);
server.tool(
	"get_memory",
	"Get a memory by ID",
	{
		id: z.string().describe("The memory ID"),
	},
	async (parameters) => {
		const memoryReadResult = await memoryStore.read(parameters.id);

		if (!memoryReadResult.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Memory not found: ${parameters.id}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(memoryReadResult.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"update_memory",
	"Update an existing memory",
	{
		id: z.string().describe("The memory ID to update"),
		content: z.string().optional().describe("New content"),
		folderId: z.string().nullable().optional().describe("New folder ID"),
		tags: z.array(tagSchema).optional().describe("New tags"),
		metadata: metadataSchema.optional().describe("New metadata"),
	},
	async (parameters) => {
		const memoryUpdateResult = await memoryStore.update(parameters.id, {
			content: parameters.content,
			folderId: parameters.folderId,
			tags: parameters.tags,
			metadata: parameters.metadata,
		});

		if (!memoryUpdateResult.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Memory not found: ${parameters.id}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(memoryUpdateResult.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"delete_memory",
	"Delete a memory",
	{
		id: z.string().describe("The memory ID to delete"),
	},
	async (parameters) => {
		const memoryDeleteResult = await memoryStore.delete(parameters.id);

		if (!memoryDeleteResult.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Memory not found: ${parameters.id}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: `Memory deleted: ${parameters.id}`,
				},
			],
		};
	},
);
server.tool(
	"list_memories",
	"List memories with optional filters",
	{
		projectId: z.string().optional().describe("Filter by project ID"),
		folderId: z.string().optional().describe("Filter by folder ID"),
		tags: z.array(z.string()).optional().describe("Filter by tag IDs"),
	},
	async (parameters) => {
		const filter =
			parameters.projectId || parameters.folderId || parameters.tags
				? {
						projectId: parameters.projectId,
						folderId: parameters.folderId,
						tags: parameters.tags,
					}
				: undefined;
		const memories = await memoryStore.list(filter);

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(memories, null, 2),
				},
			],
		};
	},
);
server.tool(
	"create_project",
	"Create a new project",
	{
		name: z.string().describe("The project name"),
		description: z.string().optional().describe("Optional project description"),
		isGlobal: z.boolean().optional().describe("Whether the project is global"),
	},
	async (parameters) => {
		const createResult = await projectStore.create({
			name: parameters.name,
			description: parameters.description,
			isGlobal: parameters.isGlobal,
		});

		if (!createResult.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: "Failed to create project",
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(createResult.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"get_project",
	"Get a project by ID",
	{
		id: z.string().describe("The project ID"),
	},
	async (parameters) => {
		const projectReadResult = await projectStore.get(parameters.id);

		if (!projectReadResult.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Project not found: ${parameters.id}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(projectReadResult.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"update_project",
	"Update an existing project",
	{
		id: z.string().describe("The project ID to update"),
		name: z.string().optional().describe("New project name"),
		description: z.string().nullable().optional().describe("New description"),
		isGlobal: z.boolean().optional().describe("New global status"),
	},
	async (parameters) => {
		const projectUpdateResult = await projectStore.update(parameters.id, {
			name: parameters.name,
			description: parameters.description,
			isGlobal: parameters.isGlobal,
		});

		if (!projectUpdateResult.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Project not found: ${parameters.id}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(projectUpdateResult.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"delete_project",
	"Delete a project",
	{
		id: z.string().describe("The project ID to delete"),
	},
	async (parameters) => {
		const projectDeleteResult = await projectStore.delete(parameters.id);

		if (!projectDeleteResult.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Project not found: ${parameters.id}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: `Project deleted: ${parameters.id}`,
				},
			],
		};
	},
);
server.tool("list_projects", "List all projects", {}, async () => {
	const listResult = await projectStore.list();

	if (!listResult.success) {
		return {
			content: [
				{
					type: "text" as const,
					text: "Failed to list projects",
				},
			],
			isError: true,
		};
	}

	return {
		content: [
			{
				type: "text" as const,
				text: JSON.stringify(listResult.value, null, 2),
			},
		],
	};
});
server.tool(
	"add_folder",
	"Add a folder to a project",
	{
		projectId: z.string().describe("The project ID"),
		name: z.string().describe("The folder name"),
		description: z.string().optional().describe("Optional folder description"),
	},
	async (parameters) => {
		const result = await projectStore.addFolder(parameters.projectId, {
			name: parameters.name,
			description: parameters.description,
		});

		if (!result.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Project not found: ${parameters.projectId}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(result.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"update_folder",
	"Update an existing folder",
	{
		projectId: z.string().describe("The project ID"),
		folderId: z.string().describe("The folder ID to update"),
		name: z.string().optional().describe("New folder name"),
		description: z.string().nullable().optional().describe("New description"),
	},
	async (parameters) => {
		const folderUpdateResult = await projectStore.updateFolder(
			parameters.projectId,
			parameters.folderId,
			{
				name: parameters.name,
				description: parameters.description,
			},
		);

		if (!folderUpdateResult.success) {
			const errorType = folderUpdateResult.error.type;

			if (errorType === "PROJECT_NOT_FOUND") {
				return {
					content: [
						{
							type: "text" as const,
							text: `Project not found: ${parameters.projectId}`,
						},
					],
					isError: true,
				};
			}

			return {
				content: [
					{
						type: "text" as const,
						text: `Folder not found: ${parameters.folderId}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(folderUpdateResult.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"remove_folder",
	"Remove a folder from a project",
	{
		projectId: z.string().describe("The project ID"),
		folderId: z.string().describe("The folder ID to remove"),
	},
	async (parameters) => {
		const folderRemoveResult = await projectStore.removeFolder(
			parameters.projectId,
			parameters.folderId,
		);

		if (!folderRemoveResult.success) {
			const errorType = folderRemoveResult.error.type;

			if (errorType === "PROJECT_NOT_FOUND") {
				return {
					content: [
						{
							type: "text" as const,
							text: `Project not found: ${parameters.projectId}`,
						},
					],
					isError: true,
				};
			}

			return {
				content: [
					{
						type: "text" as const,
						text: `Folder not found: ${parameters.folderId}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: `Folder removed: ${parameters.folderId}`,
				},
			],
		};
	},
);
server.tool(
	"list_folders",
	"List all folders in a project",
	{
		projectId: z.string().describe("The project ID"),
	},
	async (parameters) => {
		const result = await projectStore.listFolders(parameters.projectId);

		if (!result.success) {
			return {
				content: [
					{
						type: "text" as const,
						text: `Project not found: ${parameters.projectId}`,
					},
				],
				isError: true,
			};
		}

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(result.value, null, 2),
				},
			],
		};
	},
);
server.tool(
	"search_memories",
	"Search memories using semantic similarity",
	{
		embedding: z
			.array(z.number())
			.describe("The embedding vector (1536 dimensions) to search with"),
		threshold: z
			.number()
			.optional()
			.describe("Minimum similarity threshold (0-1, default 0.7)"),
		limit: z
			.number()
			.optional()
			.describe("Maximum number of results (default 10)"),
		projectId: z.string().optional().describe("Filter by project ID"),
		folderId: z.string().optional().describe("Filter by folder ID"),
	},
	async (parameters) => {
		const results = await memoryStore.search(parameters.embedding, {
			threshold: parameters.threshold,
			limit: parameters.limit,
			projectId: parameters.projectId,
			folderId: parameters.folderId,
		});

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(results, null, 2),
				},
			],
		};
	},
);
server.tool(
	"search_memories_by_text",
	"Search memories using text query with auto-generated embedding",
	{
		query: z.string().describe("The search query text"),
		threshold: z
			.number()
			.optional()
			.describe("Minimum similarity threshold (0-1, default 0.7)"),
		limit: z
			.number()
			.optional()
			.describe("Maximum number of results (default 10)"),
		projectId: z.string().optional().describe("Filter by project ID"),
		folderId: z.string().optional().describe("Filter by folder ID"),
	},
	async (parameters) => {
		if (!embeddingService) {
			return {
				content: [
					{
						type: "text" as const,
						text: "Embedding service not configured. Set OPENAI_API_KEY or IMEMIO_EMBEDDING_TYPE=local.",
					},
				],
				isError: true,
			};
		}

		const queryEmbedding = await embeddingService.generate(parameters.query);
		const searchResults = await memoryStore.search(queryEmbedding, {
			threshold: parameters.threshold,
			limit: parameters.limit,
			projectId: parameters.projectId,
			folderId: parameters.folderId,
		});

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(searchResults, null, 2),
				},
			],
		};
	},
);
server.tool(
	"generate_embedding",
	"Generate an embedding vector for text content",
	{
		text: z.string().describe("The text to generate an embedding for"),
	},
	async (parameters) => {
		if (!embeddingService) {
			return {
				content: [
					{
						type: "text" as const,
						text: "Embedding service not configured. Set OPENAI_API_KEY or IMEMIO_EMBEDDING_TYPE=local.",
					},
				],
				isError: true,
			};
		}

		const embedding = await embeddingService.generate(parameters.text);

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify({ embedding, dimensions: embedding.length }),
				},
			],
		};
	},
);
server.tool(
	"create_memory_with_embedding",
	"Create a new memory with auto-generated embedding",
	{
		content: z.string().describe("The content of the memory"),
		projectId: z.string().describe("The project ID this memory belongs to"),
		folderId: z.string().optional().describe("Optional folder ID"),
		tags: z.array(tagSchema).optional().describe("Optional tags"),
		metadata: metadataSchema.optional().describe("Optional metadata"),
	},
	async (parameters) => {
		if (!embeddingService) {
			return {
				content: [
					{
						type: "text" as const,
						text: "Embedding service not configured. Set OPENAI_API_KEY or IMEMIO_EMBEDDING_TYPE=local.",
					},
				],
				isError: true,
			};
		}

		const embedding = await embeddingService.generate(parameters.content);
		const memory = await memoryStore.create({
			content: parameters.content,
			projectId: parameters.projectId,
			folderId: parameters.folderId,
			tags: parameters.tags,
			metadata: parameters.metadata,
			embedding,
		});

		return {
			content: [
				{
					type: "text" as const,
					text: JSON.stringify(memory, null, 2),
				},
			],
		};
	},
);

async function main(): Promise<void> {
	const transport = new StdioServerTransport();

	await server.connect(transport);
}

main().catch((error) => {
	console.error("Server error:", error);
	process.exit(1);
});