### Clone Repository and Set Up Development Environment Source: https://github.com/bburda/ai_memory_protocol/blob/main/CONTRIBUTING.md Clone the repository, create a virtual environment, install the project in development mode, and install necessary development tools and pre-commit hooks. ```bash git clone https://github.com/bburda/ai_memory_protocol.git cd ai_memory_protocol python3 -m venv .venv source .venv/bin/activate pip install -e '.[mcp]' pip install ruff pytest pre-commit pre-commit install ``` -------------------------------- ### Memory Get Tool Input Example Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Example of input for the `memory_get` tool, used to retrieve full details of a specific memory by its ID. ```json { "id": "DEC_rest_framework" } ``` -------------------------------- ### Memory Add Tool Input Example Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Example of input parameters for the `memory_add` tool, used to record a new memory. This includes type, title, tags, and optional details like body, confidence, and review period. ```json { "type": "dec", "title": "Use async/await instead of callbacks", "tags": "topic:concurrency,repo:frontend", "body": "Chose async/await for cleaner code and better error handling.", "confidence": "high", "review_days": 120 } ``` -------------------------------- ### Initialize Memory Workspace Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Initialize a new memory workspace in the specified directory and install necessary components. ```bash memory init .memories --install ``` -------------------------------- ### Install AI Memory Protocol Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Install the AI Memory Protocol using pipx. ```bash pipx install -e ai_memory_protocol/ ``` -------------------------------- ### Initialize Memory Workspace Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Create a new memory workspace for your project. The --install flag sets up the workspace. ```bash memory init .memories --name "My Project" --install ``` -------------------------------- ### Install AI Memory Protocol Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Install the AI Memory Protocol CLI. Use the '[mcp]' extra for MCP server support. ```bash git clone https://github.com/bburda/ai_memory_protocol.git pipx install -e ai_memory_protocol/ # With MCP server support pipx install -e 'ai_memory_protocol/[mcp]' ``` -------------------------------- ### Install MCP Server Module Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Install the AI Memory Protocol with MCP support using pipx. You can either perform a fresh installation or inject MCP support into an existing installation. ```bash # With MCP support pipx install -e 'ai_memory_protocol/[mcp]' # Or inject into existing installation pipx inject ai-memory-protocol mcp ``` -------------------------------- ### Start MCP Server for LLM Integration Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Starts the Memory Context Protocol (MCP) server, making memory operations available to LLMs via standard input/output. The MEMORY_DIR environment variable must be set. ```bash # Start MCP server MEMORY_DIR=/path/to/.memories memory-mcp-stdio # Claude or Copilot can now call: # - memory_recall(query, tag, format, limit, body, expand, sort) # - memory_get(id) # - memory_add(type, title, tags, body, confidence, ...) # - memory_update(id, status, confidence, add_tags, body, ...) # - memory_deprecate(id, by) # - memory_tags(prefix) # - memory_stale(body, renew_days) # - memory_rebuild() ``` -------------------------------- ### Example Need Object Structure Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/need-object.md A complete example of a 'need' object as returned by load_needs(). It includes all core, metadata, and link fields. ```python { "id": "DEC_rest_framework", "type": "dec", "title": "Use REST API instead of gRPC", "status": "active", "confidence": "high", "description": "We decided to use REST instead of gRPC...", "tags": ["topic:api", "repo:backend", "tier:core"], "scope": "global", "source": "https://github.com/example/issues/123", "owner": "@alice", "created_at": "2026-05-20", "updated_at": "2026-05-29", "review_after": "2026-08-27", "expires_at": "", "full_title": "[DEC] Use REST API instead of gRPC", # Links (outgoing) "relates": ["FACT_http_status_codes"], "relates_back": ["MEM_discussed_grpc"], "supports": ["GOAL_api_interoperability"], "supports_back": [], "depends": ["FACT_json_spec"], "depends_back": [], "supersedes": ["DEC_old_grpc_plan"], "supersedes_back": [], "contradicts": ["Q_when_should_we_use_grpc"], "contradicts_back": [], "example_of": [], "example_of_back": ["PREF_rest_conventions"] } ``` -------------------------------- ### Initialize Memory Workspace via CLI Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Initializes a new memory workspace in a specified directory with a given project name and installs necessary dependencies. ```bash # Initialize memory init ./.memories --name "My Project" --install ``` -------------------------------- ### Memory Recall Tool Input Example Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Example of input parameters for the `memory_recall` tool. This tool searches memories by query and/or tags, with options for filtering, formatting, and limiting results. ```json { "query": "api timeout", "tag": "topic:api,repo:backend", "format": "brief", "limit": 10, "expand": 1 } ``` -------------------------------- ### Initialize a new memory workspace Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Use `memory init` to create a new memory workspace. Specify the directory and optionally provide a project name and install dependencies. ```bash memory init ./my-memories --name "My Project" --install ``` -------------------------------- ### CLI Data Flow Example: Search (Recall Command) Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Details the step-by-step process for the 'recall' command, from user input to formatted output, including filtering and graph expansion. ```text User Input: "memory recall api --tag topic:api --format brief" ↓ cli.cmd_recall() ├── find_workspace() → workspace path ├── load_needs(workspace) → dict[id: need] ├── text_match(need, "api") → filter ├── tag_match(need, ["topic:api"]) → filter ├── expand_graph() → add neighbors (1 hop default) ├── _sort_needs() → sort results └── _output() → format_brief() → display ``` -------------------------------- ### CLI Data Flow Example: Add Command Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Illustrates the data flow for the 'add' command in the CLI, from argument parsing to RST generation and optional rebuild. ```text argparse → cmd_add() ├── find_workspace() ├── generate_rst_directive() ├── append_to_rst() └── (optional) run_rebuild() ``` -------------------------------- ### Exit Status Examples Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Illustrates successful command execution and common failure scenarios, such as workspace not found or memory not found. ```bash # Success $ memory add mem "First note" --tags "topic:example" --rebuild && echo "OK" Added MEM_first_note → /path/to/workspace/memory/observations.rst OK ``` ```bash # Failure — workspace not found $ memory recall test Error: No memory workspace found. Run 'memory init ' to create one, or set MEMORY_DIR. ``` ```bash # Failure — memory not found $ memory get NONEXISTENT Memory 'NONEXISTENT' not found. ``` -------------------------------- ### Setup MCP Server for Claude Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Configure the MCP server for Claude using stdio transport. Specify the memory directory via environment variables. ```bash claude mcp add --transport stdio --env MEMORY_DIR=/path/to/.memories memory -- memory-mcp-stdio ``` -------------------------------- ### Initialize Memory Workspace with Python Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Initializes a memory workspace using the Python library, specifying the directory, project name, author, and whether to install dependencies. ```python from ai_memory_protocol.scaffold import init_workspace from pathlib import Path init_workspace( directory=Path(".memories"), project_name="My Project", author="Jane Doe", install_deps=True # Creates .venv with dependencies ) ``` -------------------------------- ### CLI Data Flow Example: Add Memory Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Shows the data flow for adding a new memory via the CLI, including RST directive generation and optional Sphinx rebuild. ```text User Input: "memory add fact 'API runs on port 8080' --tags 'topic:api' --rebuild" ↓ cli.cmd_add() ├── find_workspace() → workspace path ├── generate_rst_directive( │ mem_type="fact", │ title="API runs on port 8080", │ tags=["topic:api"], │ ... │ ) → RST string ├── append_to_rst(workspace, "fact", directive) │ └── Writes to memory/facts.rst (or facts_002.rst if needed) └── (optional) run_rebuild() └── sphinx-build → needs.json ``` -------------------------------- ### Initialize New Memory Workspace Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/scaffold.md Use this function to create a new memory workspace with all necessary files and configurations. It can optionally install project dependencies into a virtual environment. ```python from ai_memory_protocol.scaffold import init_workspace from pathlib import Path # Create and initialize workspace init_workspace( directory=Path(".memories"), project_name="My Project", author="Jane Doe", install_deps=True # Creates .venv with dependencies ) # Output: # Initialized memory workspace at /path/to/.memories # Created 14 files: # conf.py # index.rst # memory/index.rst # ... (other files) # Dependencies installed in /path/to/.memories/.venv # # Next steps: # cd /path/to/.memories # memory add mem 'First observation' --tags 'topic:example' # memory rebuild # memory recall example ``` -------------------------------- ### Get Full Memory Details Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Retrieve detailed information for a specific memory using its ID. ```bash memory get FACT_api_runs_on_port_8080 ``` -------------------------------- ### CLI Data Flow Example: Update Metadata Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Illustrates the process for updating memory metadata using the CLI, including field modification and tag addition, noting the need for a manual rebuild. ```text User Input: "memory update DEC_x --confidence high --add-tags 'tier:core'" ↓ cli.cmd_update() ├── find_workspace() → workspace path ├── update_field_in_rst(workspace, "DEC_x", "confidence", "high") │ └── Find "DEC_x" in RST files, update :confidence: ├── add_tags_in_rst(workspace, "DEC_x", ["tier:core"]) │ └── Merge with existing tags └── (implicit) run_rebuild() └── User must run "memory rebuild" ``` -------------------------------- ### Workspace Auto-Detection Examples Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Demonstrates how the CLI auto-detects the memory workspace. This can be done by changing the directory, setting the MEMORY_DIR environment variable, or explicitly providing the directory with `--dir`. ```bash # Auto-detect from current directory cd ~/.memories && memory recall api ``` ```bash # Set environment variable export MEMORY_DIR=/path/to/.memories memory recall api ``` ```bash # Explicit --dir memory --dir /path/to/.memories recall api ``` -------------------------------- ### View a specific memory Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Use `memory get` to retrieve a specific memory by its ID. The output includes full metadata and the body text. ```bash memory get DEC_rest_framework ``` -------------------------------- ### Load and Filter Memories in Python Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Loads memories from a workspace, filters for API-related memories that are not deprecated, and formats them for LLM context. Requires the ai_memory_protocol library to be installed. ```python from ai_memory_protocol.engine import find_workspace, load_needs from ai_memory_protocol.formatter import format_context_pack # Load memories workspace = find_workspace() needs = load_needs(workspace) # Filter and format api_memories = { k: v for k, v in needs.items() if "topic:api" in v.get("tags", []) and v.get("status") != "deprecated" } # Output for LLM context print(format_context_pack(api_memories, show_body=False)) ``` -------------------------------- ### Mapping Memory Types to Human-Readable Labels Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/types.md Provides human-readable labels for each memory type, facilitating easier understanding and interaction with memory data. For example, 'mem' is displayed as 'Observation'. ```python TYPE_LABELS = { "mem": "Observation", "dec": "Decision", "fact": "Fact", "pref": "Preference", "risk": "Risk", "goal": "Goal", "q": "Open Question", } ``` -------------------------------- ### Retrieve Full Memory Details Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Use this command to get the complete content, including title, body, and metadata, of a specific memory. This command is typically used after identifying relevant memory IDs through a brief recall. ```bash memory get DEC_handler_context_pattern ``` -------------------------------- ### Recall Memories by Format and Limit Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md This command retrieves a brief list of the most recent memories, sorted by creation date. It's useful for starting a session or getting a quick overview of recent activity. ```bash recall --format brief --limit 20 --sort newest ``` -------------------------------- ### Initialize Workspace with Default Values Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Demonstrates the default parameters used when initializing a workspace. The `directory` is set to ".memories", and `project_name` and `author` have default values. `install_deps` is set to `False` by default. ```python init_workspace( directory=Path(".memories"), project_name="AI Memory Protocol", # Default author="bburda", # Default install_deps=False # Optional ) ``` -------------------------------- ### Configure MCP Server in .vscode/mcp.json Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Set up the MCP server for VS Code (GitHub Copilot) by defining the command and environment variables in .vscode/mcp.json. ```json { "servers": { "memory": { "command": "memory-mcp-stdio", "env": { "MEMORY_DIR": "${workspaceFolder}/.memories" } } } } ``` -------------------------------- ### Create MCP Server Instance Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Create and configure an MCP server instance using the `create_mcp_server` function. The server is ready to use with stdio transport by default. ```python from ai_memory_protocol.mcp_server import create_mcp_server server = create_mcp_server() # Server is ready to use with stdio transport ``` -------------------------------- ### Set MEMORY_DIR Environment Variable Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Example of setting the MEMORY_DIR environment variable to override workspace auto-detection. ```bash export MEMORY_DIR=/path/to/.memories memory recall api ``` -------------------------------- ### Discover Tags via CLI Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Lists available tags that match a given prefix. ```bash # Discover tags memory tags --prefix topic ``` -------------------------------- ### create_mcp_server Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Creates and configures the MCP server with all memory tools. This function initializes the server, making it ready for use with transports like stdio. ```APIDOC ## create_mcp_server ### Description Create and configure the MCP server with all memory tools. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Method * Not applicable (Python function) ### Endpoint * Not applicable (Python function) ### Returns * `Server` - Configured MCP Server instance (from `mcp` SDK). ### Raises * `ImportError` if MCP SDK not installed. ### Example ```python from ai_memory_protocol.mcp_server import create_mcp_server server = create_mcp_server() # Server is ready to use with stdio transport ``` ``` -------------------------------- ### Explore related memories Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Use `memory related` to explore memories connected through the graph. Specify the starting memory ID and the number of hops to traverse. ```bash memory related DEC_rest_framework --hops 2 ``` -------------------------------- ### memory_get Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Retrieves the full details of a specific memory using its unique ID. This is typically used after a `memory_recall` to get complete information about a selected memory. ```APIDOC ## memory_get ### Description Get full details of a specific memory by ID. The DRILL step — always use after `memory_recall(format='brief')` to read full details of specific memories. ### Method * Not applicable (Tool function) ### Endpoint * Not applicable (Tool function) ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **id** (string) - Required - Memory ID (e.g., DEC_rest_framework) ### Request Example ```json { "id": "DEC_rest_framework" } ``` ### Response #### Success Response * Full formatted memory with all metadata and body text. ``` -------------------------------- ### Package Entry Points Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Defines the command-line scripts for the 'ai-memory-protocol' package as specified in 'pyproject.toml'. These entry points allow users to execute the CLI and MCP server directly from the command line. ```toml [project.scripts] memory = "ai_memory_protocol.cli:main" memory-mcp-stdio = "ai_memory_protocol.mcp_server:main_stdio" ``` -------------------------------- ### Load and Iterate Needs Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/need-object.md Demonstrates how to load all needs from a workspace and iterate through them to print their ID, title, and confidence. ```python from ai_memory_protocol.engine import find_workspace, load_needs workspace = find_workspace() all_needs = load_needs(workspace) # dict[id: need] for need_id, need in all_needs.items(): print(f"{need_id}: {need['title']} ({need['confidence']})") ``` -------------------------------- ### Test CLI Version Source: https://github.com/bburda/ai_memory_protocol/blob/main/CONTRIBUTING.md Verify the command-line interface is accessible and check its version. ```bash memory --version ``` -------------------------------- ### Recall Memories by Tag and Format Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Recall memories related to a specific topic in a brief format. This is useful when starting a new task or focusing on a particular subject area. ```bash recall --tag topic: --format brief ``` -------------------------------- ### Module Graph Overview Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Visual representation of the module dependencies and entry points for CLI and MCP server. ```text cli.py (entry point) ├── engine.py (workspace discovery, search, graph) ├── formatter.py (output formatting) ├── rst.py (RST generation and editing) ├── scaffold.py (workspace initialization) └── config.py (types, constants, defaults) mcp_server.py (MCP entry point) ├── engine.py (same search/traversal) ├── formatter.py (same formatting) ├── rst.py (same editing) └── config.py (same types) config.py (core definitions — used by all) ├── Memory types (mem/dec/fact/pref/risk/goal/q) ├── Type-to-file mapping ├── Confidence levels ├── Link types └── Context pack ordering ``` -------------------------------- ### main_stdio() Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Runs the MCP server using the stdio transport protocol. Environment variables can be used to specify the memory directory. ```APIDOC ## main_stdio() ### Description Run the MCP server over stdio transport. ### Example ```bash memory-mcp-stdio # Or with custom workspace MEMORY_DIR=/path/to/.memories memory-mcp-stdio ``` ``` -------------------------------- ### Expanding Graph from Seed IDs Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/need-object.md Utilizes the `expand_graph()` function to traverse the need graph starting from a set of seed IDs. Specify the number of hops to control the depth of the traversal. ```python from ai_memory_protocol.engine import expand_graph seed_ids = {"DEC_rest_framework"} related = expand_graph(needs, seed_ids, hops=2) # related now includes: # - DEC_rest_framework (seed) # - All memories that link to/from it (1 hop) # - All memories linked from those (2 hops) ``` -------------------------------- ### API Reference - Scaffold Module Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Function for initializing a new memory workspace. ```APIDOC ## API Reference - Scaffold Module ### Description Function for initializing a new memory workspace. ### Functions - `init_workspace()`: Create a new memory workspace with all files. ``` -------------------------------- ### Format Need Fully Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Use `format_full` for a comprehensive, markdown-formatted output of a single need, suitable for deep inspection. This format includes all fields, metadata, links, and the full body text. ```python from ai_memory_protocol.formatter import format_full need = load_needs(workspace)["DEC_rest_framework"] print(format_full(need)) ``` -------------------------------- ### Check for Stale Memories Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Run this command periodically, especially at the start of long sessions, to identify and manage expired or overdue memories. This helps maintain the accuracy and relevance of the memory graph. ```bash memory stale ``` -------------------------------- ### format_context_pack Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Organizes multiple need objects into a structured prompt section for AI context windows, grouped by type and ordered by trust level. Optionally includes body text for each memory. ```APIDOC ## `format_context_pack(needs: dict[str, Any], show_body: bool = False) -> str` ### Description Structured prompt section for AI context windows. Groups needs by type, ordered by trust level (facts first, questions last). Uses `format_compact()` for each entry. This is the default format returned by `memory recall` — optimized for fitting many results in LLM context windows. ### Parameters #### Parameters - **needs** (`dict[str, Any]`) - Required - Dict of multiple needs (from search result) - **show_body** (`bool`) - Optional - Default: `False` - Include body text for each memory ### Returns `str` — Markdown formatted section organized by type and trust level. ### Organization Order fact → dec → pref → goal → mem → risk → q ### Example ```python from ai_memory_protocol.formatter import format_context_pack from ai_memory_protocol.engine import load_needs workspace = find_workspace() needs = load_needs(workspace) # Get subset of memories subset = {k: v for k, v in needs.items() if "topic:api" in v.get("tags", [])} output = format_context_pack(subset, show_body=False) print(output) # Outputs: # ## Recalled Memories (3 results) # # ### Facts (verified, high trust) # [FACT_gateway_port] ... # # ### Decisions (with rationale) # [DEC_rest_framework] ... ``` ``` -------------------------------- ### Format Multiple Needs as Context Pack Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Use `format_context_pack` to structure multiple needs into a prompt section for AI context windows. It groups needs by type and trust level, using `format_compact` for each entry and optionally including body text. ```python from ai_memory_protocol.formatter import format_context_pack from ai_memory_protocol.engine import load_needs workspace = find_workspace() needs = load_needs(workspace) # Get subset of memories subset = {k: v for k, v in needs.items() if "topic:api" in v.get("tags", [])} output = format_context_pack(subset, show_body=False) print(output) ``` -------------------------------- ### AI Memory Protocol CLI Reference Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Overview of available commands for managing AI memories. Key flags for 'recall' are detailed. ```bash memory init # Create a new workspace memory add "" [options] # Record a memory memory recall [query] [--tag ...] [--format brief|compact|context|json] memory get <ID> # Full details of one memory memory related <ID> [--hops N] # Graph walk from a memory memory list [--type TYPE] [--status S] # Browse all memories memory update <ID> [--confidence ...] [--add-tags ...] [--body ...] [--title ...] memory deprecate <ID> [--by NEW_ID] # Mark as deprecated memory tags [--prefix PREFIX] # Discover tags in use memory stale # Find expired/overdue memories memory review # Show memories needing review memory rebuild # Rebuild needs.json Key flags for `recall`: - `--format brief` — ultra-compact, minimal tokens - `--body` — include body text (off by default) - `--sort newest|oldest|confidence|updated` - `--limit N` — cap results - `--expand 0` — disable graph expansion - `--stale` — only expired/review-overdue ``` -------------------------------- ### CLI Reference Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Documentation for the command-line interface, including all subcommands and their options. ```APIDOC ## CLI Reference ### Description Documentation for the command-line interface, including all subcommands and their options. ### Subcommands - `init`: Initialize a new workspace. - `add`: Add a new memory. - `recall`: Search memories. - `get`: Fetch a specific memory. - `related`: Find related memories. - `list`: List memories. - `update`: Update an existing memory. - `deprecate`: Mark a memory as deprecated. - `review`: Review memories due for review. - `tags`: List all available tags. - `stale`: Find stale memories. - `prune`: Remove old memories. - `rebuild`: Regenerate needs.json. ``` -------------------------------- ### Configure MCP Server in .mcp.json Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Define MCP server configuration in a project's .mcp.json file for project-scoped settings. ```json { "mcpServers": { "memory": { "type": "stdio", "command": "memory-mcp-stdio", "env": { "MEMORY_DIR": "/path/to/.memories" } } } } ``` -------------------------------- ### API Reference - Engine Module Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Functions for workspace discovery, loading configuration, searching memories, and graph traversal. ```APIDOC ## API Reference - Engine Module ### Description Functions for workspace discovery, loading configuration, searching memories, and graph traversal. ### Functions - `find_workspace()`: Locate the memory workspace. - `load_needs()`: Parse needs.json into a dict. - `text_match()`: Filter memories by text. - `tag_match()`: Filter memories by tags. - `expand_graph()`: Walk the memory graph. - `run_rebuild()`: Regenerate needs.json. ``` -------------------------------- ### format_brief Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Generates an ultra-compact, single-line string representation of a need object, suitable for minimal token usage in context windows. It displays the ID, Title, confidence, and key tags. ```APIDOC ## `format_brief(need: dict[str, Any]) -> str` ### Description Ultra-compact single line — minimal tokens for context window. Produces minimal-token output suitable for peeking at search results without reading full details. Shows only `topic:` and `repo:` tags (most contextually useful). ### Parameters #### Parameters - **need** (`dict[str, Any]`) - Required - Need object from `load_needs()` ### Returns `str` — Single-line formatted memory reference. ### Format `[ID] Title (confidence) {key-tags}` ### Example ```python from ai_memory_protocol.formatter import format_brief need = { "id": "DEC_rest_framework", "title": "Use tl::expected over exceptions", "confidence": "high", "tags": ["topic:error-handling", "repo:backend"] } print(format_brief(need)) # Output: [DEC_rest_framework] Use tl::expected over exceptions (high) {topic:error-handling,repo:backend} ``` ``` -------------------------------- ### Sphinx Metadata Configuration Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Basic project metadata for Sphinx documentation. ```python project = "<project_name>" copyright = "<year>, <author>" author = "<author>" version = "0.1" release = "0.1.0" ``` -------------------------------- ### Add Sphinx Extensions Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Shows how to add necessary Sphinx extensions to the `conf.py` file. Ensure that `sphinx_needs`, `sphinx_design`, and `sphinxcontrib.plantuml` are included for full functionality. ```python extensions = [ "sphinx_needs", "sphinx_design", "sphinxcontrib.plantuml", # Your custom extensions here ] ``` -------------------------------- ### Format Need Compactly with Body Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Use `format_compact` for a one or two-line representation suitable for quick scanning. Set `show_body=True` to optionally include a truncated body text (up to 500 characters) along with full metadata. ```python from ai_memory_protocol.formatter import format_compact need = { "id": "FACT_gateway_port", "title": "API runs on port 8080", "status": "promoted", "confidence": "high", "tags": ["topic:api", "repo:backend"], "relates": [], "description": "Gateway listens on 0.0.0.0:8080 by default" } print(format_compact(need, show_body=True)) ``` -------------------------------- ### Project Structure Overview Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md This snippet shows the directory structure of the ai_memory_protocol project, highlighting key files and directories like pyproject.toml, src/, and configuration files. ```text ai_memory_protocol/ ├── pyproject.toml # Package definition, CLI + MCP entry points ├── README.md ├── LICENSE # Apache 2.0 ├── CONTRIBUTING.md ├── .pre-commit-config.yaml ├── .github/workflows/ci.yml └── src/ └── ai_memory_protocol/ ├── __init__.py ├── cli.py # CLI (argparse, 12 subcommands) ├── mcp_server.py # MCP server (8 tools, stdio transport) ├── config.py # Type definitions, constants ├── engine.py # Workspace detection, search, graph walk ├── formatter.py # Output formatting (brief/compact/context/json) ├── rst.py # RST generation, editing, file splitting └── scaffold.py # Workspace scaffolding (init command) ``` -------------------------------- ### AI Memory Protocol CLI Entry Point Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Defines the command-line interface entry points for the AI Memory Protocol package. ```text Entry Points (from pyproject.toml): - memory — CLI command - memory-mcp-stdio — MCP server over stdio ``` -------------------------------- ### Module Import Hierarchy Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Illustrates the dependency structure of the ai-memory-protocol modules, showing leaf modules, second-level modules, third-level modules, and top-level modules. This acyclic graph ensures modularity and testability. ```text Leaf modules (no internal dependencies): config.py Second-level (depend only on config): engine.py (depends on config.LINK_FIELDS) formatter.py (depends on config.CONTEXT_PACK_ORDER, etc.) rst.py (depends on config.TYPE_FILES, etc.) Third-level (depend on second-level): scaffold.py (depends on config) Top-level (depend on all): cli.py (depends on all) mcp_server.py (depends on all) ``` -------------------------------- ### Run Linting Checks Source: https://github.com/bburda/ai_memory_protocol/blob/main/CONTRIBUTING.md Execute Ruff for checking code style and formatting on the source files. ```bash ruff check src/ && ruff format --check src/ ``` -------------------------------- ### Recall Memories by Keywords Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Search memories using keywords, which can be helpful for finding solutions to errors or failures. This should be the first reaction when encountering a problem. ```bash recall --tag topic:<X> --type mem,fact ``` -------------------------------- ### Add MCP Server to Claude Desktop Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Configure Claude Desktop to use the MCP server via stdio transport, specifying the memory directory. ```bash # Add the MCP server globally claude mcp add --transport stdio --env MEMORY_DIR=/path/to/.memories memory -- memory-mcp-stdio ``` -------------------------------- ### Sphinx-Needs Quality Gates Configuration Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Configures build-time validation rules (quality gates) for Sphinx-Needs. ```python needs_warnings = [ "missing_topic_tag", "empty_body", "deprecated_without_supersede", "tag_case_mismatch", "missing_repo_tag", "isolated_decision", "draft_too_short", "suspicious_high_confidence", "isolated_memory", ] ``` -------------------------------- ### Filtering Needs by Text, Tags, Status, and Expiration Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/need-object.md Demonstrates various filtering techniques for 'needs' objects, including free-text matching, tag-based filtering, status checks, and expiration date comparisons. Use these methods to efficiently retrieve specific needs from a loaded dataset. ```python from datetime import date from ai_memory_protocol.engine import load_needs, text_match, tag_match needs = load_needs(workspace) today = date.today().isoformat() # Free-text filter matching = [n for n in needs.values() if text_match(n, "api timeout")] # Tag filter (AND logic) api_needs = [n for n in needs.values() if tag_match(n, ["topic:api"])] # Status filter active = [n for n in needs.values() if n.get("status") == "active"] # Expired filter expired = [n for n in needs.values() if n.get("expires_at") and n.get("expires_at") <= today] # Composite filter candidates = [n for n in needs.values() if n.get("status") != "deprecated" and n.get("type") == "fact" and text_match(n, "api")] ``` -------------------------------- ### List All Tags Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Use to list all tags currently in use, with their counts, grouped by prefix. Filter by a specific prefix using the `--prefix` option. ```bash memory tags ``` ```bash memory tags --prefix topic ``` -------------------------------- ### MCP Server Core Functions Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Outlines the core factory, build, and registration functions for the MCP server, which exposes memory tools to LLM clients. ```text create_mcp_server() — Factory for MCP Server _build_tools() — Define MCP tool schemas _register_tools() — Register tool listing handler _register_handlers() — Register tool call handlers ``` -------------------------------- ### format_compact Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Generates a one or two-line string representation of a need object, optionally including a truncated body. It displays full metadata including ID, title, status, confidence, tags, and links. ```APIDOC ## `format_compact(need: dict[str, Any], show_body: bool = False) -> str` ### Description One-liner (optionally two) per memory — for quick scanning. Shows full metadata: id, title, status, confidence, tags, and links. If `show_body=True`, appends first 500 characters of body text. ### Parameters #### Parameters - **need** (`dict[str, Any]`) - Required - Need object from `load_needs()` - **show_body** (`bool`) - Optional - Default: `False` - Include truncated body text (up to 500 chars) ### Returns `str` — One or two lines with full metadata and optional body snippet. ### Example ```python from ai_memory_protocol.formatter import format_compact need = { "id": "FACT_gateway_port", "title": "API runs on port 8080", "status": "promoted", "confidence": "high", "tags": ["topic:api", "repo:backend"], "relates": [], "description": "Gateway listens on 0.0.0.0:8080 by default" } print(format_compact(need, show_body=True)) ``` ``` -------------------------------- ### format_full Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Generates a comprehensive, markdown-formatted string representation of a need object, including all fields and the full body text. This is intended for deep inspection of a single memory. ```APIDOC ## `format_full(need: dict[str, Any]) -> str` ### Description Full metadata — for deep inspection of a single memory. Comprehensive format showing all fields: type, status, confidence, scope, tags, metadata (source, owner, created_at, updated_at, review_after, expires_at), all link types, and full body text. ### Parameters #### Parameters - **need** (`dict[str, Any]`) - Required - Need object from `load_needs()` ### Returns `str` — Markdown formatted full details including body text. ### Example ```python from ai_memory_protocol.formatter import format_full need = load_needs(workspace)["DEC_rest_framework"] print(format_full(need)) # Outputs comprehensive details with all links and body ``` ``` -------------------------------- ### Format Need Briefly Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/formatter.md Use `format_brief` for an ultra-compact, single-line representation of a need, ideal for minimizing tokens in context windows. It displays ID, title, confidence, and key tags. ```python from ai_memory_protocol.formatter import format_brief need = { "id": "DEC_rest_framework", "title": "Use tl::expected over exceptions", "confidence": "high", "tags": ["topic:error-handling", "repo:backend"] } print(format_brief(need)) ``` -------------------------------- ### Makefile Build Targets Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Provides common Makefile targets for building and cleaning the Sphinx documentation. `make html` builds the HTML output and `needs.json`, while `make clean` removes build artifacts. ```bash make html # Build HTML + needs.json make clean # Remove build artifacts make rebuild # Equivalent to 'memory rebuild' ``` -------------------------------- ### Recall Memories by Tag (Brief Format) Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Use this command to quickly scan memory titles associated with a specific tag. Set expand to 0 to avoid retrieving body text, minimizing token usage. This is the first step in a two-phase recall process. ```bash memory recall --tag topic:gateway --format brief --expand 0 ``` -------------------------------- ### Search Memories by Tag via CLI Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Searches for memories tagged with 'topic:api' and displays a brief summary of the results. ```bash # Search memory recall api --tag topic:api --format brief ``` -------------------------------- ### Sphinx Extensions Configuration Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md List of enabled Sphinx extensions, including sphinx-needs and sphinx-design. ```python extensions = [ "sphinx_needs", "sphinx_design", "sphinxcontrib.plantuml", ] ``` -------------------------------- ### Recall Memories by Tag and Type (Coding Style) Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Retrieve preferences or conventions related to coding style for a specific topic. This is useful before implementing a pattern. ```bash recall --tag intent:coding-style --type pref ``` -------------------------------- ### Graph Expansion Logic Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Explains how the `expand_graph` function works by iteratively collecting related memories based on specified hops. ```text User Input: "memory recall --expand 2" (from initial search of 3 matches) ↓ expand_graph(needs, {ID1, ID2, ID3}, hops=2) ├── Hop 1: Collect all relates, supports, depends, supersedes, contradicts, example_of │ + Their _back variants (incoming) └── Hop 2: Repeat from new frontier ↓ Result: {original 3} + {hop 1 neighbors} + {hop 2 neighbors} ``` -------------------------------- ### Format Need Object Compactly Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/need-object.md Formats a need object into a compact string representation, showing key fields like ID, title, status, confidence, tags, and links. ```python from ai_memory_protocol.formatter import format_compact need = all_needs["DEC_rest_framework"] print(format_compact(need)) ``` -------------------------------- ### Add a New Memory with Superseding Option Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md When knowledge changes, record a new memory that supersedes an old one by referencing its ID. This ensures that outdated information is marked and new information is prioritized. ```bash --supersedes OLD_ID ``` -------------------------------- ### API Reference - MCP Server Module Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Functions for creating and interacting with the MCP server for memory operations. ```APIDOC ## API Reference - MCP Server Module ### Description Functions for creating and interacting with the MCP server for memory operations. ### Functions - `create_mcp_server()`: Create the MCP server. - `memory_recall`: Search memories. - `memory_get`: Fetch a specific memory. - `memory_add`: Record a new memory. - `memory_update`: Edit existing memory. - `memory_deprecate`: Mark as deprecated. - `memory_tags`: List all tags. - `memory_stale`: Find expired/review-due memories. - `memory_rebuild`: Regenerate needs.json. ``` -------------------------------- ### Engine Module Data Flow Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/modules.md Illustrates the data processing pipeline within the engine module, from workspace loading to graph expansion. ```text Workspace → needs.json → load_needs() → dict[id: need] ↓ text_match() / tag_match() ↓ expand_graph() ↓ dict[id: need] (filtered/expanded) ``` -------------------------------- ### Sphinx-Needs Status Workflow Configuration Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Defines the status workflow for memory lifecycle management in Sphinx-Needs. ```python needs_statuses = [ {"name": "draft", "description": "Freshly captured, not yet validated"}, {"name": "active", "description": "Validated and current"}, {"name": "promoted", "description": "Elevated to core knowledge"}, {"name": "deprecated", "description": "Superseded or no longer valid"}, {"name": "review", "description": "Flagged for review"}, ] ``` -------------------------------- ### Safe Field Access with Default Values Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/need-object.md Demonstrates safe access to potentially missing fields in a need object using the .get() method with default values. ```python # Fields may not exist in all needs confidence = need.get("confidence", "unknown") owner = need.get("owner", "") review_date = need.get("review_after", "") ``` -------------------------------- ### Change HTML Theme Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/configuration.md Demonstrates how to set the HTML theme for Sphinx documentation in `conf.py`. Common themes like `sphinx_rtd_theme` or `alabaster` can be specified. ```python html_theme = "sphinx_rtd_theme" # or "alabaster", etc. ``` -------------------------------- ### Record a new memory Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Use `memory add` to record a new memory of a specific type. Provide a title, tags, confidence level, and an optional body. The `--rebuild` flag can be used to auto-rebuild needs.json. ```bash memory add fact "API timeout is 30s" \ --tags "topic:api,repo:backend" \ --confidence high \ --body "Gateway timeout configured to 30000ms (30 seconds)" \ --rebuild ``` -------------------------------- ### Check Pending Reviews Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Use these commands to check for items that are due for review or have become stale. ```bash memory review memory stale ``` -------------------------------- ### Run MCP Server over StdIO Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/mcp-server.md Execute the MCP server using stdio transport. Can be configured with a custom memory directory via environment variable. ```bash memory-mcp-stdio # Or with custom workspace MEMORY_DIR=/path/to/.memories memory-mcp-stdio ``` -------------------------------- ### Rebuild Needs Index Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/cli-reference.md Use to rebuild the needs.json file from RST sources. This command provides a build status summary. ```bash memory rebuild ``` -------------------------------- ### API Reference - Formatter Module Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Functions for formatting memory output in various styles. ```APIDOC ## API Reference - Formatter Module ### Description Functions for formatting memory output in various styles. ### Functions - `format_brief()`: Ultra-compact one-liner output. - `format_compact()`: One-liner with metadata. - `format_full()`: Complete details with body. - `format_context_pack()`: Grouped for LLM context. ``` -------------------------------- ### Run Sphinx Build with `run_rebuild` Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/api-reference/engine.md Execute `run_rebuild` to regenerate the `needs.json` file using Sphinx. This function handles finding the `sphinx-build` executable and returns a success status and a message summarizing the build process. It is designed to not raise exceptions on build failure. ```python from ai_memory_protocol.engine import run_rebuild workspace = Path(".") # Replace with your actual workspace path success, message = run_rebuild(workspace) if success: print(message) else: print(f"Build failed: {message}") ``` -------------------------------- ### Retrieve Full Memory Details via CLI Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Retrieves and displays the complete details of a specific memory using its ID. ```bash # Get full details memory get FACT_api_timeout ``` -------------------------------- ### AI Memory Protocol Package Structure Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/README.md Overview of the directory structure for the AI Memory Protocol Python package. ```python ai_memory_protocol/ ├── __init__.py # Package definition (minimal exports) ├── config.py # Types, constants, defaults ├── engine.py # Search, workspace, graph operations ├── formatter.py # Output formatting ├── rst.py # RST generation and editing ├── scaffold.py # Workspace initialization ├── cli.py # CLI entry point (13 subcommands) └── mcp_server.py # MCP server (8 tools) ``` -------------------------------- ### Format Need Object Briefly Source: https://github.com/bburda/ai_memory_protocol/blob/main/_autodocs/need-object.md Formats a need object into a brief string representation, including ID, title, confidence, and tags. ```python from ai_memory_protocol.formatter import format_brief need = all_needs["DEC_rest_framework"] print(format_brief(need)) ``` -------------------------------- ### Rebuild Memory Index Source: https://github.com/bburda/ai_memory_protocol/blob/main/README.md Use this flag when adding new memories to ensure they are immediately searchable and indexed. This is crucial for making new information discoverable. ```bash --rebuild ```