How the ai-memory MCP Tool Surface Works: A Complete Guide to the 18 Available Tools

The ai-memory MCP tool surface exposes 18 long-term memory operations through a stateless HTTP RPC server built on the rmcp library, enabling agents to query, write, and manage persistent knowledge via standardized tool calls with automatic project scoping.

The akitaonrails/ai-memory project implements a Model Context Protocol (MCP) server that transforms local vector storage into a queryable long-term memory system for LLM agents. Understanding how the ai-memory MCP tool surface functions is essential for integrating persistent context into AI workflows and building agents that retain knowledge across sessions.

MCP Server Architecture

The entry point for the ai-memory MCP tool surface is AiMemoryServer defined in crates/ai-memory-mcp/src/server.rs. This struct implements the core protocol handler and manages the lifecycle of agent connections.

The server holds a ToolRouter (tool_router: ToolRouter<Self>) that registers every tool implementation marked with the #[tool(...)] attribute macro. When an agent connects, the server delivers a handshake payload (MEMORY_INSTRUCTIONS) containing the available tool schemas and scoping guidance. The server extracts the actor key—a composite identifier combining user identity and session ID—from either the mcp-session-id or x-memory-actor-session-id HTTP header, as implemented in crates/ai-memory-mcp/src/auth.rs.

Each incoming request becomes a ToolCallContext containing the deserialized arguments, shared reader/writer handles to the underlying store, and the authenticated actor key. The context flows through tool_router.call(tcc).await to reach the appropriate async handler.

Tool Discovery Mechanism

Agents discover available capabilities by calling the tools/list endpoint. The server returns a JSON array of Tool objects derived from the MCP_TOOL_NAMES constant slice defined in server.rs:

const MCP_TOOL_NAMES: &[&str] = &[
    "memory_query",
    "memory_recent",
    "memory_status",
    "memory_briefing",
    "memory_explore",
    "memory_handoff_accept",
    "memory_handoff_begin",
    "memory_handoff_cancel",
    "memory_consolidate",
    "memory_auto_improve",
    "memory_write_page",
    "memory_read_page",
    "memory_read_session_observations",
    "memory_delete_page",
    "memory_feedback",
    "memory_lint",
    "memory_forget_sweep",
    "memory_install_self_routing",
];

The integration test prompts_cover_every_registered_mcp_tool (lines 47-85 in server.rs) enforces that this list remains synchronized with the router's registered implementations, preventing drift between documented and actual tool availability.

The 18 Available MCP Tools

The ai-memory MCP tool surface provides stateless RPCs organized into read, write, and administrative categories:

Read Operations

  • memory_query – Full-text and vector search (FTS5) across one or many scopes with optional entity extraction.
  • memory_recent – Returns the N most recently updated pages within the active scope.
  • memory_status – Reports per-client tool-call counters, storage statistics, and server health metrics.
  • memory_briefing – Generates a structured snapshot of project activity including page counts and recent modifications.
  • memory_explore – LLM-driven exploration mode that falls back to memory_briefing when no LLM is configured.
  • memory_read_page – Fetches the complete body of a specific page by its relative path.
  • memory_read_session_observations – Retrieves raw lifecycle observations for a single session ID.

Write Operations

  • memory_handoff_begin – Creates an open handoff record for transferring context between agents.
  • memory_handoff_accept – Accepts the latest open handoff for the caller's current working directory.
  • memory_handoff_cancel – Explicitly expires an open handoff without accepting it.
  • memory_consolidate – Triggers the LLM-driven consolidation pipeline to merge redundant pages.
  • memory_auto_improve – Initiates the auto-improve review loop for quality enhancement.
  • memory_write_page – Persists a durable wiki page (manual "remember this" operation).
  • memory_delete_page – Removes a page by its exact relative path.
  • memory_feedback – Records a relevance rating (thumbs up/down) for a recalled page to improve ranking.
  • memory_lint – Runs LLM-driven linting to detect contradictions, stale information, or style violations.
  • memory_forget_sweep – Executes a policy-based sweep to delete pages matching specific forgetting criteria.

Administrative Operations

  • memory_install_self_routing – Installs the MCP-handshake snippet and managed-skill definitions into the target repository.

Scoping and Authentication

Every read and write tool accepts optional scoping parameters that determine which projects the operation targets. If no scope is specified, the server derives the active project from the caller's current working directory.

