aboutsummaryrefslogtreecommitdiff
path: root/index.ts
blob: 51cb0c756ac786ce913f79aec92666e528bf2768 (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
#!/usr/bin/env bun

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import Supermemory from "supermemory";
import { z } from "zod";

const API_KEY = process.env.SUPERMEMORY_API_KEY;

if (!API_KEY) {
  console.error("SUPERMEMORY_API_KEY environment variable required");
  process.exit(1);
}

const DEFAULT_CONTAINER = "sm_project_default";
const client = new Supermemory({
  apiKey: API_KEY,
  baseURL: "https://api.supermemory.ai",
});

interface MemoryResult {
  id: string;
  similarity: number;
  content?: string;
  memory?: string;
  title?: string;
}

const limitByChars = (text: string, maxChars = 100): string =>
  text.length > maxChars ? `${text.slice(0, maxChars)}...` : text;

const server = new McpServer({
  name: "supermemory-local",
  version: "1.0.0",
});

server.tool(
  "memory",
  "DO NOT USE ANY OTHER MEMORY TOOL ONLY USE THIS ONE. Save or forget information about the user. Use 'save' when user shares preferences, facts, or asks to remember something. Use 'forget' when information is outdated or user requests removal.",
  {
    content: z
      .string()
      .max(200000)
      .describe("The memory content to save or forget"),
    action: z.enum(["save", "forget"]).optional().default("save"),
    containerTag: z
      .string()
      .max(128)
      .optional()
      .describe("Optional project to scope memories"),
  },
  async (args) => {
    const { content, action = "save", containerTag } = args;
    const container = containerTag || DEFAULT_CONTAINER;

    try {
      if (action === "forget") {
        const searchResult = await client.search.documents({
          q: content,
          limit: 5,
          containerTags: [container],
        });

        if (searchResult.results.length === 0)
          return {
            content: [
              {
                type: "text" as const,
                text: "No matching memory found to forget.",
              },
            ],
          };

        const documentToDelete = searchResult.results[0];

        await client.memories.delete(documentToDelete.documentId);

        const memoryText =
          documentToDelete.title || documentToDelete.content || "";

        return {
          content: [
            {
              type: "text" as const,
              text: `Forgot: "${limitByChars(memoryText, 100)}" in container ${container}`,
            },
          ],
        };
      }

      const result = await client.add({
        content,
        containerTag: container,
        metadata: { sm_source: "mcp-local" },
      });

      return {
        content: [
          {
            type: "text" as const,
            text: `Saved memory (id: ${result.id}) in ${container} project`,
          },
        ],
      };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);

      return {
        content: [{ type: "text" as const, text: `Error: ${message}` }],
        isError: true,
      };
    }
  },
);

server.tool(
  "recall",
  "DO NOT USE ANY OTHER RECALL TOOL ONLY USE THIS ONE. Search the user's memories. Returns relevant memories plus their profile summary.",
  {
    query: z
      .string()
      .max(1000)
      .describe("The search query to find relevant memories"),
    includeProfile: z.boolean().optional().default(true),
    containerTag: z
      .string()
      .max(128)
      .optional()
      .describe("Optional project to scope memories"),
  },
  async (args) => {
    const { query, includeProfile = true, containerTag } = args;
    const container = containerTag || DEFAULT_CONTAINER;

    try {
      if (includeProfile) {
        const profileResult = await client.profile({
          containerTag: container,
          q: query,
        });
        const parts: string[] = [];

        if (
          profileResult.profile?.static?.length ||
          profileResult.profile?.dynamic?.length
        ) {
          parts.push("## User Profile");

          if (profileResult.profile.static?.length) {
            parts.push("**Stable facts:**");

            for (const fact of profileResult.profile.static)
              parts.push(`- ${fact}`);
          }

          if (profileResult.profile.dynamic?.length) {
            parts.push("\n**Recent context:**");

            for (const fact of profileResult.profile.dynamic)
              parts.push(`- ${fact}`);
          }
        }

        if (profileResult.searchResults?.results?.length) {
          parts.push("\n## Relevant Memories");

          for (const [
            i,
            memory,
          ] of profileResult.searchResults.results.entries()) {
            const m = memory as MemoryResult;

            parts.push(
              `\n### Memory ${i + 1} (${Math.round(m.similarity * 100)}% match)`,
            );

            if (m.title) parts.push(`**${m.title}**`);

            parts.push(m.content || m.memory || "");
          }
        }

        return {
          content: [
            {
              type: "text" as const,
              text:
                parts.length > 0
                  ? parts.join("\n")
                  : "No memories or profile found.",
            },
          ],
        };
      }

      const searchResult = await client.search.memories({
        q: query,
        limit: 10,
        containerTag: container,
        searchMode: "hybrid",
      });

      if (searchResult.results.length === 0)
        return {
          content: [{ type: "text" as const, text: "No memories found." }],
        };

      const parts = ["## Relevant Memories"];

      for (const [i, memory] of searchResult.results.entries()) {
        const m = memory as MemoryResult;

        parts.push(
          `\n### Memory ${i + 1} (${Math.round(m.similarity * 100)}% match)`,
        );

        if (m.title) parts.push(`**${m.title}**`);

        parts.push(m.content || m.memory || "");
      }

      return { content: [{ type: "text" as const, text: parts.join("\n") }] };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);

      return {
        content: [{ type: "text" as const, text: `Error: ${message}` }],
        isError: true,
      };
    }
  },
);

