Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(mcp): count tool calls per MCP client (V46)

Samir Hanna Verza1b510b0d794d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ce568cfa..0ecdb5f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- MCP-only clients are now visible in the operator's traffic picture.
+ Every MCP tool call is counted against its caller — the sanitized
+ `clientInfo.name` from the initialize handshake when the HTTP
+ transport runs stateful (`--http-stateful`) or over stdio, else the
+ `X-Memory-Actor-Agent` overlay an ingress proxy asserts, else
+ `unknown` — split into reads and writes and bucketed per UTC day in a
+ new `client_activity` table (V46). A new root-gated
+ `GET /admin/activity/by-client?since_days=N` reports the aggregate,
+ volume-descending with a name tiebreak (`0`/absent = whole history).
+ Counts buffer in memory and fold into the store at most once per
+ minute, so a query burst costs the writer one tiny batch rather than
+ one write per call — the M8 access-bump trade; up to a minute of
+ telemetry is lost on shutdown by design. Unknown future tools count
+ as writes, so an unclassified tool surfaces as suspicious growth
+ instead of hiding among reads. This complements
+ `/admin/sessions/by-agent`: hook-driven agents open sessions,
+ MCP-only clients (VS Code Copilot, Claude Desktop, scripts) never do,
+ and until now left no trace at all.
- Added explicit Kiro CLI v2 managed-workstream launches through `ai-memory run
kiro` / `kiro-cli`, including native `--resume-id` reuse, `$KIRO_HOME`
discovery, v2 `--yolo` translation, read-only visible-event import, and
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 76ba65db..398946c0 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -11,6 +11,7 @@
//! - `GET /admin/projects` — authoritative `(workspace, project)` list.
//! - `GET /admin/open-sessions` — open (not yet ended) sessions for one scope + agent.
//! - `GET /admin/sessions/by-agent` — session counts per agent CLI for one scope.
+//! - `GET /admin/activity/by-client` — MCP tool-call counts per client (server-wide).
//! - `GET /admin/search?q=` — FTS5 hits against the wiki index.
//! - `POST /admin/reorg` — retro-fit sessions to per-cwd projects.
//! - `POST /admin/lint` — run the M8 lint pass.
@@ -564,6 +565,7 @@ pub fn admin_router_with_decay_breadth(state: AdminState, breadth_weight: f64) -
.route("/admin/projects", get(handle_list_projects))
.route("/admin/open-sessions", get(handle_open_sessions))
.route("/admin/sessions/by-agent", get(handle_sessions_by_agent))
+ .route("/admin/activity/by-client", get(handle_activity_by_client))
.route(
"/admin/audit-contamination",
get(handle_audit_contamination),
@@ -909,6 +911,45 @@ struct OpenSessionEntry {
cwd: Option<String>,
}
+/// Query string for `GET /admin/activity/by-client` — MCP tool-call
+/// counts per client. Server-wide: MCP-only clients (the reason this
+/// exists) are not reliably scoped to one project per call, and the
+/// endpoint mirrors the buffer's own granularity.
+///
+/// `since_days = 0` means the whole history, mirroring
+/// `/admin/sessions/by-agent`.
+#[derive(Debug, Deserialize)]
+struct ActivityByClientQuery {
+ #[serde(default)]
+ since_days: u32,
+}
+
+async fn handle_activity_by_client(
+ State(state): State<Arc<AdminState>>,
+ Query(query): Query<ActivityByClientQuery>,
+) -> impl IntoResponse {
+ let since_day = (query.since_days > 0).then(|| {
+ jiff::Timestamp::now()
+ .as_microsecond()
+ .saturating_sub(i64::from(query.since_days).saturating_mul(US_PER_DAY))
+ .div_euclid(US_PER_DAY)
+ });
+ match state.reader.client_activity_since(since_day).await {
+ Ok(rows) => (
+ StatusCode::OK,
+ Json(
+ serde_json::to_value(&rows)
+ .map(|list| serde_json::json!({ "by_client": list }))
+ .unwrap_or_else(|_| serde_json::json!({ "by_client": [] })),
+ ),
+ ),
+ Err(e) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
/// Query string for `GET /admin/sessions/by-agent` — how many sessions each
/// agent CLI opened in one scope.
///
@@ -5388,6 +5429,91 @@ mod tests {
assert_eq!(json["providers"]["embedding"]["status"], "disabled");
}
+ /// The MCP-only complement: per-client tool-call counters served
+ /// back with the same window semantics as by-agent.
+ #[tokio::test]
+ async fn activity_by_client_aggregates_and_bounds_the_window() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ let today = jiff::Timestamp::now()
+ .as_microsecond()
+ .div_euclid(US_PER_DAY);
+ store
+ .writer
+ .bump_client_activity(vec![
+ ("vscode".into(), today, 4, 1),
+ ("vscode".into(), today - 40, 7, 0),
+ ("claude-desktop".into(), today, 1, 0),
+ ])
+ .await
+ .unwrap();
+
+ let router = admin_router(AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ auto_improve_require_approval: false,
+ auto_improve_review_config: Default::default(),
+ embedder: None,
+ provider_health: ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path: store.db_path().to_path_buf(),
+ bind: "127.0.0.1:49376".to_string(),
+ home_dir: None,
+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
+ token_pepper: None,
+ active_project: ai_memory_core::ActiveProject::new(),
+ scope_invalidator: None,
+ trusted_proxy_identity: false,
+ });
+
+ // Whole history: the 40-day-old bucket counts.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/admin/activity/by-client")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ json["by_client"],
+ serde_json::json!([
+ { "client": "vscode", "reads": 11, "writes": 1 },
+ { "client": "claude-desktop", "reads": 1, "writes": 0 },
+ ]),
+ "volume-desc across all history: {json}"
+ );
+
+ // A 7-day window drops the old bucket.
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/admin/activity/by-client?since_days=7")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ json["by_client"][0],
+ serde_json::json!({ "client": "vscode", "reads": 4, "writes": 1 }),
+ "{json}"
+ );
+ }
+
/// The dashboard read: session counts grouped per agent CLI, with the
/// scope failing closed and never auto-created.
#[tokio::test]
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index c575a8e4..906f5acb 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -375,6 +375,11 @@ pub struct AiMemoryServer {
/// Optional post-RRF reranker. When `None`, `memory_query` returns
/// fused, authority-adjusted order and stays on the zero-LLM path.
reranker: Option<Arc<dyn ai_memory_llm::Reranker>>,
+ /// Per-client MCP tool-call counters, buffered in memory and folded
+ /// into `client_activity` at most once per flush interval so a query
+ /// burst costs the writer one tiny upsert batch, not one write per
+ /// call (same reasoning as the M8 access-bump throttle).
+ client_activity: Arc<std::sync::Mutex<ClientActivityBuffer>>,
/// Shared across cloned request handlers so concurrent searches cannot
/// create an unbounded number of billable provider calls.
rerank_gate: Arc<tokio::sync::Semaphore>,
@@ -591,6 +596,64 @@ const RERANK_MAX_IN_FLIGHT: usize = 4;
/// answers from the adjusted pre-rerank order instead of waiting.
const RERANK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
+/// Microseconds in one UTC day, for `client_activity` bucketing.
+const US_PER_DAY: i64 = 86_400_000_000;
+/// How long buffered client-activity counts may age before the next
+/// tool call flushes them to the store. Counts inside the window are
+/// lost on process exit — acceptable for telemetry, and the price of
+/// not putting a write on every read's hot path.
+const CLIENT_ACTIVITY_FLUSH: std::time::Duration = std::time::Duration::from_secs(60);
+/// Cap on a sanitized client name. MCP `clientInfo.name` is untrusted
+/// free text; anything longer is truncated on a char boundary.
+const MAX_CLIENT_NAME_CHARS: usize = 64;
+
+/// In-memory accumulation of per-client tool-call counts between
+/// flushes. Keyed by `(client, utc_day)` so a flush that straddles
+/// midnight books each call to the day it actually happened.
+struct ClientActivityBuffer {
+ last_flush: std::time::Instant,
+ pending: HashMap<(String, i64), (u32, u32)>,
+}
+
+impl ClientActivityBuffer {
+ fn new() -> Self {
+ Self {
+ last_flush: std::time::Instant::now(),
+ pending: HashMap::new(),
+ }
+ }
+}
+
+/// Whether an MCP tool mutates server state, for the reads/writes split
+/// in `client_activity`. Anything unknown counts as a write: failing
+/// toward "write" means a future tool added without updating this list
+/// shows up as suspicious growth in the write column instead of being
+/// silently misfiled as harmless reads.
+fn tool_call_is_write(tool: &str) -> bool {
+ !matches!(
+ tool,
+ "memory_query"
+ | "memory_read_page"
+ | "memory_recent"
+ | "memory_briefing"
+ | "memory_explore"
+ | "memory_status"
+ )
+}
+
+/// Trim, drop control characters, and cap an untrusted client name.
+/// `None` when nothing printable remains.
+fn sanitize_client_name(raw: &str) -> Option<String> {
+ let cleaned: String = raw
+ .trim()
+ .chars()
+ .filter(|c| !c.is_control())
+ .take(MAX_CLIENT_NAME_CHARS)
+ .collect();
+ let cleaned = cleaned.trim().to_string();
+ (!cleaned.is_empty()).then_some(cleaned)
+}
+
/// Cap on the free-text `reason` stored with a feedback signal.
const MAX_FEEDBACK_REASON_CHARS: usize = 500;
@@ -1007,6 +1070,7 @@ impl AiMemoryServer {
decay_breadth_weight: 0.0,
embedder: None,
reranker: None,
+ client_activity: Arc::new(std::sync::Mutex::new(ClientActivityBuffer::new())),
rerank_gate: Arc::new(tokio::sync::Semaphore::new(RERANK_MAX_IN_FLIGHT)),
sanitizer: ai_memory_core::Sanitizer::builtin(),
auto_improve_require_approval: false,
@@ -3418,6 +3482,20 @@ impl ServerHandler for AiMemoryServer {
.with_instructions(MEMORY_INSTRUCTIONS.to_string())
}
+ // Declared manually so `#[tool_handler]` skips its generated
+ // `call_tool`: every tool invocation passes through here once, which
+ // is the single choke point where the caller's client identity is
+ // still attached (issue-style: guard the door, not each room).
+ async fn call_tool(
+ &self,
+ request: rmcp::model::CallToolRequestParams,
+ context: rmcp::service::RequestContext<RoleServer>,
+ ) -> Result<rmcp::model::CallToolResult, McpError> {
+ self.record_client_activity(&request.name, &context);
+ let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
+ self.tool_router.call(tcc).await
+ }
+
// Declared manually so `#[tool_handler]` skips its generated
// `list_tools` and the flavor patch runs on every tools/list.
async fn list_tools(
@@ -3542,6 +3620,66 @@ impl AiMemoryServer {
/// breadth — the signal `[decay] breadth_weight` exists to read — would
/// under-count exactly on the busy pages it matters for. Failures are
/// logged at warn but never surfaced to the caller.
+ /// Record one MCP tool call against its client and flush the buffer
+ /// when it is older than [`CLIENT_ACTIVITY_FLUSH`]. Client identity
+ /// prefers the MCP `clientInfo.name` from the initialize handshake
+ /// (present in stateful HTTP / stdio); a stateless transport carries
+ /// no handshake, so the `X-Memory-Actor-Agent` overlay is the
+ /// fallback, then the literal `unknown`.
+ fn record_client_activity(
+ &self,
+ tool: &str,
+ context: &rmcp::service::RequestContext<RoleServer>,
+ ) {
+ let client = context
+ .peer
+ .peer_info()
+ .and_then(|init| sanitize_client_name(&init.client_info.name))
+ .or_else(|| {
+ context
+ .extensions
+ .get::<http::request::Parts>()
+ .and_then(|parts| parts.extensions.get::<ai_memory_core::ActorContext>())
+ .and_then(|actor| actor.agent.as_deref())
+ .and_then(sanitize_client_name)
+ })
+ .unwrap_or_else(|| "unknown".to_string());
+ let day = jiff::Timestamp::now()
+ .as_microsecond()
+ .div_euclid(US_PER_DAY);
+ let is_write = tool_call_is_write(tool);
+ let due = {
+ let mut buffer = self
+ .client_activity
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let slot = buffer.pending.entry((client, day)).or_insert((0, 0));
+ if is_write {
+ slot.1 = slot.1.saturating_add(1);
+ } else {
+ slot.0 = slot.0.saturating_add(1);
+ }
+ if buffer.last_flush.elapsed() >= CLIENT_ACTIVITY_FLUSH {
+ buffer.last_flush = std::time::Instant::now();
+ Some(std::mem::take(&mut buffer.pending))
+ } else {
+ None
+ }
+ };
+ if let Some(pending) = due {
+ let entries: Vec<(String, i64, u32, u32)> = pending
+ .into_iter()
+ .map(|((client, day), (reads, writes))| (client, day, reads, writes))
+ .collect();
+ let writer = self.writer.clone();
+ tokio::spawn(async move {
+ if let Err(e) = writer.bump_client_activity(entries).await {
+ tracing::warn!(error = %e, "client activity flush failed");
+ }
+ });
+ }
+ }
+
fn spawn_access_bump(&self, ids: Vec<PageId>, actor: Option<&ai_memory_core::IdentityKey>) {
if ids.is_empty() {
return;
@@ -9575,4 +9713,45 @@ mod tests {
assert!(select_bumpable(&mut seen, vec![page], Some(&alice), t10, cooldown).is_empty());
assert!(select_bumpable(&mut seen, vec![page], Some(&bob), t10, cooldown).is_empty());
}
+ #[test]
+ fn tool_write_classification_fails_toward_write() {
+ for read in [
+ "memory_query",
+ "memory_read_page",
+ "memory_recent",
+ "memory_briefing",
+ "memory_explore",
+ "memory_status",
+ ] {
+ assert!(!tool_call_is_write(read), "{read}");
+ }
+ for write in [
+ "memory_write_page",
+ "memory_delete_page",
+ "memory_feedback",
+ "memory_consolidate",
+ "memory_forget_sweep",
+ "memory_handoff_begin",
+ ] {
+ assert!(tool_call_is_write(write), "{write}");
+ }
+ // The deliberate default: a tool this list has never met counts as
+ // a write, so forgetting to classify a future tool is visible.
+ assert!(tool_call_is_write("memory_some_future_tool"));
+ }
+
+ #[test]
+ fn client_names_are_sanitized_and_bounded() {
+ assert_eq!(
+ sanitize_client_name(" Visual Studio Code ").as_deref(),
+ Some("Visual Studio Code"),
+ );
+ assert_eq!(
+ sanitize_client_name("evil\u{7}name").as_deref(),
+ Some("evilname")
+ );
+ assert_eq!(sanitize_client_name(" \u{0}\u{1} "), None);
+ let long = "x".repeat(500);
+ assert_eq!(sanitize_client_name(&long).unwrap().chars().count(), 64);
+ }
}
diff --git a/crates/ai-memory-store/migrations/V46__client_activity.sql b/crates/ai-memory-store/migrations/V46__client_activity.sql
new file mode 100644
index 00000000..2c4f6614
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V46__client_activity.sql
@@ -0,0 +1,25 @@
+-- Per-client MCP tool-call counters, bucketed by UTC day.
+--
+-- Hook-driven agents surface in `sessions.agent_kind` (and the
+-- `/admin/sessions/by-agent` aggregate), but MCP-only clients — VS Code
+-- Copilot, Claude Desktop, ad-hoc scripts — never fire a lifecycle hook,
+-- so they were invisible to "where is this server's memory traffic
+-- coming from". This table records what those clients actually do:
+-- tool calls, split into reads and writes.
+--
+-- `client` is the sanitized MCP `clientInfo.name` from the initialize
+-- handshake when the HTTP transport runs stateful, else the
+-- `X-Memory-Actor-Agent` overlay when an ingress proxy asserts one,
+-- else the literal 'unknown'. Free text on purpose: MCP client names
+-- are an open set, and forcing them through the `AgentKind` CHECK
+-- would misfile every client the enum has not met yet.
+--
+-- One row per (client, day) keeps the table O(clients × days) — it
+-- grows with the calendar, not with traffic.
+CREATE TABLE client_activity (
+ client TEXT NOT NULL,
+ day INTEGER NOT NULL, -- UTC days since the epoch
+ reads INTEGER NOT NULL DEFAULT 0 CHECK (reads >= 0),
+ writes INTEGER NOT NULL DEFAULT 0 CHECK (writes >= 0),
+ PRIMARY KEY (client, day)
+) WITHOUT ROWID;
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index c1cd752f..4012941d 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -48,12 +48,13 @@ pub use ops::{
};
pub use reader::{
ActivityWindow, AgentSessionCount, AutoImproveCandidateSession, BriefPageBody, BriefingPage,
- BriefingSnapshot, ContaminationFinding, ContaminationReport, ContaminationSummary,
- DecayCandidate, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding, GraphVia,
- HealthDetail, HealthPage, ObservationHit, OpenSession, PageAuthor, PageHit, PageHitWithMeta,
- PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage,
- RrfContributions, ScopeRow, SearchExplain, SessionEndDisposition, StatusCounts,
- StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
+ BriefingSnapshot, ClientActivity, ContaminationFinding, ContaminationReport,
+ ContaminationSummary, DecayCandidate, DerivedIndexStatus, EmbeddingTripleCount,
+ FeedbackFinding, GraphVia, HealthDetail, HealthPage, ObservationHit, OpenSession, PageAuthor,
+ PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,
+ ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow, SearchExplain,
+ SessionEndDisposition, StatusCounts, StoredEmbedding, StoredPageBody, WorkspaceScopeRow,
+ WorkspaceSummary, f32_vec_to_bytes,
};
pub use scope::{
ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 58373a36..7aaef04f 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -1099,6 +1099,31 @@ pub fn store_embeddings(conn: &mut Connection, embeddings: &[EmbeddingWrite]) ->
Ok(())
}
+/// Fold per-client MCP tool-call deltas into their `(client, day)`
+/// buckets. UPSERT per bucket inside one transaction: the buffer layer
+/// in the MCP server coalesces a minute of calls into a handful of
+/// entries, so this stays a few tiny rows per flush regardless of
+/// traffic.
+pub(crate) fn bump_client_activity(
+ conn: &mut Connection,
+ entries: &[(String, i64, u32, u32)],
+) -> StoreResult<()> {
+ if entries.is_empty() {
+ return Ok(());
+ }
+ let tx = conn.transaction()?;
+ {
+ let mut stmt = tx.prepare_cached(
+ "INSERT INTO client_activity (client, day, reads, writes) VALUES (?1, ?2, ?3, ?4) ON CONFLICT(client, day) DO UPDATE SET reads = reads + excluded.reads, writes = writes + excluded.writes",
+ )?;
+ for (client, day, reads, writes) in entries {
+ stmt.execute(params![client, day, reads, writes])?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+}
+
/// Bump `access_count` + `last_accessed_at` for the pages whose ids
/// appear in `page_ids`. Idempotent for unknown ids (no-op).
/// Used by the read path to feed the M8 reinforcement term.
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 1e1750c4..fa70b9aa 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -430,6 +430,22 @@ pub struct OpenSession {
pub cwd: Option<String>,
}
+/// Aggregate MCP tool-call counts for one client, from
+/// `client_activity` — the MCP-only complement to
+/// [`AgentSessionCount`]: hook-less clients (VS Code Copilot, Claude
+/// Desktop, scripts) never open sessions but still read and write
+/// memory through tools.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct ClientActivity {
+ /// Sanitized client name (`clientInfo.name`, actor overlay, or
+ /// `unknown`).
+ pub client: String,
+ /// Read-shaped tool calls (query/read/recent/briefing/…).
+ pub reads: u64,
+ /// Write-shaped tool calls (write_page/feedback/consolidate/…).
+ pub writes: u64,
+}
+
/// How many sessions one agent CLI opened in a scope — the shape behind
/// "where is this project's memory actually coming from".
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -1698,6 +1714,55 @@ impl ReaderPool {
.await
}
+ /// Sum per-client MCP tool-call counters, optionally bounded to
+ /// buckets at or after `since_day` (UTC days since the epoch;
+ /// `None` = whole history). Ordered by total volume descending
+ /// with a client-name tiebreak so equal totals do not reorder
+ /// between calls.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn client_activity_since(
+ &self,
+ since_day: Option<i64>,
+ ) -> StoreResult<Vec<ClientActivity>> {
+ self.with_conn(move |conn| {
+ let since_clause = if since_day.is_some() {
+ " WHERE day >= :since"
+ } else {
+ ""
+ };
+ let sql = format!(
+ "SELECT client, SUM(reads), SUM(writes) FROM client_activity\
+ {since_clause} \
+ GROUP BY client \
+ ORDER BY SUM(reads) + SUM(writes) DESC, client ASC"
+ );
+ let mut stmt = conn.prepare_cached(&sql)?;
+ let map = |row: &rusqlite::Row<'_>| {
+ let client: String = row.get(0)?;
+ let reads: i64 = row.get(1)?;
+ let writes: i64 = row.get(2)?;
+ Ok((client, reads, writes))
+ };
+ let rows = match &since_day {
+ Some(since) => stmt.query_map(&[(":since", since as &dyn rusqlite::ToSql)], map)?,
+ None => stmt.query_map([], map)?,
+ };
+ let mut out = Vec::new();
+ for row in rows {
+ let (client, reads, writes) = row?;
+ out.push(ClientActivity {
+ client,
+ reads: u64::try_from(reads).unwrap_or(0),
+ writes: u64::try_from(writes).unwrap_or(0),
+ });
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// Count sessions per agent CLI in one scope, newest window first.
///
/// Counts every session the window covers, open or ended — the question
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 8005de7b..0c077054 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -188,6 +188,11 @@ pub(crate) enum WriteCmd {
actor: Option<IdentityKey>,
reply: oneshot::Sender<StoreResult<()>>,
},
+ BumpClientActivity {
+ /// `(client, utc_day, reads_delta, writes_delta)` buckets.
+ entries: Vec<(String, i64, u32, u32)>,
+ reply: oneshot::Sender<StoreResult<()>>,
+ },
RecordPageFeedback {
workspace_id: WorkspaceId,
project_id: ProjectId,
@@ -895,6 +900,21 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Fold buffered per-client MCP tool-call counts into their
+ /// `(client, day)` buckets. Entries are deltas, not totals.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ pub async fn bump_client_activity(
+ &self,
+ entries: Vec<(String, i64, u32, u32)>,
+ ) -> StoreResult<()> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::BumpClientActivity { entries, reply: tx })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Record one explicit feedback signal for a page and update its
/// derived salience. Returns `None` when the path has no latest
/// version in that scope.
@@ -1795,6 +1815,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
ops::bump_access_for_pages_for_actor(&mut conn, &page_ids, actor.as_ref());
send_or_warn(reply, result, "bump_access_for_pages");
}
+ WriteCmd::BumpClientActivity { entries, reply } => {
+ let result = ops::bump_client_activity(&mut conn, &entries);
+ send_or_warn(reply, result, "bump_client_activity");
+ }
WriteCmd::SoftDeleteForDecay { page_ids, reply } => {
let result = ops::soft_delete_for_decay(&mut conn, &page_ids);
send_or_warn(reply, result, "soft_delete_for_decay");
diff --git a/crates/ai-memory-store/tests/client_activity.rs b/crates/ai-memory-store/tests/client_activity.rs
new file mode 100644
index 00000000..f8a714a2
--- /dev/null
+++ b/crates/ai-memory-store/tests/client_activity.rs
@@ -0,0 +1,72 @@
+//! `client_activity` — per-client MCP tool-call buckets.
+
+use ai_memory_store::Store;
+
+#[tokio::test]
+async fn buckets_accumulate_and_aggregate_deterministically() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+
+ // Two flushes into the same (client, day) bucket accumulate; a second
+ // client and a second day stay separate.
+ store
+ .writer
+ .bump_client_activity(vec![
+ ("vscode".into(), 100, 3, 1),
+ ("claude-desktop".into(), 100, 2, 0),
+ ])
+ .await
+ .unwrap();
+ store
+ .writer
+ .bump_client_activity(vec![
+ ("vscode".into(), 100, 2, 0),
+ ("vscode".into(), 101, 1, 1),
+ ])
+ .await
+ .unwrap();
+
+ let all = store.reader.client_activity_since(None).await.unwrap();
+ let seen: Vec<(&str, u64, u64)> = all
+ .iter()
+ .map(|c| (c.client.as_str(), c.reads, c.writes))
+ .collect();
+ assert_eq!(
+ seen,
+ vec![("vscode", 6, 2), ("claude-desktop", 2, 0)],
+ "summed across days, volume-desc",
+ );
+
+ // The window bound is inclusive on the day bucket.
+ let recent = store.reader.client_activity_since(Some(101)).await.unwrap();
+ let seen: Vec<(&str, u64, u64)> = recent
+ .iter()
+ .map(|c| (c.client.as_str(), c.reads, c.writes))
+ .collect();
+ assert_eq!(seen, vec![("vscode", 1, 1)]);
+
+ // A future bound excludes everything rather than ignoring the argument.
+ assert!(
+ store
+ .reader
+ .client_activity_since(Some(4_000_000))
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn equal_volumes_keep_a_stable_name_order() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ store
+ .writer
+ .bump_client_activity(vec![("zed".into(), 10, 1, 0), ("cursor".into(), 10, 1, 0)])
+ .await
+ .unwrap();
+ let first = store.reader.client_activity_since(None).await.unwrap();
+ let again = store.reader.client_activity_since(None).await.unwrap();
+ assert_eq!(first, again);
+ assert_eq!(first[0].client, "cursor", "name tiebreak, not scan order");
+}