Skip to content

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

Rust

feat(mcp): add memory_read_page tool + read-page CLI command (#49)

Demostenes Albert0aa20c7056d4
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index bff689ab..7ba84cb9 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -33,6 +33,10 @@ pub enum Command {
Status(StatusArgs),
/// Full-text search the wiki via FTS5.
Search(SearchArgs),
+ /// Fetch and display the full body of a wiki page.
+ /// Accepts either `--path` (exact path) or a positional query that
+ /// searches FTS5 and fetches the top matching page.
+ ReadPage(ReadPageArgs),
/// Write or update a wiki page atomically (also indexes it in the store).
WritePage(WritePageArgs),
/// Run the MCP server (with watcher) over stdio or HTTP.
@@ -407,6 +411,26 @@ pub struct SearchArgs {
pub json: bool,
}
+/// Arguments for `read-page`.
+#[derive(Debug, Args)]
+pub struct ReadPageArgs {
+ /// FTS5 query to find the page (searches and fetches the top hit).
+ /// Ignored when `--path` is provided.
+ pub query: Option<String>,
+ /// Exact wiki path (e.g. `notes/foo.md`). Takes precedence over `query`.
+ #[arg(long)]
+ pub path: Option<String>,
+ /// Workspace name. Defaults to `default`.
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
+ pub workspace: String,
+ /// Project name. When omitted, auto-derived from the current project.
+ #[arg(long)]
+ pub project: Option<String>,
+ /// Emit the page as JSON (includes frontmatter).
+ #[arg(long)]
+ pub json: bool,
+}
+
/// Arguments for `reset`.
#[derive(Debug, Args)]
pub struct ResetArgs {
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 37c8436d..289cced8 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -21,6 +21,7 @@ pub mod lint;
pub mod llm_test;
pub mod openclaw_plugin;
pub mod purge_project;
+pub mod read_page;
pub mod rename_project;
pub mod render_shared;
pub mod reorg;
diff --git a/crates/ai-memory-cli/src/commands/read_page.rs b/crates/ai-memory-cli/src/commands/read_page.rs
new file mode 100644
index 00000000..e2f7ba77
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/read_page.rs
@@ -0,0 +1,82 @@
+//! `ai-memory read-page` — display the full body of a wiki page.
+//!
+//! Two resolution modes:
+//! - `--path <path>`: fetch the page at that exact wiki path.
+//! - positional `<query>`: FTS5 search scoped to the current project;
+//! fetches the top-ranking hit's full body.
+//!
+//! The project is auto-detected from the current directory (same heuristic
+//! as `search`). Pass `--project` to target a different project explicitly.
+//!
+//! Thin HTTP client. Never opens the store or wiki directly.
+
+use anyhow::{Result, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::cli::ReadPageArgs;
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, get_json};
+
+/// Mirrors the `ReadPageResponse` struct on the server side.
+#[derive(Debug, Deserialize, Serialize)]
+struct PageContent {
+ path: String,
+ #[serde(default)]
+ workspace: String,
+ #[serde(default)]
+ project: String,
+ title: Option<String>,
+ body: String,
+ frontmatter: serde_json::Value,
+}
+
+/// Run the `read-page` subcommand.
+///
+/// # Errors
+/// Returns an error if the server is unreachable, returns non-2xx,
+/// or neither `--path` nor a query is supplied.
+pub async fn run(config: &Config, args: ReadPageArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_config(config);
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
+
+ let page: PageContent = if let Some(ref raw_path) = args.path {
+ get_json(
+ &ep,
+ "/admin/read-page",
+ &[
+ ("workspace", args.workspace.as_str()),
+ ("project", project.as_str()),
+ ("path", raw_path.as_str()),
+ ],
+ )
+ .await?
+ } else if let Some(ref query) = args.query {
+ get_json(
+ &ep,
+ "/admin/read-page",
+ &[
+ ("workspace", args.workspace.as_str()),
+ ("project", project.as_str()),
+ ("q", query.as_str()),
+ ],
+ )
+ .await?
+ } else {
+ bail!("provide a query (positional) or --path <wiki-path>");
+ };
+
+ if args.json {
+ println!("{}", serde_json::to_string_pretty(&page)?);
+ } else {
+ if let Some(ref title) = page.title {
+ println!("# {title}");
+ }
+ println!("path: {}", page.path);
+ println!();
+ print!("{}", page.body);
+ if !page.body.ends_with('\n') {
+ println!();
+ }
+ }
+ Ok(())
+}
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 76a8f1c8..10c33823 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -43,6 +43,7 @@ async fn main() -> Result<()> {
Command::Init(args) => commands::init::run(&config, args, config_path.as_deref()),
Command::Status(args) => commands::status::run(&config, args).await,
Command::Search(args) => commands::search::run(&config, args).await,
+ Command::ReadPage(args) => commands::read_page::run(&config, args).await,
Command::WritePage(args) => commands::write_page::run(&config, args).await,
Command::Serve(args) => commands::serve::run(&config, args).await,
Command::Reset(args) => commands::reset::run(&config, args),
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index 0c6dcf98..0be0cc14 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -70,6 +70,7 @@ match the intent to the tool. They do not need to name the tool.
| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) |
| "consolidate this session" / "compile what we learned" (also runs on PreCompact; at session end only if `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set) | `memory_consolidate` |
| "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes) |
+| "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup) |
| "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` |
| "prune old pages" / "memory cleanup" | `memory_forget_sweep` |
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 0ab58771..d3f37e71 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -14,6 +14,7 @@
//! - `POST /admin/purge-project` — delete a project and all its data.
//! - `POST /admin/rename-project` — rename a project (column-only; no files move).
//! - `POST /admin/write-page` — write or update a wiki page atomically.
+//! - `GET /admin/read-page` — fetch the full body of a single wiki page by path.
//!
//! The CLI is responsible for filesystem access (collecting sources from
//! the project repo, rendering output for humans); the server is
@@ -124,6 +125,7 @@ fn default_chunk_input_tokens() -> usize {
/// - `POST /admin/bootstrap`
/// - `GET /admin/status`
/// - `GET /admin/search`
+/// - `GET /admin/read-page`
/// - `POST /admin/reorg`
/// - `POST /admin/lint`
/// - `POST /admin/forget-sweep`
@@ -138,6 +140,7 @@ pub fn admin_router(state: AdminState) -> Router {
.route("/admin/bootstrap", post(handle_bootstrap))
.route("/admin/status", get(handle_status))
.route("/admin/search", get(handle_search))
+ .route("/admin/read-page", get(handle_read_page))
.route("/admin/reorg", post(handle_reorg))
.route("/admin/lint", post(handle_lint))
.route("/admin/forget-sweep", post(handle_forget_sweep))
@@ -341,6 +344,113 @@ async fn handle_search(
}
}
+// ---------------------------------------------------------------------
+// read-page
+// ---------------------------------------------------------------------
+
+/// Query string for `GET /admin/read-page`.
+///
+/// Two modes:
+/// - Path mode: `workspace` + `project` + `path` — direct lookup.
+/// - Query mode: `workspace` + `project` + `q` — FTS5 search scoped to
+/// the given project; fetches the top-ranking hit's full body.
+#[derive(Debug, Deserialize)]
+struct ReadPageQuery {
+ /// Workspace name (required).
+ workspace: String,
+ /// Project name (required).
+ project: String,
+ /// Direct wiki path (e.g. `notes/foo.md`). Takes precedence over `q`.
+ #[serde(default)]
+ path: Option<String>,
+ /// FTS5 query. Used when `path` is absent; fetches the top hit's full body.
+ #[serde(default)]
+ q: Option<String>,
+}
+
+/// Response body for `GET /admin/read-page`.
+#[derive(Debug, Serialize)]
+struct ReadPageResponse {
+ path: String,
+ workspace: String,
+ project: String,
+ title: Option<String>,
+ body: String,
+ frontmatter: serde_json::Value,
+}
+
+async fn handle_read_page(
+ State(state): State<Arc<AdminState>>,
+ Query(query): Query<ReadPageQuery>,
+) -> impl IntoResponse {
+ let (ws, proj) = match resolve_ws_proj(&state, &query.workspace, &query.project).await {
+ Ok(ids) => ids,
+ Err(e) => return e,
+ };
+
+ // Resolve the page path: direct `path` takes precedence over `q`.
+ let page_path = if let Some(raw) = query.path {
+ match ai_memory_core::PagePath::new(raw) {
+ Ok(p) => p,
+ Err(e) => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({ "error": format!("invalid path: {e}") })),
+ );
+ }
+ }
+ } else if let Some(q) = query.q {
+ let hits = match state
+ .reader
+ .search_pages_for_project(ws, proj, q.clone(), 1)
+ .await
+ {
+ Ok(h) => h,
+ Err(e) => return internal_err(e.to_string()),
+ };
+ match hits.into_iter().next() {
+ Some(h) => h.path,
+ None => {
+ return (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": format!("no pages found for query {q:?}") })),
+ );
+ }
+ }
+ } else {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({ "error": "provide `path` or `q`" })),
+ );
+ };
+
+ match state.wiki.read_page(ws, proj, &page_path) {
+ Ok(md) => {
+ let title = md
+ .frontmatter
+ .get("title")
+ .and_then(|v| v.as_str())
+ .map(str::to_string);
+ let resp = ReadPageResponse {
+ path: page_path.to_string(),
+ workspace: query.workspace,
+ project: query.project,
+ title,
+ body: md.body,
+ frontmatter: md.frontmatter,
+ };
+ (
+ StatusCode::OK,
+ Json(serde_json::to_value(&resp).unwrap_or_else(|_| serde_json::json!({}))),
+ )
+ }
+ Err(e) => (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
// ---------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 8188229f..bd9b09be 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -75,6 +75,11 @@ the conversation calls for them:\n\
- `memory_write_page` — when the user explicitly asks to remember, \
save, or annotate durable project knowledge. This writes a wiki page; \
do NOT use `memory_handoff_begin` for permanent annotations.\n\
+- `memory_read_page` — when the user asks to read, open, or show the \
+ full content of a specific page. Accepts a `query` (searches FTS5 and \
+ returns the top hit's full body) or a `path` (direct lookup). Use \
+ this instead of memory_query when the user wants the complete text, \
+ not just snippets.\n\
- `memory_lint` — when the user asks to audit the wiki for stale \
pages, contradictions, or rule suggestions.\n\
- `memory_forget_sweep` — when the user wants to prune old / cold \
@@ -315,6 +320,21 @@ struct ExploreArgs {
workspace: Option<String>,
}
+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
+struct ReadPageArgs {
+ /// FTS5 query to find the page (searches and returns the top hit's full body).
+ /// Ignored when `path` is provided.
+ #[serde(default, alias = "q", alias = "search")]
+ query: Option<String>,
+ /// Exact wiki path (e.g. `notes/foo.md`). Takes precedence over `query`.
+ #[serde(default)]
+ path: Option<String>,
+ /// Project to read from. Omit to target the project you're currently
+ /// working in (resolved from recent hook activity).
+ #[serde(default)]
+ project: Option<String>,
+}
+
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct WritePageArgs {
/// Relative wiki path to write, for example `notes/santander-2025.md`.
@@ -854,6 +874,74 @@ impl AiMemoryServer {
}))
}
+ /// Fetch the full body of a single wiki page.
+ #[tool(description = "Fetch the FULL body of a wiki page for the current \
+ project. Use this when the user asks to read, open, or show a specific \
+ page by name or topic — not just snippets. \
+ \
+ Two modes: \
+ (1) pass `query` — runs an FTS5 search and returns the top hit's \
+ complete body (title + markdown, frontmatter stripped); \
+ (2) pass `path` — direct lookup by the page's relative wiki path \
+ (e.g. `notes/budget.md`). `path` takes precedence when both are given. \
+ \
+ Returns `{ path, title, body, frontmatter }`. Errors if the page is \
+ not found or neither argument is supplied.")]
+ async fn memory_read_page(
+ &self,
+ Parameters(args): Parameters<ReadPageArgs>,
+ ) -> Result<CallToolResult, McpError> {
+ let Some(wiki) = self.wiki.as_ref() else {
+ return Err(McpError::internal_error(
+ "memory_read_page requires the server to be built with a wiki handle",
+ None,
+ ));
+ };
+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
+
+ let page_path = if let Some(p) = args.path {
+ PagePath::new(p)
+ .map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?
+ } else if let Some(query) = args.query {
+ let hits = self
+ .reader
+ .search_pages_for_project(ws, proj, query.clone(), 1)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ match hits.into_iter().next() {
+ Some(h) => h.path,
+ None => {
+ return Err(McpError::internal_error(
+ format!("no pages found for query {query:?}"),
+ None,
+ ));
+ }
+ }
+ } else {
+ return Err(McpError::invalid_params(
+ "provide either `query` or `path`",
+ None,
+ ));
+ };
+
+ let md = wiki
+ .read_page(ws, proj, &page_path)
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+
+ let title = md
+ .frontmatter
+ .get("title")
+ .and_then(|v| v.as_str())
+ .map(str::to_string);
+
+ ok_json(&serde_json::json!({
+ "path": page_path.to_string(),
+ "title": title,
+ "body": md.body,
+ "frontmatter": md.frontmatter,
+ }))
+ }
+
/// Create a handoff snapshot for the next agent CLI.
#[tool(description = "Record a cross-agent handoff snapshot for the \
NEXT agent that opens this project (e.g. Codex picking up after \
@@ -1299,6 +1387,7 @@ mod tests {
"memory_handoff_begin",
"memory_consolidate",
"memory_write_page",
+ "memory_read_page",
"memory_lint",
"memory_forget_sweep",
"memory_install_self_routing",