use super::*;
#[derive(Debug, Deserialize)]
pub struct SupersedeParams {
#[serde(default)]
pub tenant_id: String,
pub old_chunk_id: String,
pub new_text: String,
#[serde(rename = "type")]
pub chunk_type: String,
#[serde(default)]
pub project_id: Option<String>,
#[serde(default)]
pub source: Option<SourceParams>,
#[serde(default)]
pub tags: Vec<String>,
}
pub async fn handle_memory_supersede<S: Store>(
store: &S,
tenant_manager: Option<&TenantManager>,
params: SupersedeParams,
) -> Result<(Value, PostWriteEvent), McpError> {
let ps = store.as_persistent().ok_or_else(|| {
McpError::ToolError("memory.supersede requires a persistent store".into())
})?;
let tenant_id = resolve_tenant_id(¶ms.tenant_id)?;
info!(
tenant_id = %tenant_id,
old_chunk_id = %params.old_chunk_id,
new_text_len = params.new_text.len(),
"memory.supersede"
);
if let Some(tm) = tenant_manager {
tm.ensure_tenant_dir(&tenant_id)
.map_err(|e| McpError::ToolError(e.to_string()))?;
}
let old_id = ChunkId::parse(¶ms.old_chunk_id)
.map_err(|e| McpError::InvalidParams(format!("old_chunk_id: {e}")))?;
let chunk_type = parse_chunk_type(¶ms.chunk_type)?;
let source_path = params.source.as_ref().and_then(|s| s.path.clone());
let mut new_chunk = MemoryChunk::new(tenant_id.clone(), ¶ms.new_text, chunk_type);
if let Some(project_id) = params.project_id.clone() {
new_chunk = new_chunk.with_project(ProjectId::new(Some(project_id)));
}
new_chunk = new_chunk.with_source(params_to_source(params.source));
if !params.tags.is_empty() {
new_chunk = new_chunk.with_tags(params.tags.clone());
}
let admission = crate::write_service::prepare_write(PrepareWriteRequest {
chunk_type,
text: &new_chunk.text,
tags: &new_chunk.tags,
ingestion_mode: crate::types::IngestionMode::Document,
expires_at_ms: None,
review_after_ms: None,
});
if admission.is_rejected() {
return Err(McpError::InvalidParams(format!(
"memory.supersede rejected by quality gate: {}",
admission.outcome.reason
)));
}
new_chunk = admission.apply_to_chunk(new_chunk);
let lifecycle_delta = admission.lifecycle_delta();
let (new_id, stored_chunk_ids) = ps
.supersede_chunk_with_lifecycle_and_stored_ids(
&tenant_id,
&old_id,
new_chunk,
lifecycle_delta,
)
.await
.map_err(|e| McpError::ToolError(e.to_string()))?;
info!(new_chunk_id = %new_id, old_chunk_id = %old_id, "chunk superseded");
let event = PostWriteEvent {
tenant_id: tenant_id.to_string(),
chunk_id: new_id.clone(),
chunk_type: params.chunk_type.clone(),
project_id: params.project_id,
source_path,
text: params.new_text.clone(),
};
let response = format_mcp_response(&json!({
"new_chunk_id": new_id.to_string(),
"new_stored_chunk_ids": stored_chunk_ids.iter().map(ToString::to_string).collect::<Vec<_>>(),
"old_chunk_id": old_id.to_string(),
"admission_decision": admission.decision(),
"admission_reason": admission.outcome.reason,
"admission_warning": admission.outcome.warning,
}))?;
Ok((response, event))
}
#[derive(Debug, Deserialize, Default)]
pub struct SetExpiryParams {
#[serde(default)]
pub tenant_id: String,
pub chunk_id: String,
#[serde(default, deserialize_with = "deserialize_some")]
pub expires_at_ms: Option<Option<i64>>,
#[serde(default, deserialize_with = "deserialize_some")]
pub review_after_ms: Option<Option<i64>>,
}
fn deserialize_some<'de, T, D>(deserializer: D) -> std::result::Result<Option<T>, D::Error>
where
T: Deserialize<'de>,
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(Some)
}
pub async fn handle_memory_set_expiry<S: Store>(
store: &S,
tenant_manager: Option<&TenantManager>,
params: SetExpiryParams,
) -> Result<Value, McpError> {
let ps = store.as_persistent().ok_or_else(|| {
McpError::ToolError("memory.set_expiry requires a persistent store".into())
})?;
let tenant_id = resolve_tenant_id(¶ms.tenant_id)?;
let chunk_id = ChunkId::parse(¶ms.chunk_id)
.map_err(|e| McpError::InvalidParams(format!("chunk_id: {e}")))?;
if let Some(tm) = tenant_manager {
tm.ensure_tenant_dir(&tenant_id)
.map_err(|e| McpError::ToolError(e.to_string()))?;
}
if params.expires_at_ms.is_none() && params.review_after_ms.is_none() {
return Err(McpError::InvalidParams(
"memory.set_expiry requires at least one of expires_at_ms / review_after_ms".into(),
));
}
info!(
tenant_id = %tenant_id,
chunk_id = %chunk_id,
set_expires = params.expires_at_ms.is_some(),
set_review = params.review_after_ms.is_some(),
"memory.set_expiry"
);
let delta = LifecycleDelta {
expires_at_ms: params.expires_at_ms,
review_after_ms: params.review_after_ms,
lifecycle_updated_at_ms: Some(current_time_ms()),
..Default::default()
};
let updated = ps
.update_lifecycle_if_exists(&tenant_id, &chunk_id, &delta)
.await
.map_err(|e| McpError::ToolError(e.to_string()))?;
if !updated {
return Err(McpError::ToolError(format!(
"memory.set_expiry: chunk {chunk_id} not found in tenant {tenant_id}"
)));
}
format_mcp_response(&json!({
"chunk_id": chunk_id.to_string(),
"updated": true,
}))
}
pub async fn handle_memory_get<S: Store>(store: &S, params: GetParams) -> Result<Value, McpError> {
let tenant_id = resolve_tenant_id(¶ms.tenant_id)?;
let chunk_id = validate_chunk_id(¶ms.chunk_id)?;
debug!(
tenant_id = %tenant_id,
chunk_id = %chunk_id,
"memory.get"
);
let resolved = match store
.get_with_lifecycle(&tenant_id, &chunk_id)
.await
.map_err(|e| McpError::ToolError(e.to_string()))?
{
Some(r) => r,
None => {
debug!(chunk_id = %chunk_id, "chunk not found");
store.record_usage_event(UsageEvent {
op: UsageOp::Get,
tenant: Some(tenant_id.to_string()),
project: None,
outcome: "zero_hits".to_string(),
chunk_count: Some(0),
bytes: None,
detail: None,
});
return format_mcp_response(&json!({ "found": false }));
}
};
store.record_usage_event(UsageEvent {
op: UsageOp::Get,
tenant: Some(tenant_id.to_string()),
project: None,
outcome: "hits:1".to_string(),
chunk_count: Some(1),
bytes: None,
detail: None,
});
let policy = VisibilityPolicy {
include_superseded: params.include_superseded.unwrap_or(false),
include_expired: params.include_expired.unwrap_or(false),
include_history: params.include_history.unwrap_or(false),
};
let now_ms = current_time_ms();
if !policy.is_visible_at(resolved.status, &resolved.lifecycle, now_ms) {
use crate::types::{ChunkStatus, MemoryTier};
let reason = match resolved.status {
ChunkStatus::Candidate => "candidate",
ChunkStatus::Superseded => "superseded",
ChunkStatus::Expired => "expired",
ChunkStatus::Error => "error",
_ if resolved.lifecycle.tier == MemoryTier::History => "history",
_ if resolved
.lifecycle
.expires_at_ms
.is_some_and(|t| t <= now_ms) =>
{
"expired"
}
_ => "unknown",
};
info!(
chunk_id = %chunk_id,
status = %resolved.status,
tier = %resolved.lifecycle.tier,
reason = reason,
"memory.get hidden by visibility policy"
);
return format_mcp_response(&json!({
"found": true,
"hidden": true,
"status": resolved.status.to_string(),
"tier": resolved.lifecycle.tier.to_string(),
"hidden_reason": reason,
}));
}
info!(chunk_id = %chunk_id, "chunk found");
format_mcp_response(&json!({
"found": true,
"chunk": resolved.chunk,
"lifecycle": resolved.lifecycle,
"status": resolved.status.to_string(),
}))
}
pub async fn handle_memory_delete<S: Store>(
store: &S,
params: DeleteParams,
) -> Result<Value, McpError> {
let tenant_id = resolve_tenant_id(¶ms.tenant_id)?;
let chunk_id = validate_chunk_id(¶ms.chunk_id)?;
info!(
tenant_id = %tenant_id,
chunk_id = %chunk_id,
"memory.delete"
);
let deleted = store
.delete(&tenant_id, &chunk_id)
.await
.map_err(|e| McpError::ToolError(e.to_string()))?;
if deleted {
info!(chunk_id = %chunk_id, "chunk deleted");
} else {
warn!(chunk_id = %chunk_id, "chunk not found for deletion");
}
store.record_usage_event(UsageEvent {
op: UsageOp::Delete,
tenant: Some(tenant_id.to_string()),
project: None,
outcome: if deleted { "ok" } else { "not_found" }.to_string(),
chunk_count: Some(if deleted { 1 } else { 0 }),
bytes: None,
detail: None,
});
format_mcp_response(&DeleteResult { deleted })
}