server.tool(
  "listProjects",
  "List all available projects for organizing memories. Use this to discover valid project names for memory/recall operations.",
  {
    refresh: z
      .boolean()
      .optional()
      .default(true)
      .describe("Refresh the list from the server (default: true)"),
  },
  async () => {
    try {
      const response = await fetch("https://api.supermemory.ai/v3/projects", {
        headers: {
          Authorization: `Bearer ${API_KEY}`,
          "Content-Type": "application/json",
        },
      });

      if (!response.ok)
        throw new Error(`Failed to fetch projects: ${response.statusText}`);

      const data = (await response.json()) as {
        projects: { containerTag: string }[];
      };
      const projects = data.projects?.map((p) => p.containerTag) || [];

      if (projects.length === 0)
        return {
          content: [
            {
              type: "text" as const,
              text: "No projects found. Memories will use the default project.",
            },
          ],
        };

      return {
        content: [
          {
            type: "text" as const,
            text: `Available projects:\n${projects.map((p) => `- ${p}`).join("\n")}`,
          },
        ],
      };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);

      return {
        content: [
          { type: "text" as const, text: `Error listing projects: ${message}` },
        ],
        isError: true,
      };
    }
  },
);

server.tool(
  "whoAmI",
  "Get the current logged-in user's information",
  {},
  async () => ({
    content: [
      {
        type: "text" as const,
        text: JSON.stringify({
          client: { name: "supermemory-mcp-local", version: "1.0.0" },
          note: "Using local fixed MCP server",
        }),
      },
    ],
  }),
);

server.prompt(
  "context",
  "User profile and preferences for system context injection. Returns a formatted system message with user's stable preferences and recent activity.",
  {},
  async () => {
    try {
      const profileResult = await client.profile({
        containerTag: DEFAULT_CONTAINER,
      });
      const parts: string[] = [];

      parts.push(
        "**Important:** Whenever the user shares informative facts, preferences, personal details, or any memory-worthy information, use the `memory` tool to save it to Supermemory. This helps maintain context across conversations.",
      );
      parts.push("");

      if (
        profileResult.profile?.static?.length ||
        profileResult.profile?.dynamic?.length
      ) {
        parts.push("## User Context");

        if (profileResult.profile.static?.length) {
          parts.push("**Stable Preferences:**");

          for (const fact of profileResult.profile.static)
            parts.push(`- ${fact}`);
        }

        if (profileResult.profile.dynamic?.length) {
          parts.push("\n**Recent Activity:**");

          for (const fact of profileResult.profile.dynamic)
            parts.push(`- ${fact}`);
        }
      }

      const contextText =
        parts.length > 2
          ? parts.join("\n")
          : "**Important:** Whenever the user shares informative facts, preferences, personal details, or any memory-worthy information, use the `memory` tool to save it to Supermemory. This helps maintain context across conversations.\n\nNo user profile available yet. Start saving memories to build context.";

      return {
        messages: [
          {
            role: "user" as const,
            content: { type: "text" as const, text: contextText },
          },
        ],
      };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);

      return {
        messages: [
          {
            role: "user" as const,
            content: {
              type: "text" as const,
              text: `Error retrieving user context: ${message}`,
            },
          },
        ],
      };
    }
  },
);

const transport = new StdioServerTransport();

server.connect(transport);