CLAUDE.md - Basic Memory Project Guide
Project Overview
Basic Memory is a local-first knowledge management system built on the Model Context Protocol (MCP). It enables
bidirectional communication between LLMs (like Claude) and markdown files, creating a personal knowledge graph that can
be traversed using links between documents.
CODEBASE DEVELOPMENT
Project information
See the README.md file for a project overview.
Build and Test Commands
- Install:
make install or pip install -e ".[dev]"
- Run tests:
uv run pytest -p pytest_mock -v or make test
- Single test:
pytest tests/path/to/test_file.py::test_function_name
- Lint:
make lint or ruff check . --fix
- Type check:
make type-check or uv run pyright
- Format:
make format or uv run ruff format .
- Run all code checks:
make check (runs lint, format, type-check, test)
- Create db migration:
make migration m="Your migration message"
- Run development MCP Inspector:
make run-inspector
Note: Project supports Python 3.10+
Code Style Guidelines
- Line length: 100 characters max
- Python 3.12+ with full type annotations
- Format with ruff (consistent styling)
- Import order: standard lib, third-party, local imports
- Naming: snake_case for functions/variables, PascalCase for classes
- Prefer async patterns with SQLAlchemy 2.0
- Use Pydantic v2 for data validation and schemas
- CLI uses Typer for command structure
- API uses FastAPI for endpoints
- Follow the repository pattern for data access
- Tools communicate to api routers via the httpx ASGI client (in process)
Codebase Architecture
/alembic - Alembic db migrations
/api - FastAPI implementation of REST endpoints
/cli - Typer command-line interface
/markdown - Markdown parsing and processing
/mcp - Model Context Protocol server implementation
/models - SQLAlchemy ORM models
/repository - Data access layer
/schemas - Pydantic models for validation
/services - Business logic layer
/sync - File synchronization services
Development Notes
- MCP tools are defined in src/basic_memory/mcp/tools/
- MCP prompts are defined in src/basic_memory/mcp/prompts/
- MCP tools should be atomic, composable operations
- Use
textwrap.dedent() for multi-line string formatting in prompts and tools
- MCP Prompts are used to invoke tools and format content with instructions for an LLM
- Schema changes require Alembic migrations
- SQLite is used for indexing and full text search, files are source of truth
- Testing uses pytest with asyncio support (strict mode)
- Test database uses in-memory SQLite
- Avoid creating mocks in tests in most circumstances.
- Each test runs in a standalone environment with in memory SQLite and tmp_file directory
Async Client Pattern (Important!)
All MCP tools and CLI commands use the context manager pattern for HTTP clients:
from basic_memory.mcp.async_client import get_client
async def my_mcp_tool():
async with get_client() as client:
# Use client for API calls
response = await call_get(client, "/path")
return response
Do NOT use:
- ❌
from basic_memory.mcp.async_client import client (deprecated module-level client)
- ❌ Manual auth header management
- ❌
inject_auth_header() (deleted)
Key principles:
- Auth happens at client creation, not per-request
- Proper resource management via context managers
- Supports three modes: Local (ASGI), CLI cloud (HTTP + auth), Cloud app (factory injection)
- Factory pattern enables dependency injection for cloud consolidation
For cloud app integration:
from basic_memory.mcp import async_client
# Set custom factory before importing tools
async_client.set_client_factory(your_custom_factory)
See SPEC-16 for full context manager refactor details.
BASIC MEMORY PRODUCT USAGE
Knowledge Structure
- Entity: Any concept, document, or idea represented as a markdown file
- Observation: A categorized fact about an entity (
- [category] content)
- Relation: A directional link between entities (
- relation_type [[Target]])
- Frontmatter: YAML metadata at the top of markdown files
- Knowledge representation follows precise markdown format:
- Observations with [category] prefixes
- Relations with WikiLinks [[Entity]]
- Frontmatter with metadata
Basic Memory Commands
Local Commands:
- Sync knowledge:
basic-memory sync or basic-memory sync --watch
- Import from Claude:
basic-memory import claude conversations
- Import from ChatGPT:
basic-memory import chatgpt
- Import from Memory JSON:
basic-memory import memory-json
- Check sync status:
basic-memory status
- Tool access:
basic-memory tools (provides CLI access to MCP tools)
- Guide:
basic-memory tools basic-memory-guide
- Continue:
basic-memory tools continue-conversation --topic="search"
Cloud Commands (requires subscription):
- Authenticate:
basic-memory cloud login
- Logout:
basic-memory cloud logout
- Bidirectional sync:
basic-memory cloud sync
- Integrity check:
basic-memory cloud check
- Mount cloud storage:
basic-memory cloud mount
- Unmount cloud storage:
basic-memory cloud unmount
MCP Capabilities
Basic Memory exposes these MCP tools to LLMs:
Content Management:
write_note(title, content, folder, tags) - Create/update markdown notes with semantic observations and relations
read_note(identifier, page, page_size) - Read notes by title, permalink, or memory:// URL with knowledge graph awareness
read_content(path) - Read raw file content (text, images, binaries) without knowledge graph processing
view_note(identifier, page, page_size) - View notes as formatted artifacts for better readability
edit_note(identifier, operation, content) - Edit notes incrementally (append, prepend, find/replace, replace_section)
move_note(identifier, destination_path) - Move notes to new locations, updating database and maintaining links
delete_note(identifier) - Delete notes from the knowledge base
Knowledge Graph Navigation:
build_context(url, depth, timeframe) - Navigate the knowledge graph via memory:// URLs for conversation continuity
recent_activity(type, depth, timeframe) - Get recently updated information with specified timeframe (e.g., "1d", "1 week")
list_directory(dir_name, depth, file_name_glob) - Browse directory contents with filtering and depth control
Search & Discovery:
search_notes(query, page, page_size, search_type, types, entity_types, after_date) - Full-text search across all content with advanced filtering options
Project Management:
list_memory_projects() - List all available projects with their status
create_memory_project(project_name, project_path, set_default) - Create new Basic Memory projects
delete_project(project_name) - Delete a project from configuration
get_current_project() - Get current project information and stats
sync_status() - Check file synchronization and background operation status
Visualization:
canvas(nodes, edges, title, folder) - Generate Obsidian canvas files for knowledge graph visualization
MCP Prompts for better AI interaction:
ai_assistant_guide() - Guidance on effectively using Basic Memory tools for AI assistants
continue_conversation(topic, timeframe) - Continue previous conversations with relevant historical context
search(query, after_date) - Search with detailed, formatted results for better context understanding
recent_activity(timeframe) - View recently changed items with formatted output
json_canvas_spec() - Full JSON Canvas specification for Obsidian visualization
Cloud Features (v0.15.0+)
Basic Memory now supports cloud synchronization and storage (requires active subscription):
Authentication:
- JWT-based authentication with subscription validation
- Secure session management with token refresh
- Support for multiple cloud projects
Bidirectional Sync:
- rclone bisync integration for two-way synchronization
- Conflict resolution and integrity verification
- Real-time sync with change detection
- Mount/unmount cloud storage for direct file access
Cloud Project Management:
- Create and manage projects in the cloud
- Toggle between local and cloud modes
- Per-project sync configuration
- Subscription-based access control
Security & Performance:
- Removed .env file loading for improved security
- .gitignore integration (respects gitignored files)
- WAL mode for SQLite performance
- Background relation resolution (non-blocking startup)
- API performance optimizations (SPEC-11)
AI-Human Collaborative Development
Basic Memory emerged from and enables a new kind of development process that combines human and AI capabilities. Instead
of using AI just for code generation, we've developed a true collaborative workflow:
- AI (LLM) writes initial implementation based on specifications and context
- Human reviews, runs tests, and commits code with any necessary adjustments
- Knowledge persists across conversations using Basic Memory's knowledge graph
- Development continues seamlessly across different AI sessions with consistent context
- Results improve through iterative collaboration and shared understanding
This approach has allowed us to tackle more complex challenges and build a more robust system than either humans or AI
could achieve independently.
GitHub Integration
Basic Memory has taken AI-Human collaboration to the next level by integrating Claude directly into the development workflow through GitHub:
GitHub MCP Tools
Using the GitHub Model Context Protocol server, Claude can now:
Repository Management:
- View repository files and structure
- Read file contents
- Create new branches
- Create and update files
Issue Management:
- Create new issues
- Comment on existing issues
- Close and update issues
- Search across issues
Pull Request Workflow:
- Create pull requests
- Review code changes
- Add comments to PRs
This integration enables Claude to participate as a full team member in the development process, not just as a code generation tool. Claude's GitHub account (bm-claudeai) is a member of the Basic Machines organization with direct contributor access to the codebase.
Collaborative Development Process
With GitHub integration, the development workflow includes:
- Direct code review - Claude can analyze PRs and provide detailed feedback
- Contribution tracking - All of Claude's contributions are properly attributed in the Git history
- Branch management - Claude can create feature branches for implementations
- Documentation maintenance - Claude can keep documentation updated as the code evolves
This level of integration represents a new paradigm in AI-human collaboration, where the AI assistant becomes a full-fledged team member rather than just a tool for generating code snippets.
1---2name: claude-md-basic-memory-project-guide3description: Basic Memory is a local-first knowledge management system built on the Model Context Protocol (MCP).4---5# CLAUDE.md - Basic Memory Project Guide67## Project Overview89Basic Memory is a local-first knowledge management system built on the Model Context Protocol (MCP). It enables10bidirectional communication between LLMs (like Claude) and markdown files, creating a personal knowledge graph that can11be traversed using links between documents.1213## CODEBASE DEVELOPMENT1415### Project information1617See the [README.md](README.md) file for a project overview.1819### Build and Test Commands2021- Install: `make install` or `pip install -e ".[dev]"`22- Run tests: `uv run pytest -p pytest_mock -v` or `make test`23- Single test: `pytest tests/path/to/test_file.py::test_function_name`24- Lint: `make lint` or `ruff check . --fix`25- Type check: `make type-check` or `uv run pyright`26- Format: `make format` or `uv run ruff format .`27- Run all code checks: `make check` (runs lint, format, type-check, test)28- Create db migration: `make migration m="Your migration message"`29- Run development MCP Inspector: `make run-inspector`3031**Note:** Project supports Python 3.10+3233### Code Style Guidelines3435- Line length: 100 characters max36- Python 3.12+ with full type annotations37- Format with ruff (consistent styling)38- Import order: standard lib, third-party, local imports39- Naming: snake_case for functions/variables, PascalCase for classes40- Prefer async patterns with SQLAlchemy 2.041- Use Pydantic v2 for data validation and schemas42- CLI uses Typer for command structure43- API uses FastAPI for endpoints44- Follow the repository pattern for data access45- Tools communicate to api routers via the httpx ASGI client (in process)4647### Codebase Architecture4849- `/alembic` - Alembic db migrations50- `/api` - FastAPI implementation of REST endpoints51- `/cli` - Typer command-line interface52- `/markdown` - Markdown parsing and processing53- `/mcp` - Model Context Protocol server implementation54- `/models` - SQLAlchemy ORM models55- `/repository` - Data access layer56- `/schemas` - Pydantic models for validation57- `/services` - Business logic layer58- `/sync` - File synchronization services5960### Development Notes6162- MCP tools are defined in src/basic_memory/mcp/tools/63- MCP prompts are defined in src/basic_memory/mcp/prompts/64- MCP tools should be atomic, composable operations65- Use `textwrap.dedent()` for multi-line string formatting in prompts and tools66- MCP Prompts are used to invoke tools and format content with instructions for an LLM67- Schema changes require Alembic migrations68- SQLite is used for indexing and full text search, files are source of truth69- Testing uses pytest with asyncio support (strict mode)70- Test database uses in-memory SQLite71- Avoid creating mocks in tests in most circumstances.72- Each test runs in a standalone environment with in memory SQLite and tmp_file directory7374### Async Client Pattern (Important!)7576**All MCP tools and CLI commands use the context manager pattern for HTTP clients:**7778```python79from basic_memory.mcp.async_client import get_client8081async def my_mcp_tool():82 async with get_client() as client:83 # Use client for API calls84 response = await call_get(client, "/path")85 return response86```8788**Do NOT use:**89- ❌ `from basic_memory.mcp.async_client import client` (deprecated module-level client)90- ❌ Manual auth header management91- ❌ `inject_auth_header()` (deleted)9293**Key principles:**94- Auth happens at client creation, not per-request95- Proper resource management via context managers96- Supports three modes: Local (ASGI), CLI cloud (HTTP + auth), Cloud app (factory injection)97- Factory pattern enables dependency injection for cloud consolidation9899**For cloud app integration:**100```python101from basic_memory.mcp import async_client102103# Set custom factory before importing tools104async_client.set_client_factory(your_custom_factory)105```106107See SPEC-16 for full context manager refactor details.108109## BASIC MEMORY PRODUCT USAGE110111### Knowledge Structure112113- Entity: Any concept, document, or idea represented as a markdown file114- Observation: A categorized fact about an entity (`- [category] content`)115- Relation: A directional link between entities (`- relation_type [[Target]]`)116- Frontmatter: YAML metadata at the top of markdown files117- Knowledge representation follows precise markdown format:118 - Observations with [category] prefixes119 - Relations with WikiLinks [[Entity]]120 - Frontmatter with metadata121122### Basic Memory Commands123124**Local Commands:**125- Sync knowledge: `basic-memory sync` or `basic-memory sync --watch`126- Import from Claude: `basic-memory import claude conversations`127- Import from ChatGPT: `basic-memory import chatgpt`128- Import from Memory JSON: `basic-memory import memory-json`129- Check sync status: `basic-memory status`130- Tool access: `basic-memory tools` (provides CLI access to MCP tools)131 - Guide: `basic-memory tools basic-memory-guide`132 - Continue: `basic-memory tools continue-conversation --topic="search"`133134**Cloud Commands (requires subscription):**135- Authenticate: `basic-memory cloud login`136- Logout: `basic-memory cloud logout`137- Bidirectional sync: `basic-memory cloud sync`138- Integrity check: `basic-memory cloud check`139- Mount cloud storage: `basic-memory cloud mount`140- Unmount cloud storage: `basic-memory cloud unmount`141142### MCP Capabilities143144- Basic Memory exposes these MCP tools to LLMs:145146 **Content Management:**147 - `write_note(title, content, folder, tags)` - Create/update markdown notes with semantic observations and relations148 - `read_note(identifier, page, page_size)` - Read notes by title, permalink, or memory:// URL with knowledge graph awareness149 - `read_content(path)` - Read raw file content (text, images, binaries) without knowledge graph processing150 - `view_note(identifier, page, page_size)` - View notes as formatted artifacts for better readability151 - `edit_note(identifier, operation, content)` - Edit notes incrementally (append, prepend, find/replace, replace_section)152 - `move_note(identifier, destination_path)` - Move notes to new locations, updating database and maintaining links153 - `delete_note(identifier)` - Delete notes from the knowledge base154155 **Knowledge Graph Navigation:**156 - `build_context(url, depth, timeframe)` - Navigate the knowledge graph via memory:// URLs for conversation continuity157 - `recent_activity(type, depth, timeframe)` - Get recently updated information with specified timeframe (e.g., "1d", "1 week")158 - `list_directory(dir_name, depth, file_name_glob)` - Browse directory contents with filtering and depth control159160 **Search & Discovery:**161 - `search_notes(query, page, page_size, search_type, types, entity_types, after_date)` - Full-text search across all content with advanced filtering options162163 **Project Management:**164 - `list_memory_projects()` - List all available projects with their status165 - `create_memory_project(project_name, project_path, set_default)` - Create new Basic Memory projects166 - `delete_project(project_name)` - Delete a project from configuration167 - `get_current_project()` - Get current project information and stats168 - `sync_status()` - Check file synchronization and background operation status169170 **Visualization:**171 - `canvas(nodes, edges, title, folder)` - Generate Obsidian canvas files for knowledge graph visualization172173- MCP Prompts for better AI interaction:174 - `ai_assistant_guide()` - Guidance on effectively using Basic Memory tools for AI assistants175 - `continue_conversation(topic, timeframe)` - Continue previous conversations with relevant historical context176 - `search(query, after_date)` - Search with detailed, formatted results for better context understanding177 - `recent_activity(timeframe)` - View recently changed items with formatted output178 - `json_canvas_spec()` - Full JSON Canvas specification for Obsidian visualization179180### Cloud Features (v0.15.0+)181182Basic Memory now supports cloud synchronization and storage (requires active subscription):183184**Authentication:**185- JWT-based authentication with subscription validation186- Secure session management with token refresh187- Support for multiple cloud projects188189**Bidirectional Sync:**190- rclone bisync integration for two-way synchronization191- Conflict resolution and integrity verification192- Real-time sync with change detection193- Mount/unmount cloud storage for direct file access194195**Cloud Project Management:**196- Create and manage projects in the cloud197- Toggle between local and cloud modes198- Per-project sync configuration199- Subscription-based access control200201**Security & Performance:**202- Removed .env file loading for improved security203- .gitignore integration (respects gitignored files)204- WAL mode for SQLite performance205- Background relation resolution (non-blocking startup)206- API performance optimizations (SPEC-11)207208## AI-Human Collaborative Development209210Basic Memory emerged from and enables a new kind of development process that combines human and AI capabilities. Instead211of using AI just for code generation, we've developed a true collaborative workflow:2122131. AI (LLM) writes initial implementation based on specifications and context2142. Human reviews, runs tests, and commits code with any necessary adjustments2153. Knowledge persists across conversations using Basic Memory's knowledge graph2164. Development continues seamlessly across different AI sessions with consistent context2175. Results improve through iterative collaboration and shared understanding218219This approach has allowed us to tackle more complex challenges and build a more robust system than either humans or AI220could achieve independently.221222## GitHub Integration223224Basic Memory has taken AI-Human collaboration to the next level by integrating Claude directly into the development workflow through GitHub:225226### GitHub MCP Tools227228Using the GitHub Model Context Protocol server, Claude can now:229230- **Repository Management**:231 - View repository files and structure232 - Read file contents233 - Create new branches234 - Create and update files235236- **Issue Management**:237 - Create new issues238 - Comment on existing issues239 - Close and update issues240 - Search across issues241242- **Pull Request Workflow**:243 - Create pull requests244 - Review code changes245 - Add comments to PRs246247This integration enables Claude to participate as a full team member in the development process, not just as a code generation tool. Claude's GitHub account ([bm-claudeai](https://github.com/bm-claudeai)) is a member of the Basic Machines organization with direct contributor access to the codebase.248249### Collaborative Development Process250251With GitHub integration, the development workflow includes:2522531. **Direct code review** - Claude can analyze PRs and provide detailed feedback2542. **Contribution tracking** - All of Claude's contributions are properly attributed in the Git history2553. **Branch management** - Claude can create feature branches for implementations2564. **Documentation maintenance** - Claude can keep documentation updated as the code evolves257258This level of integration represents a new paradigm in AI-human collaboration, where the AI assistant becomes a full-fledged team member rather than just a tool for generating code snippets.