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
//! StoreWrapper for MCP tool implementations.
use crate::errors::Error;
use crate::memory::lifecycle::{MemoryImportance, MemoryStatus, MemoryType};
use crate::memory_types::ConflictMemory as InternalConflictMemory;
use crate::memory_types::IngestPolicy;
use std::sync::{Arc, Mutex};
use crate::memory::{MemoryStore, NewMemory, NewSupersedingMemory, UpdateParams};
use super::store_lock::{lock_mcp, lock_store};
#[cfg(test)]
#[path = "store_wrapper_error_tests.rs"]
mod error_mapping_tests;
/// Wrapper for MemoryStore to allow async-sound use.
///
/// Since MCP stdio handles requests sequentially, the Mutex will never contend.
pub(crate) struct StoreWrapper(pub(crate) Arc<Mutex<MemoryStore>>);
impl StoreWrapper {
/// Create a new StoreWrapper from a shared MemoryStore.
#[allow(dead_code)] // Used in cfg(test) builds
pub(crate) fn new(store: Arc<Mutex<MemoryStore>>) -> Self {
Self(store)
}
/// Store a memory with conflict detection.
#[allow(dead_code)] // Used for backward compatibility
pub(crate) fn ingest(
&self,
project_id: &str,
text: &str,
metadata: Option<&str>,
force: bool,
) -> Result<serde_json::Value, rmcp::ErrorData> {
let mut store = lock_mcp(&self.0, "ingest")?;
let policy = if force {
IngestPolicy::Force
} else {
IngestPolicy::ConflictAware
};
match store
.ingest(project_id, text, metadata, policy)
.map_err(|e| -> rmcp::ErrorData { e.into() })?
{
crate::memory_types::AddResult::Added { id } => {
Ok(serde_json::to_value(SuccessResponse {
id,
status: "added".to_string(),
})
.map_err(McpError::from_serde_error)?)
}
crate::memory_types::AddResult::Conflicts {
proposed,
conflicts,
} => Err(McpError::conflict(
&proposed,
conflicts
.into_iter()
.map(|c: InternalConflictMemory| ConflictMemory {
id: c.id,
content: c.content,
similarity: c.similarity,
})
.collect(),
)),
}
}
/// Store a memory with the full lifecycle the `store_memory` tool carries.
///
/// The row and its level travel together in the store's own `NewMemory` +
/// `MemoryImportance` params — no MCP-side row struct that could drift from
/// them — so the frame that parses the strings is not the frame that drops
/// one (#256, the MCP twin of the CLI defect #238). `force` decides the
/// ingest policy; the other three are the parsed lifecycle columns.
pub(crate) fn ingest_with_lifecycle(
&self,
row: &NewMemory<'_>,
force: bool,
importance: MemoryImportance,
) -> Result<serde_json::Value, rmcp::ErrorData> {
let mut store = lock_mcp(&self.0, "ingest_with_lifecycle")?;
let policy = if force {
IngestPolicy::Force
} else {
IngestPolicy::ConflictAware
};
match store
.ingest_with_importance(row, policy, importance)
.map_err(|e| -> rmcp::ErrorData { e.into() })?
{
crate::memory_types::AddResult::Added { id } => {
Ok(serde_json::to_value(SuccessResponse {
id,
status: "added".to_string(),
})
.map_err(McpError::from_serde_error)?)
}
crate::memory_types::AddResult::Conflicts {
proposed,
conflicts,
} => Err(McpError::conflict(
&proposed,
conflicts
.into_iter()
.map(|c: InternalConflictMemory| ConflictMemory {
id: c.id,
content: c.content,
similarity: c.similarity,
})
.collect(),
)),
}
}
/// Supersede an existing memory with new content at the `active` status and the
/// default importance — what `supersede_memory` drives. `metadata` is `Option<&str>`:
/// `None` is SQL NULL (as `store_memory`), not the string `"null"` (#305).
#[allow(dead_code)] // Used by supersede_memory tool
pub(crate) fn supersede(
&self,
project_id: &str,
new_text: &str,
metadata: Option<&str>,
memory_type: MemoryType,
old_memory_id: &str,
) -> Result<serde_json::Value, rmcp::ErrorData> {
let row = NewMemory {
project_id,
content: new_text,
metadata,
memory_type,
status: MemoryStatus::Active,
};
self.supersede_with_row(&row, old_memory_id, MemoryImportance::default())
}
/// Supersede an existing memory with a fully specified replacement row — what
/// `store_memory`'s `supersedes` path drives, since that tool takes `status`
/// and `importance` (#258, #256). `supersede_memory` reaches the same store
/// call through [`Self::supersede`], which composes the row with `active` and
/// the default level; the two tools differ only in their schemas, not in a
/// second write path.
///
/// The replacement row is the store's own [`NewMemory`] — the same type the
/// add path carries — composed with the replaced id and the level into
/// [`NewSupersedingMemory`] right here, so the two INSERT paths cannot drift
/// column-for-column and no MCP-side row struct duplicates `NewMemory`.
///
/// This frame adds nothing to the insert-status rule: it takes the row whose
/// `status` is a `MemoryStatus`, the same type the store takes, so no string
/// can become an unvalidated status one frame lower, and
/// [`MemoryStore::supersede_with`] is the one place that rejects
/// `superseded`/`deprecated` — the error arrives back as `invalid_input`
/// through `From<Error> for rmcp::ErrorData`.
pub(crate) fn supersede_with_row(
&self,
row: &NewMemory<'_>,
old_memory_id: &str,
importance: MemoryImportance,
) -> Result<serde_json::Value, rmcp::ErrorData> {
let mut store = lock_mcp(&self.0, "supersede_with_row")?;
let new_id = match store.supersede_with(&NewSupersedingMemory {
row: *row,
old_id: old_memory_id,
// The level the caller named, defaulted by name to `medium` in the
// tool handler — never the column DEFAULT (#238, #256). On the
// supersedes path it applies to the NEW row, matching the CLI.
importance,
}) {
Ok(id) => id,
Err(err) => {
return Err(err.into());
}
};
serde_json::to_value(SuccessResponse {
id: new_id,
status: "superseded".to_string(),
})
.map_err(McpError::from_serde_error)
}
/// Search memories by semantic meaning, returning raw Memory structs.
pub(crate) fn search_raw(
&self,
project_id: &str,
query: &str,
limit: usize,
recency_weight: f64,
options: crate::memory::SearchOptions,
) -> Result<Vec<crate::Memory>, Error> {
let mut store = lock_store(&self.0, "search_raw")?;
store.search(project_id, query, limit, recency_weight, options)
}
/// Search memories by hybrid (semantic + BM25), returning raw Memory structs.
pub(crate) fn search_hybrid_raw(
&self,
project_id: &str,
query: &str,
limit: usize,
recency_weight: f64,
options: crate::memory::SearchOptions,
) -> Result<Vec<crate::Memory>, Error> {
let mut store = lock_store(&self.0, "search_hybrid_raw")?;
store.search_hybrid(project_id, query, limit, recency_weight, options)
}
/// Search memories by semantic meaning.
#[allow(dead_code)] // Used in tests but not in actual MCP flow
pub(crate) fn search(
&self,
project_id: &str,
query: &str,
limit: usize,
recency_weight: f64,
memory_types: Option<Vec<&str>>,
statuses: Option<Vec<&str>>,
) -> Result<serde_json::Value, Error> {
let mut store = lock_store(&self.0, "search")?;
let memories = store.search(
project_id,
query,
limit,
recency_weight,
crate::memory::SearchOptions {
memory_types,
statuses,
},
)?;
let results: Vec<serde_json::Value> = memories
.into_iter()
.map(|m| {
let metadata_value = match m.metadata {
Some(ref meta_str) if meta_str.trim() != "null" => {
serde_json::from_str::<serde_json::Value>(meta_str)
.unwrap_or_else(|_| serde_json::Value::String(meta_str.clone()))
}
_ => serde_json::Value::Null,
};
serde_json::json!({
"id": m.id,
"content": m.content,
"similarity": m.similarity.unwrap_or(0.0),
"created_at": m.created_at,
"updated_at": m.updated_at,
"project_id": m.project_id,
"metadata": metadata_value
})
})
.collect();
Ok(serde_json::to_value(results)?)
}
/// Search memories by hybrid (semantic + BM25 with RRF fusion).
#[allow(dead_code)] // MCP tool, available for future use
pub(crate) fn search_hybrid(
&self,
project_id: &str,
query: &str,
limit: usize,
recency_weight: f64,
memory_types: Option<Vec<&str>>,
statuses: Option<Vec<&str>>,
) -> Result<serde_json::Value, Error> {
let mut store = lock_store(&self.0, "search_hybrid")?;
let options = crate::memory::SearchOptions {
memory_types,
statuses,
};
let memories = store.search_hybrid(project_id, query, limit, recency_weight, options)?;
let results: Vec<serde_json::Value> = memories
.into_iter()
.map(|m| {
let metadata_value = match m.metadata {
Some(ref meta_str) if meta_str.trim() != "null" => {
serde_json::from_str::<serde_json::Value>(meta_str)
.unwrap_or_else(|_| serde_json::Value::String(meta_str.clone()))
}
_ => serde_json::Value::Null,
};
serde_json::json!({
"id": m.id,
"content": m.content,
"similarity": m.similarity.unwrap_or(0.0),
"created_at": m.created_at,
"updated_at": m.updated_at,
"project_id": m.project_id,
"metadata": metadata_value
})
})
.collect();
Ok(serde_json::to_value(results)?)
}
/// List recent memories.
pub(crate) fn list(
&self,
project_id: &str,
limit: usize,
memory_types: Option<&[&str]>,
statuses: Option<&[&str]>,
) -> Result<serde_json::Value, Error> {
let store = lock_store(&self.0, "list")?;
let memories = store.list(project_id, limit, memory_types, statuses)?;
let results: Vec<serde_json::Value> = memories
.into_iter()
.map(|m| {
let metadata_value = match m.metadata {
Some(ref meta_str) if meta_str.trim() != "null" => {
serde_json::from_str::<serde_json::Value>(meta_str)
.unwrap_or_else(|_| serde_json::Value::String(meta_str.clone()))
}
_ => serde_json::Value::Null,
};
serde_json::json!({
"id": m.id,
"content": m.content,
"created_at": m.created_at,
"updated_at": m.updated_at,
"project_id": m.project_id,
"metadata": metadata_value
})
})
.collect();
Ok(serde_json::to_value(results)?)
}
/// Access the inner Arc<Mutex<MemoryStore>> for ToolHandler.
#[allow(dead_code)]
pub(crate) fn inner(&self) -> &Arc<Mutex<MemoryStore>> {
&self.0
}
/// Get a specific memory by ID scoped to a project.
#[allow(dead_code)] // Used by get_memory tool
pub(crate) fn get(
&self,
id: &str,
project_id: &str,
) -> Result<Option<crate::Memory>, rmcp::ErrorData> {
let store = lock_mcp(&self.0, "get")?;
store
.get(id, project_id)
.map_err(|e| -> rmcp::ErrorData { e.into() })
}
/// Delete a memory by ID scoped to a project.
#[allow(dead_code)] // Used by delete_memory tool
pub(crate) fn delete(&self, id: &str, project_id: &str) -> Result<bool, rmcp::ErrorData> {
let store = lock_mcp(&self.0, "delete")?;
store
.delete(id, project_id)
.map_err(|e| -> rmcp::ErrorData { e.into() })
}
/// Update a memory's content, metadata, type, or status.
#[allow(dead_code)] // Used by update_memory tool
pub(crate) fn update(
&self,
id: &str,
project_id: &str,
params: UpdateParams<'_>,
) -> Result<(), rmcp::ErrorData> {
let mut store = lock_mcp(&self.0, "update")?;
store
.update(id, project_id, params)
.map_err(|e| -> rmcp::ErrorData { e.into() })
}
/// Update retrieval telemetry for a list of memory IDs.
#[allow(dead_code)] // Used by search_memories and get_memory tools
pub(crate) fn touch_memories(&self, ids: &[&str]) -> Result<(), rmcp::ErrorData> {
let store = lock_mcp(&self.0, "touch_memories")?;
store
.touch_memories(ids)
.map_err(|e| -> rmcp::ErrorData { e.into() })
}
}
/// Response type for successful operations.
#[derive(serde::Serialize)]
struct SuccessResponse {
id: String,
status: String,
}
/// Conflict memory type for MCP errors.
#[derive(serde::Serialize)]
pub struct ConflictMemory {
pub id: String,
pub content: String,
pub similarity: f64,
}
/// MCP error types mapped to rmcp ErrorData.
#[derive(Debug)]
pub struct McpError;
impl McpError {
pub fn invalid_input(message: &str) -> rmcp::ErrorData {
rmcp::ErrorData::new(
rmcp::model::ErrorCode::INVALID_REQUEST,
message.to_string(),
Some(serde_json::json!({"type": "invalid_input"})),
)
}
pub fn internal_error(message: &str) -> rmcp::ErrorData {
rmcp::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
message.to_string(),
Some(serde_json::json!({"type": "internal_error"})),
)
}
pub fn conflict(proposed: &str, conflicts: Vec<ConflictMemory>) -> rmcp::ErrorData {
rmcp::ErrorData::new(
rmcp::model::ErrorCode::INVALID_REQUEST,
format!(
"Proposed memory conflicts with {} existing memory(ies)",
conflicts.len()
),
Some(serde_json::json!({
"type": "conflict",
"proposed": proposed,
"conflicts": conflicts
})),
)
}
pub fn from_serde_error(e: serde_json::Error) -> rmcp::ErrorData {
rmcp::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
format!("Serialization error: {}", e),
Some(serde_json::json!({"type": "internal_error"})),
)
}
}
/// Conversion from library errors to MCP errors.
impl From<Error> for rmcp::ErrorData {
fn from(e: Error) -> Self {
match e {
Error::EmptyInput => McpError::invalid_input("Text cannot be empty"),
Error::InputTooLong {
max_length,
actual_length,
} => McpError::invalid_input(&format!(
"Input too long: {} characters (max: {})",
actual_length, max_length
)),
Error::InvalidInput(msg) => McpError::invalid_input(&msg),
Error::Validation(msg) => McpError::invalid_input(&msg),
Error::InvalidTimestamp { timestamp, error } => {
McpError::invalid_input(&format!("Invalid timestamp '{}': {}", timestamp, error))
}
Error::ContentTooLong {
token_count,
max_tokens,
} => McpError::invalid_input(&format!(
"Content exceeds {}-token embedding limit (measured: {} tokens)",
max_tokens, token_count
)),
Error::NotFound(msg) => rmcp::ErrorData::new(
rmcp::model::ErrorCode::INVALID_REQUEST,
msg,
Some(serde_json::json!({"type": "not_found"})),
),
// Database errors keep the INTERNAL_ERROR code and the rendered
// message (issue #255 changed only the message body: the underlying
// SQLite text is now included instead of the bare "Database
// error"). That text is returned verbatim to the client by design:
// vipune does not filter SQLite wording on any surface — the CLI
// prints it (stderr for humans, and in the `error` key on STDOUT
// under `--json`, so it is part of that data stream, not just a
// diagnostic channel), and MCP returns the same string. A log
// shipper therefore sees raw SQLite text (`no such table: …`,
// `UNIQUE constraint failed: memories.id`) whichever surface it
// consumes. What vipune *does* sanitise (memory ids in not-found
// errors, below) is sanitised on every surface alike.
// A locked database is reported as such so an MCP client
// can retry rather than treat it as a server defect. rmcp's
// `ErrorCode` set has no "try again later", so the code stays
// INTERNAL_ERROR and `data.type` is the discriminator a client
// must read — the code alone cannot tell a retryable lock from a
// server bug.
Error::DatabaseLocked => rmcp::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
e.to_string(),
Some(serde_json::json!({"type": "database_locked"})),
),
// The structured embedding failures carry their fields in `data`
// as well as in the message, so a client can locate the corrupt
// row without parsing prose (the #186 payload, on the MCP side).
Error::Database { .. } => McpError::internal_error(&e.to_string()),
Error::CorruptEmbedding { ref id, ref reason } => rmcp::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
e.to_string(),
Some(serde_json::json!({
"type": "corrupt_embedding",
"id": id,
"reason": reason
})),
),
Error::InvalidBlobSize { expected, actual } => rmcp::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
e.to_string(),
Some(serde_json::json!({
"type": "invalid_blob_size",
"expected": expected,
"actual": actual
})),
),
Error::MismatchedDimensions { expected, actual } => rmcp::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
e.to_string(),
Some(serde_json::json!({
"type": "mismatched_dimensions",
"expected": expected,
"actual": actual
})),
),
Error::EmbedderUnavailable { reason } => rmcp::ErrorData::new(
rmcp::model::ErrorCode::INTERNAL_ERROR,
reason,
Some(serde_json::json!({"type": "embedder_unavailable"})),
),
_ => McpError::internal_error(&e.to_string()),
}
}
}