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
|
import Supermemory from "supermemory"
const MAX_CHARS = 200000 // ~50k tokens (character-based limit)
const DEFAULT_PROJECT_ID = "sm_project_default"
export interface Memory {
id: string
memory: string
similarity: number
title?: string
content?: string
}
export interface SearchResult {
results: Memory[]
total: number
timing: number
}
export interface Profile {
static: string[]
dynamic: string[]
}
export interface ProfileResponse {
profile: Profile
searchResults?: SearchResult
}
export interface Project {
id: string
name: string
containerTag: string
createdAt: string
updatedAt: string
isExperimental: boolean
documentCount?: number
}
function limitByChars(text: string, maxChars = MAX_CHARS): string {
return text.length > maxChars ? `${text.slice(0, maxChars)}...` : text
}
// Type for SDK search result item
interface SDKResult {
id: string
memory?: string
content?: string
similarity: number
title?: string
context?: string
}
export class SupermemoryClient {
private client: Supermemory
private containerTag: string
private bearerToken: string
private apiUrl: string
constructor(
bearerToken: string,
containerTag?: string,
apiUrl = "https://api.supermemory.ai",
) {
this.bearerToken = bearerToken
this.apiUrl = apiUrl
this.client = new Supermemory({
apiKey: bearerToken,
baseURL: apiUrl,
})
this.containerTag = containerTag || DEFAULT_PROJECT_ID
}
// Create memory using SDK
async createMemory(
content: string,
): Promise<{ id: string; status: string; containerTag: string }> {
try {
const result = await this.client.add({
content,
containerTag: this.containerTag,
metadata: {
sm_source: "mcp",
},
})
return {
id: result.id,
status: "queued",
containerTag: this.containerTag,
}
} catch (error) {
this.handleError(error)
}
}
// Delete/forget memory by searching first
async forgetMemory(
content: string,
): Promise<{ success: boolean; message: string; containerTag: string }> {
try {
// First search for the memory
const searchResult = await this.search(content, 5)
if (searchResult.results.length === 0) {
return {
success: false,
message: "No matching memory found to forget.",
containerTag: this.containerTag,
}
}
// Delete the most similar match
const memoryToDelete = searchResult.results[0]
await this.client.memories.delete(memoryToDelete.id)
const memoryText = memoryToDelete.memory || memoryToDelete.content || ""
return {
success: true,
message: `Forgot: "${limitByChars(memoryText, 100)}"`,
containerTag: this.containerTag,
}
} catch (error) {
this.handleError(error)
}
}
// Search memories using SDK
async search(query: string, limit = 10): Promise<SearchResult> {
try {
const result = await this.client.search.memories({
q: query,
limit,
containerTag: this.containerTag,
searchMode: "hybrid",
})
// Normalize and limit response size
const results: Memory[] = (result.results as SDKResult[]).map((r) => ({
id: r.id,
memory: limitByChars(r.content || r.memory || r.context || ""),
similarity: r.similarity,
title: r.title,
content: r.content,
}))
return {
results,
total: result.total,
timing: result.timing,
}
} catch (error) {
this.handleError(error)
}
}
// Get user profile using SDK
async getProfile(query?: string): Promise<ProfileResponse> {
try {
const result = await this.client.profile({
containerTag: this.containerTag,
q: query,
})
const response: ProfileResponse = {
profile: {
static: result.profile?.static || [],
dynamic: result.profile?.dynamic || [],
},
}
if (result.searchResults) {
response.searchResults = {
results: (result.searchResults.results as SDKResult[]).map((r) => ({
id: r.id,
memory: limitByChars(r.content || r.memory || r.context || ""),
similarity: r.similarity,
title: r.title,
content: r.content,
})),
total: result.searchResults.total,
timing: result.searchResults.timing,
}
}
return response
} catch (error) {
this.handleError(error)
}
}
// Get projects list
async getProjects(): Promise<string[]> {
try {
const response = await fetch(`${this.apiUrl}/v3/projects`, {
method: "GET",
headers: {
Authorization: `Bearer ${this.bearerToken}`,
"Content-Type": "application/json",
},
})
if (!response.ok) {
if (response.status === 401) {
throw new Error("Authentication failed. Please re-authenticate.")
}
throw new Error(`Failed to fetch projects: ${response.statusText}`)
}
const data = (await response.json()) as {
projects: Project[]
}
return data.projects?.map((p) => p.containerTag) || []
} catch (error) {
this.handleError(error)
}
}
private handleError(error: unknown): never {
// Handle network/fetch errors
if (error instanceof TypeError) {
if (
error.message.includes("fetch") ||
error.message.includes("network")
) {
throw new Error(
"Network error. Please check your connection and try again.",
)
}
}
// Handle HTTP status errors from SDK/fetch
if (error && typeof error === "object" && "status" in error) {
const status = (error as { status: number }).status
const message =
"message" in error ? (error as { message: string }).message : undefined
switch (status) {
case 400:
case 422:
throw new Error(
message || "Invalid request parameters. Please check your input.",
)
case 401:
throw new Error("Authentication failed. Please re-authenticate.")
case 402:
throw new Error("Memory limit reached. Upgrade at supermemory.ai")
case 403:
throw new Error(
"Access forbidden. Your account may be restricted or blocked.",
)
case 404:
throw new Error("Memory not found. It may have been deleted.")
case 429:
throw new Error(
"Rate limit exceeded. Please wait a moment and try again.",
)
default:
if (status >= 500) {
throw new Error(
"Server error. The service may be temporarily unavailable. Please try again later.",
)
}
}
}
// Re-throw Error instances as-is
if (error instanceof Error) {
throw error
}
// Wrap unknown errors
throw new Error(`An unexpected error occurred: ${String(error)}`)
}
}
|