Parameter Purpose
workspace / project Explicit UUIDs targeting a single workspace or project.
scopes Array of (workspace, project) tuples enabling multi-project queries.
global Boolean flag that, when true, searches all projects (requires explicit opt-in via default_global recall setting).
include_expired Includes pages marked as expired in search results.
limit / explain Controls pagination and returns debug execution information.

The authentication layer extracts credentials from HTTP headers and validates permissions before the ToolCallContext reaches the handler. All tool calls are recorded in the client_activity table for rate-limiting and analytics, with data periodically folded into daily buckets as defined in ai-memory-store/src/ops.rs.

Tool Execution Flow

When an agent invokes a tool, the sequence proceeds through these stages:

  1. HTTP Ingress – The request hits AiMemoryServer::call_tool, which constructs a ToolCallContext.
  2. Actor Resolution – The context extracts the actor key via actor_key_from_parts using the session headers.
  3. Routingtool_router.call(tcc).await dispatches to the specific async handler (e.g., memory_query).
  4. Storage Operation – The handler uses the shared ai-memory-store reader/writer interfaces to execute the query or mutation.
  5. Response – The handler returns a CallToolResult serialized as JSON, respecting the scoping constraints enforced during execution.

Integration Examples

Querying Memory via curl

Discover available tools:

curl -s http://127.0.0.1:49374/tools/list | jq '.[] .name'

Execute a scoped search:

curl -s -X POST http://127.0.0.1:49374/tools/call \
  -H "Content-Type: application/json" \
  -H "mcp-session-id: session-abc-123" \
  -d '{"tool":"memory_query","args":{"query":"rust async runtime","limit":5}}' \
  | jq .

Rust Client Integration

Using the AiMemoryClient wrapper from the CLI crate:

use ai_memory_cli::client::AiMemoryClient;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let client = AiMemoryClient::new("http://127.0.0.1:49374")?;
    let resp = client.memory_query("async channel", None).await?;
    println!("hits: {:#?}", resp.hits);
    Ok(())
}

Cross-Agent Handoff Flow

Agent A (finishing work) initiates the handoff:

await mcp.call_tool(
    "memory_handoff_begin",
    {"cwd": "/repo/src", "scope": "project"}
)

Agent B (resuming work) retrieves the context:

handoff = await mcp.call_tool("memory_handoff_accept", {"cwd": "/repo/src"})
print(handoff["handoff"]["content"])

Summary

  • The ai-memory MCP tool surface is implemented in crates/ai-memory-mcp/src/server.rs as AiMemoryServer, built on the rmcp library.
  • Agents discover 18 distinct tools via the tools/list endpoint, with the MCP_TOOL_NAMES constant ensuring consistency between registration and documentation.
  • Tool calls are stateless RPCs processed through a ToolRouter that injects scoping, authentication, and storage access via ToolCallContext.
  • Scoping rules default to the caller's current working directory but support explicit workspace, project, or global overrides.
  • The surface includes specialized tools for cross-agent handoffs (memory_handoff_begin, memory_handoff_accept), automatic consolidation, and manual page management.

Frequently Asked Questions

What is the MCP protocol in ai-memory?

The Model Context Protocol (MCP) in ai-memory is a standardized HTTP-based RPC mechanism defined in the rmcp library. It allows LLM agents to discover and invoke tools through a consistent interface, with ai-memory implementing this protocol to expose long-term memory operations as callable functions that accept JSON arguments and return structured results.

How does ai-memory handle multi-project scoping?

The server accepts workspace and project UUIDs as explicit parameters, or a scopes array containing multiple (workspace, project) tuples for cross-project queries. When the global parameter is set to true and the repository has opted into [recall] default_global, the search spans all accessible projects. Without explicit scoping, the system defaults to the project associated with the agent's current working directory.

What is the difference between memory_query and memory_recent?

memory_query performs full-text and vector similarity searches using FTS5 across the content of pages, supporting complex filtering and entity extraction, while memory_recent simply returns the N most recently updated pages in chronological order without evaluating content relevance. Use memory_query for semantic retrieval and memory_recent for activity feeds.

How do agents authenticate with the ai-memory MCP server?

Agents authenticate by providing session-identifying headers—either mcp-session-id or x-memory-actor-session-id—which the server validates in crates/ai-memory-mcp/src/auth.rs. The server derives an actor key from these headers using actor_key_from_parts, combining user identity and session information to enforce per-client rate limits and permission scopes.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →