Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): keep an MCP tool's server and tool name in its observation
AkitaOnRails1ef9eceef0f9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 91cde92d..9df0bacd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -339,6 +339,14 @@ version in [`docs/changelog/`](docs/changelog/):expanded entries.([#1509](https://github.com/akitaonrails/ai-memory/issues/1509))+- A tool hook for an MCP tool now keeps the tool's identity. Claude Code, Codex+ and Hermes Agent name such a call `mcp__<server>__<tool>`; it stays in the+ `unknown` family, so its arguments and result are still never stored, but the+ observation now adds `mcp_server` and `mcp_tool` lines when the name is at+ most 64 ASCII letters, digits, `_` or `-`. Before, a session's MCP calls+ were recorded only as `tool unknown`.+ ([#1522](https://github.com/akitaonrails/ai-memory/issues/1522))+## [3.1.2] - 2026-10-20### Fixeddiff --git a/crates/ai-memory-cli/src/commands/transcript_capture.rs b/crates/ai-memory-cli/src/commands/transcript_capture.rsindex c7dbb66d..239a4e34 100644--- a/crates/ai-memory-cli/src/commands/transcript_capture.rs+++ b/crates/ai-memory-cli/src/commands/transcript_capture.rs@@ -37,8 +37,8 @@ pub(crate) enum EventCapture {Drop,/// A tool the capture policy does not recognize: record that it ran,/// never its arguments or output. The live server stores only the family- /// for an unknown-family tool, whatever the policy, so an import must not- /// store more.+ /// for an unknown-family tool, plus an MCP tool's validated server and+ /// tool names, whatever the policy, so an import must not store more.Unrecognized,/// Record that the tool ran, never its arguments or output.MetadataOnly(CaptureDecision),diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex 75893ee4..52acf9d8 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -144,6 +144,47 @@ pub enum ToolFamily {pub(crate) struct ToolObservationMetadata {pub(crate) tool_family: ToolFamily,pub(crate) tool_call_id: Option<String>,+ /// Set only for an unknown-family call whose name is a strictly+ /// validated MCP tool name; see [`mcp_tool_name`].+ pub(crate) mcp_tool: Option<McpToolName>,+}++/// The server and tool an MCP tool name identifies.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct McpToolName {+ pub(crate) server: String,+ pub(crate) tool: String,+}++/// Longest MCP tool name kept. Hermes clamps its generated names to the 64+/// characters OpenAI-compatible providers accept (`tools/mcp_tool_schema.py`,+/// v0.22.2); a longer name is not a shape any documented harness sends.+const MAX_MCP_TOOL_NAME_CHARS: usize = 64;++/// The server and tool of an `mcp__<server>__<tool>` tool name, the shape+/// Claude Code (<https://code.claude.com/docs/en/hooks>, "Match MCP tools",+/// plugin servers as `mcp__plugin_<plugin>_<server>__<tool>`), Codex+/// (<https://learn.chatgpt.com/docs/hooks>, `mcp__fs__read`) and Hermes Agent+/// (`mcp_prefixed_tool_name`, v0.22.2; server and tool reduced to+/// `[A-Za-z0-9_]`) put in a tool hook's `tool_name`.+///+/// An MCP tool's arguments have no known path shape, so it stays an unknown+/// family and keeps no input or output. Only the two names are kept, and only+/// when the whole name is at most 64 ASCII letters, digits, `_` or `-`: an+/// identifier, never free text. The server ends at the first `__`.+pub(crate) fn mcp_tool_name(name: &str) -> Option<McpToolName> {+ if name.len() > MAX_MCP_TOOL_NAME_CHARS+ || !name+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')+ {+ return None;+ }+ let (server, tool) = name.strip_prefix("mcp__")?.split_once("__")?;+ (!server.is_empty() && !tool.is_empty()).then(|| McpToolName {+ server: server.to_owned(),+ tool: tool.to_owned(),+ })}/// Safe outcome class for a completed tool call.@@ -305,9 +346,17 @@ pub(crate) fn tool_observation_metadata().is_some(),};- has_args.then(|| ToolObservationMetadata {- tool_family: agent_family(agent, name),- tool_call_id: id.filter(|id| valid_call_id(id)).map(str::to_owned),+ has_args.then(|| {+ let tool_family = agent_family(agent, name);+ ToolObservationMetadata {+ tool_family,+ tool_call_id: id.filter(|id| valid_call_id(id)).map(str::to_owned),+ mcp_tool: if tool_family == ToolFamily::Unknown {+ mcp_tool_name(name)+ } else {+ None+ },+ }})}diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 65b1ef01..e0438ce8 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -937,6 +937,12 @@ fn safe_tool_body(summary.push_str("\ntool_call_id: ");summary.push_str(id);}+ if let Some(mcp) = &metadata.mcp_tool {+ summary.push_str("\nmcp_server: ");+ summary.push_str(&mcp.server);+ summary.push_str("\nmcp_tool: ");+ summary.push_str(&mcp.tool);+ }match event {HookEvent::PreToolUse => Some(summary),HookEvent::PostToolUse => {@@ -1406,6 +1412,7 @@ mod tests {let written = safe_tool_title(&ToolObservationMetadata {tool_family: family,tool_call_id: None,+ mcp_tool: None,});assert!(is_safe_tool_title(&written),@@ -2574,6 +2581,142 @@ mod tests {);}+ /// Hermes v0.22.2 names an MCP tool `mcp__<server>__<tool>`+ /// (`tools/mcp_tool_schema.py` `mcp_prefixed_tool_name`) in the same+ /// `pre_tool_call` / `post_tool_call` envelope as its own tools. Such a+ /// call stays an unknown family, so its arguments and result are never+ /// kept, but its server and tool names are (#1522).+ #[test]+ fn hermes_mcp_tool_keeps_its_server_and_tool_names_but_no_input_or_output() {+ for (event, hermes_event, expected) in [+ (+ "pre-tool-use",+ "pre_tool_call",+ "tool_family: unknown\ntool_call_id: call_00_2m0e\nmcp_server: aim\nmcp_tool: memory_query",+ ),+ (+ "post-tool-use",+ "post_tool_call",+ "tool_family: unknown\ntool_call_id: call_00_2m0e\nmcp_server: aim\nmcp_tool: memory_query\noutcome: success",+ ),+ ] {+ let raw = serde_json::json!({+ "hook_event_name": hermes_event,+ "tool_name": "mcp__aim__memory_query",+ "tool_input": {"query": "SECRET-ARGUMENT"},+ "session_id": "hermes-session",+ "cwd": "/repo",+ "extra": {+ "tool_call_id": "call_00_2m0e",+ "status": "ok",+ "result": "SECRET-RESULT"+ }+ });+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("hermes".into()),+ ..Default::default()+ },+ raw,+ );+ assert_eq!(env.title_hint.as_deref(), Some("tool unknown"));+ assert_eq!(env.body_excerpt.as_deref(), Some(expected), "{event}");+ }+ }++ /// Every documented `mcp__<server>__<tool>` spelling keeps both names:+ /// a hyphenated Claude Code server, a Claude Code plugin server, Codex's+ /// own example and a Hermes name clamped to 64 characters with a hash.+ #[test]+ fn mcp_tool_names_from_each_documented_harness_keep_server_and_tool() {+ for (agent, tool_name, server, tool) in [+ (+ "claude-code",+ "mcp__brave-search__web_search",+ "brave-search",+ "web_search",+ ),+ (+ "claude-code",+ "mcp__plugin_my-plugin_db__query",+ "plugin_my-plugin_db",+ "query",+ ),+ ("codex", "mcp__fs__read", "fs", "read"),+ (+ "hermes",+ "mcp__plugin_bridge_team_server__list_open_pull_requests_1a2b3c4d",+ "plugin_bridge_team_server",+ "list_open_pull_requests_1a2b3c4d",+ ),+ ] {+ let mut raw = serde_json::json!({+ "tool_name": tool_name,+ "tool_input": {"path": "/etc/SECRET"},+ "tool_use_id": "call-1",+ "tool_response": "SECRET-OUTPUT",+ });+ if agent == "hermes" {+ raw["extra"] =+ serde_json::json!({"tool_call_id": "call-1", "result": "SECRET-OUTPUT"});+ }+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "PreToolUse".into(),+ agent: Some(agent.into()),+ ..Default::default()+ },+ raw,+ );+ assert_eq!(+ env.body_excerpt.as_deref(),+ Some(+ format!(+ "tool_family: unknown\ntool_call_id: call-1\nmcp_server: {server}\nmcp_tool: {tool}"+ )+ .as_str()+ ),+ "{agent} {tool_name}"+ );+ }+ }++ /// A name that is not exactly the documented MCP shape keeps no name at+ /// all, as before: an older Hermes `mcp_<server>_<tool>` cannot be split,+ /// and free text, over-long names and empty halves are refused.+ #[test]+ fn names_outside_the_mcp_shape_keep_no_tool_identity() {+ for tool_name in [+ "mcp_github_create_issue",+ "mcp__server",+ "mcp____tool",+ "mcp__server__",+ "MCP__server__tool",+ "mcp__my server__tool",+ "mcp__srv__tool\nsecret",+ "mcp__srv__tool.read",+ "mcp__srv/path__tool",+ "mcp__s\u{e9}rver__tool",+ &format!("mcp__srv__{}", "t".repeat(55)),+ "brand_new_tool",+ ] {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "PreToolUse".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({"tool_name": tool_name, "tool_input": {}, "tool_use_id": "call-1"}),+ );+ assert_eq!(+ env.body_excerpt.as_deref(),+ Some("tool_family: unknown\ntool_call_id: call-1"),+ "{tool_name:?}"+ );+ }+ }+/// Real Hermes execution-surface tools classify as non-file so their/// bodies carry the `extra.result` output (live names, 2026-10-07).#[test]@@ -3535,7 +3678,13 @@ mod tests {assert!(env.body_excerpt.is_none());}}- for tool in ["mcp__fs__read", "update_plan", "UNPROVEN_TOOL"] {+ for (tool, identity) in [+ // An MCP tool keeps its validated names (#1522), never its input+ // or output.+ ("mcp__fs__read", "\nmcp_server: fs\nmcp_tool: read"),+ ("update_plan", ""),+ ("UNPROVEN_TOOL", ""),+ ] {let env = HookEnvelope::from_query_and_body(HookQuery {event: "PostToolUse".into(),@@ -3546,7 +3695,12 @@ mod tests {);assert_eq!(env.body_excerpt.as_deref(),- Some("tool_family: unknown\ntool_call_id: call-unknown\noutcome: unknown")+ Some(+ format!(+ "tool_family: unknown\ntool_call_id: call-unknown{identity}\noutcome: unknown"+ )+ .as_str()+ ));}for response in [diff --git a/docs/companion-crates.md b/docs/companion-crates.mdindex d2ce9763..9de9dc76 100644--- a/docs/companion-crates.md+++ b/docs/companion-crates.md@@ -683,8 +683,9 @@ unclaimed tree. Building the guard on ai-memory's captured(agentmemory #221), so by design there is no synchronous veto channel back tothe harness.- **ai-memory does not retain the file paths.** For closed-tool agents the- stored observation is reduced to a `tool_family` label plus outcome; raw- arguments, paths, and tool names are extracted only transiently for+ stored observation is reduced to a `tool_family` label plus outcome (and an+ MCP tool's validated server and tool names); raw+ arguments, paths, and other tool names are extracted only transiently fordenylist matching, then dropped (`CaptureDecision` "never retains rawarguments, paths, or arbitrary tool names"). A consumer can see *that* a fileop happened in a session, never *which file*.diff --git a/docs/marker-file.md b/docs/marker-file.mdindex 2bc4b3e9..3642b673 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -898,7 +898,11 @@ The normal capture contract is intentionally narrow: supported Claude Code,OpenCode, Pi, OMP, and Antigravity tool events retain only canonical tool family,an agent-provided validated call ID when their documented schema proves one,and a PostToolUse outcome class. `PreToolUse` never retains commands,-arguments, paths, input bodies, or arbitrary tool names. `PostToolUse` appends+arguments, paths, input bodies, or arbitrary tool names. The one name kept is+an MCP tool's: a call named `mcp__<server>__<tool>` (Claude Code, Codex, Hermes+Agent) stays in the `unknown` family, with no input or output, and adds+`mcp_server` and `mcp_tool` lines when the whole name is at most 64 ASCII+letters, digits, `_` or `-`. `PostToolUse` appendsits existing tool-response/error excerpt and caps the complete rendered body at2,000 UTF-8-safe bytes. Antigravity's successful file-edit events fall back tothe bounded replacement or written-content field in `toolCall.args` because itsdiff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex b8cf4a30..302c5abe 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -49,7 +49,7 @@| Cline CLI | Hooks + MCP | `install-mcp --client cline --apply` merges Cline's required top-level `type`, `url`, and optional `headers` fields into `${CLINE_MCP_SETTINGS_PATH:-~/.cline/data/settings/cline_mcp_settings.json}` and explicitly selects Streamable HTTP (a bare URL selects legacy SSE). `install-hooks --agent cline --apply` writes the nine supported CLI event files to `~/.cline/hooks` (or project `.cline/hooks` with `--scope project`): task start/resume, prompt, pre/post tool, complete/cancel/error, and shutdown. The generated owner-only files refuse user-owned files and final-component symlinks. Cline starts task hooks detached, so pending handoffs are accepted through MCP; yolo mode disables hooks, and Cline must be restarted after installation. This installs Cline CLI hooks only; the VS Code extension uses a separate `~/Documents/Cline/Hooks` convention. No managed workstream. || FreeBuff | MCP-only | `install-mcp --client freebuff --apply` merges an `ai-memory mcp-bridge --no-session-id` stdio entry into `~/.agents/mcp.json`. FreeBuff discovers that file from the current directory, its parents, or the home directory and already reads `AGENTS.md`; it has no documented lifecycle-hook or managed-workstream surface. The bridge reaches the configured local or remote server without attempting to start a second server that would contend for the data-dir lock. || Prime Agent | MCP-only | `install-mcp --client prime-agent` merges an HTTP entry (`type: "http"` + `url`) into the `mcpServers` map of `$PRIME_AGENT_CODING_AGENT_DIR/settings.json` (default `~/.prime/agent/settings.json`), preserving other settings and servers; a project's `.prime/agent/settings.json` works through `--config-file`. A token is referenced as `"bearerTokenEnvVar": "AI_MEMORY_AUTH_TOKEN"`, never written: Prime Agent 0.10 counts a user HTTP server as connected and names it in the model's prompt only with that variable set or an OAuth grant. A credential-less entry is still callable through `mcp.call_tool("ai-memory", ...)` but is not listed. The model reaches MCP tools from its Python REPL (`await mcp.call_tool("ai-memory", "memory_query", {...})`), and Prime Agent sends no session id or cwd, so pass `workspace` and `project` on project-scoped calls. Lifecycle capture and managed workstreams are not claimed: Prime Agent 0.10 removed the TypeScript extensions its 0.9 releases had and has no hook surface. Verified against Prime Agent 0.10.0. |-| Hermes Agent | Supported | `install-hooks --agent hermes` (alias `hermes-agent`) prints a ready-to-paste `hooks:` block for `~/.hermes/config.yaml`; ai-memory never writes that YAML file, which Hermes also gates behind its hook-acceptance prompt (`hooks_auto_accept`). Each entry runs the native `ai-memory hook` command in exec form (Hermes splits `command` with `shlex.split` and uses no shell) with a 20-second timeout. Six events: `pre_tool_call` and `post_tool_call` for tool capture and exclusions; `on_session_start` to record the start; `pre_llm_call` for the prompt (text from `extra.user_message`, never the conversation history); `on_session_end` as a turn boundary, since Hermes fires it after every turn; and `on_session_finalize` to end the session on CLI exit, `/new` or gateway shutdown (after a gateway `/new` only the ending session is closed). A `delegate_task` child's lifecycle events are dropped; its tool events are kept. Hermes ignores `on_session_start` output, so every primary-session `pre_llm_call` checks for a pending handoff and prints it as `{"context": ...}`, which Hermes adds to that turn; this includes a resumed native Hermes session. Hermes reports its own process directory as `cwd`; the hook routes by `TERMINAL_CWD` (Hermes' `terminal.cwd`) when it names an existing absolute directory (inside a gateway, only for the `default` profile, whose `terminal.cwd` a multiplexing gateway exports), and a tool call still moves to the checkout its absolute `workdir` or `path` proves. A gateway session that expires idle is never finalized; close it with `ai-memory finalize-session --agent hermes`. When the community [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is installed in `$HERMES_HOME/plugins/ai-memory`, the block wires only the two tool events, because the plugin already captures prompts, ends sessions and claims the handoff. MCP: `install-mcp --client hermes` prints an `mcp_servers:` entry that runs `ai-memory mcp-bridge --no-session-id` (no token in the file, and `--apply` is refused). Hermes does not read MCP server instructions, so install the skills with `install-skills --scope global --agent hermes` (`~/.hermes/skills`). No managed workstream. Modeled on the Hermes v0.22.2 source; not yet run end to end by the maintainers. |+| Hermes Agent | Supported | `install-hooks --agent hermes` (alias `hermes-agent`) prints a ready-to-paste `hooks:` block for `~/.hermes/config.yaml`; ai-memory never writes that YAML file, which Hermes also gates behind its hook-acceptance prompt (`hooks_auto_accept`). Each entry runs the native `ai-memory hook` command in exec form (Hermes splits `command` with `shlex.split` and uses no shell) with a 20-second timeout. Six events: `pre_tool_call` and `post_tool_call` for tool capture and exclusions (an MCP tool, named `mcp__<server>__<tool>`, keeps its server and tool name but never its arguments or result); `on_session_start` to record the start; `pre_llm_call` for the prompt (text from `extra.user_message`, never the conversation history); `on_session_end` as a turn boundary, since Hermes fires it after every turn; and `on_session_finalize` to end the session on CLI exit, `/new` or gateway shutdown (after a gateway `/new` only the ending session is closed). A `delegate_task` child's lifecycle events are dropped; its tool events are kept. Hermes ignores `on_session_start` output, so every primary-session `pre_llm_call` checks for a pending handoff and prints it as `{"context": ...}`, which Hermes adds to that turn; this includes a resumed native Hermes session. Hermes reports its own process directory as `cwd`; the hook routes by `TERMINAL_CWD` (Hermes' `terminal.cwd`) when it names an existing absolute directory (inside a gateway, only for the `default` profile, whose `terminal.cwd` a multiplexing gateway exports), and a tool call still moves to the checkout its absolute `workdir` or `path` proves. A gateway session that expires idle is never finalized; close it with `ai-memory finalize-session --agent hermes`. When the community [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is installed in `$HERMES_HOME/plugins/ai-memory`, the block wires only the two tool events, because the plugin already captures prompts, ends sessions and claims the handoff. MCP: `install-mcp --client hermes` prints an `mcp_servers:` entry that runs `ai-memory mcp-bridge --no-session-id` (no token in the file, and `--apply` is refused). Hermes does not read MCP server instructions, so install the skills with `install-skills --scope global --agent hermes` (`~/.hermes/skills`). No managed workstream. Modeled on the Hermes v0.22.2 source; not yet run end to end by the maintainers. || GrizzyBot | Supported | [GrizzyBot](https://github.com/Foscoe63/GrizzyBot), a native macOS agent app, ships its own ai-memory bridge: it posts lifecycle events to `/hook` with `agent=grizzybot` (alias `grizzy-bot`) and talks to `/mcp` directly, so there is nothing for `install-hooks` or `install-mcp` to write. Sessions are attributed to `grizzybot`, and its Claude Code-shaped tool payloads (`tool_name`/`tool_input`/`tool_use_id`) are stored as closed-schema tool families, never tool names or arguments. The bridge is maintained in the GrizzyBot repository; review it before pointing it at a shared server. No managed workstream. || Factory Droid | Supported | MCP config (`install-mcp --client droid`, alias `factory-droid` → `~/.factory/mcp.json`, root `mcpServers`, `type: "http"`) + lifecycle hooks (`install-hooks --agent droid` → `~/.factory/hooks.json`) (#1240). The URL is written literally because Droid expands `${VAR}` only in headers; a bearer becomes `Authorization: Bearer ${AI_MEMORY_AUTH_TOKEN}`, so export that variable where droid runs (a token-file install gets the same reference, never the token). Droid sends Claude Code-shaped hook payloads, so each entry runs the native `ai-memory hook --event … --agent droid` command (no script bundle) and native commands enforce capture exclusions over Droid's `Read`, `Create`, `Edit`, `ApplyPatch`, `LS`, `Grep`, `Glob` and `Execute` tools, verified against the Droid 0.240.0 tool schemas; Droid payloads carry no tool-call id. Seven events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`, `SessionEnd`. The `SessionStart` hook delivers the prior session's handoff through `hookSpecificOutput.additionalContext`, and Droid's own `SessionEnd` closes the session, so no `finalize-session` step is needed. `--apply` merges around your own entries, and refuses to create `hooks.json` while `~/.factory/settings.json` keeps hooks under its `hooks` key, because Droid reads those only while `hooks.json` is absent. The issue reporter ran capture and recall end to end with this hook wiring on Droid 0.239.0; the handoff injection follows Droid's documented contract and has not been run end to end yet. No managed workstream (`ai-memory run droid`). See [`install.md`](install.md#factory-droid). || CodeBuddy Code | Hooks-only | Tencent CodeBuddy Code (`codebuddy`, alias `code-buddy`). Lifecycle-hook capture via `install-hooks --agent codebuddy --apply`: native `ai-memory hook` commands (no script bundle) merged into the `hooks` key of `~/.codebuddy/settings.json` around sibling settings and third-party hooks. Payloads are Claude Code-shaped (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_response`), so tool observations and capture exclusions use that parser. Seven events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`, `SessionEnd`. `SessionStart` stdout (`hookSpecificOutput.additionalContext`) delivers the prior session's handoff; with nothing to deliver, `SessionStart` and `UserPromptSubmit` print nothing, because CodeBuddy appends that stdout to the session. An interactive `SessionStart` may arrive without `cwd`; the hook then uses the `CODEBUDDY_PROJECT_DIR` CodeBuddy exports, and when neither names a directory it captures the event but claims no handoff, which stays open for `memory_handoff_accept`. `setup` detects CodeBuddy when `~/.codebuddy` exists. No `install-mcp` client, no transcript backfill, no headless `codebuddy -p` session close and no managed workstream are claimed. Verified against CodeBuddy's hook documentation and the payloads reported on v2.164–v2.167 (#1299); not yet run end to end by the maintainers. See [`install.md`](install.md#codebuddy-code). |