mem-brain-cli
v1.1.0
Published
The official CLI for MemBrain — persistent memory infrastructure
Readme
mb — MemBrain CLI
The official command line interface for MemBrain — persistent memory infrastructure for AI agents and applications, built by Alphanimble.
mb gives you direct terminal access to your entire memory graph: store memories, run semantic searches, traverse graph edges, inspect neighborhoods, and export your full knowledge graph — all without leaving the terminal.
Table of Contents
- Installation
- Quick Start
- Interactive Mode
- Authentication
- Command Reference
- Global Flags
- Scripting & CI/CD
- Configuration & Personalization
- Error Handling
- Scope System
- Project Structure
- Building from Source
Installation
npm install -g mem-brain-cliNote: You need -g (global). Installing with npm install mem-brain-cli alone only adds a project-local CLI; use npx mb … or ./node_modules/.bin/mb … in that case.
If mb is not found after a global install, your shell’s PATH probably doesn’t include npm’s global binaries. Check the directory and add it to your profile (~/.zshrc, ~/.bashrc, etc.):
npm config get prefix # e.g. ~/.nvm/versions/node/v20.x.x or /usr/local
ls "$(npm config get prefix)/bin/mb" # should exist
echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.zshrc # exampleAlternatively run without a global link: npx mem-brain-cli --version (or npx mb --version).
Requirements: Node.js 18 or later.
Quick Start
# 1. Run quickstart for a guided flow
mb quickstart
# OR launch the interactive REPL
mb
# 2. Authenticate
mb auth login
# 3. Store a memory (shorthand 'a')
mb a "Postgres is the primary database for Fintellytics" --scope domain.backend
# 4. Search your memory graph (shorthand 's')
mb s "what database does Fintellytics use"Interactive Mode
Running mb with no arguments in a TTY terminal launches the Interactive REPL.
mb
# MEMBRAIN ASCII Art...
# Tip: Use 'menu' to see all available commands.
mb› search "database"Special Commands:
?orhelp: Show interactive helpmenuorpalette: Open a visual command selection menuhistory: Show recent command history/query: Shorthand for searching command historyexitorquit: Leave the REPL
History is persistently stored at ~/.membrain/command-history.json.
Authentication
mb uses API key authentication. Keys are resolved in this priority order:
| Priority | Source | How to set |
| -------- | --------------------------------- | ------------------------------- |
| 1 | MB_API_KEY environment variable | export MB_API_KEY=mb_live_xxx |
| 2 | --key <api_key> flag | Per-command override |
| 3 | ~/.membrain/config.json | Set by mb auth login |
The config file is stored at ~/.membrain/config.json with 600 permissions. It is never written to your project directory and should never be committed to version control.
Command Reference
Auth
mb auth login
Authenticate with your MemBrain API key. Validates the key against the live API and stores it locally.
mb auth login
# ? Enter your MemBrain API key: ••••••••••••
# ✓ Authenticated — 42 memories in your storeFlags:
--key <api_key>— Provide the key directly (skips the prompt)
mb auth logout
Remove stored credentials.
mb auth logout
# ✓ Logged out. Config cleared.mb auth status
Show current auth state, masked key, and live store summary.
mb auth status
# API Key: mb_live_...xxx (config)
# User ID: user_abc123
# Total Memories: 42
# Total Links: 134
# Authenticated At: 5/4/2026, 10:00:00 AMadd (alias: mb a)
Store a new memory. The ingest is asynchronous — mb handles the job polling transparently with a spinner and confirms once complete. Provides completion timing on success.
mb a "Postgres is the primary database for Fintellytics"
mb add "User prefers dark mode" --scope type.preference,domain.uimb add "Sprint 3 goals: auth, dashboard, reporting" --category project-notes mb add "Rate limiting is at the API gateway" --scope domain.security
**Flags:**
- `--scope <tokens>` — Comma-separated dot-notation scope tokens (max 50). Repeatable.
- `--category <name>` — Optional category label
**Output:**✓ Memory stored (mem_xyz789)
If ingest times out after 30 seconds, a warning is shown with the `job_id` for manual follow-up.
---
### search (alias: `mb s`)
Natural language semantic search over your memory graph. Suggests corrections for typos and provides execution timing.
```bash
mb s "what database does Fintellytics use"
mb search "user interface preferences" --k 10
mb search "security decisions" --format interpreted
mb search "auth flow" --scope domain.security
mb search "deploy events" --scope domain.deploy --scope type.event
mb search "all security memories" --full-scope --scope domain.security
mb search "vendor risk" --rerank --k 8Flags:
--k <number>— Number of results (default5, max100). For--full-scope, the API returns all scope matches;--kdoes not cap that listing (it is still sent for API compatibility).--format <raw|interpreted|both>— Response format (default:raw)--scope <regex>— Scope filter. Each value is a PostgreSQL~* regex. Repeatable; multiple values are AND-combined.--rerank— After vector search, return onlymemory_noderows:relationship_edgehits are folded onto source and target nodes, deduplicated by id (best score kept),related_memoriesmerged, sorted by score descending, then truncated to--k. Ignored when--full-scopeis set. Works with any--format(interpreted synthesis runs on the post-processed list).--full-scope— Skips vector search. Lists every memory whose scope matches the given--scopepatterns (at least one--scoperequired). Response nodes havesemantic_score1.0and emptyrelated_memories.--rerankis ignored in this mode. The positionalqueryis still required by the API; it is used for--format interpreted/both(LLM summary), not for picking which memories appear.
Direct API shape matches the CLI body: query, k, optional scope, response_format, optional rerank, optional full_scope (snake_case in JSON).
Example JSON (e.g. curl): { "query": "…", "k": 10, "scope": ["domain.security"], "response_format": "raw", "rerank": true } or add "full_scope": true with a non-empty scope.
Output (raw — default):
Found 2 memories:
mem_xyz789 [type.preference, domain.ui]
User prefers dark mode and uses VSCode
↳ links: mem_abc123
mem_abc123 [domain.dev, tool.vscode]
VSCode is the standard editor across the teamOutput (interpreted):
──────────────────────────────────────────────────
Summary:
The user prefers VSCode in dark mode for development work,
consistent with the team's standard editor choice.
Key facts:
• VSCode is the user's preferred editor
• Dark mode is enabled by preference
Relationships:
• The user's preference aligns with the team-wide editor choice
Confidence: high
Supporting memories: mem_xyz789, mem_abc123
──────────────────────────────────────────────────When --format both is passed, the raw block renders first followed by the interpreted block.
get (alias: mb g)
Fetch one or more memories by ID. Automatically uses the batch endpoint when multiple IDs are provided (single round trip).
mb g mem_xyz789
mb get mem_xyz789 mem_abc123 mem_def456update (alias: mb u)
Update the content, scope, or both on an existing memory.
mb u mem_xyz789 --content "User prefers dark mode and uses Neovim now"
mb update mem_xyz789 --scope-replace type.preference,domain.ui,tool.neovimmb update mem_xyz789 --scope-append tool.neovim mb update mem_xyz789 --content "Updated content" --scope-append type.preference
**Flags:**
- `--content <text>` — New content (max 20,000 chars)
- `--scope-append <tokens>` — Append scope tokens to existing scope list. Comma-separated and repeatable.
- `--scope-replace <tokens>` — Replace existing scope list with provided tokens. Comma-separated and repeatable.
At least one of `--content`, `--scope-append`, or `--scope-replace` is required.
---
### delete
Delete a single memory. Asks for confirmation unless `--force` is passed.
```bash
mb delete mem_xyz789
# ? Delete memory mem_xyz789? (y/N)
mb delete mem_xyz789 --forceFlags:
--force— Skip confirmation prompt
count
Get the total memory count, optionally filtered.
mb count
# 42 memories
mb count --scope domain.security
# 7 memories matching scope: domain.security
mb count --category project-notes
# 12 memories matching category: project-notes
mb count --scope domain.security --scope type.event
# 3 memories matching scope: domain.security, type.eventFlags:
--scope <regex>— Repeatable. Each value is a regex; AND semantics across values.--category <name>— Filter by exact category match.
stats
Full stats dashboard for your memory store.
mb statsOutput:
─────────────────────────────────────────────
MemBrain Store Stats
─────────────────────────────────────────────
User ID user_abc123
Total Memories 42
Total Links 134
Avg Links / Memory 3.19
Top Scope type.preference (12)
domain.ui (8)
project.fintellytics (6)
─────────────────────────────────────────────graph
Graph traversal and inspection commands.
mb graph traverse <memory_id>
Walk the graph from a starting memory, following only edges whose descriptions semantically match the query.
mb graph traverse mem_xyz789 --query "authentication flow"
mb graph traverse mem_xyz789 --query "database decisions" --hops 3 --threshold 0.6
mb graph traverse mem_xyz789 --query "security events" --scope domain.securityFlags:
--query <text>— (required) Natural language edge matching query (max 10,000 chars)--hops <n>— Max traversal depth (default2, max5)--threshold <float>— Min edge similarity score0.0–1.0(default0.7)--scope <regex>— Optional scope filter on traversed memories. Repeatable, AND semantics.
Output:
mem_xyz789 Auth uses JWT
└─[authentication flow]─→ mem_001 Refresh tokens rotate on use
└─[token lifecycle]─→ mem_002 Tokens expire after 7 daysmb graph path <from_id> <to_id>
Find the shortest reasoning path between two memories.
mb graph path mem_aaa mem_zzzOutput:
mem_aaa User prefers minimal UI
└──→ mem_bbb Dashboard uses dark theme
└──→ mem_zzz Dark mode is default for all new usersIf no path exists, the API message is surfaced and the command exits non-zero.
mb graph neighborhood <memory_id>
Return all memories within N hops of a given memory.
mb graph neighborhood mem_xyz789
mb graph neighborhood mem_xyz789 --hops 3Flags:
--hops <n>— Hop radius (default2, max5)
mb graph hubs
Return the most connected memories in the graph — the central knowledge anchors.
mb graph hubs
mb graph hubs --limit 5Flags:
--limit <n>— Number of hubs to return (default10, max100)
Output:
1. mem_001 Core architecture decisions (15 connections)
2. mem_002 User preferences (12 connections)
3. mem_003 Authentication system design (9 connections)mb graph unlink <memory_id_1> <memory_id_2>
Remove the edge between two memories. Asks for confirmation unless --force is passed.
mb graph unlink mem_aaa mem_bbb
# ? Unlink mem_aaa ↔ mem_bbb? (y/N)
mb graph unlink mem_aaa mem_bbb --forceFlags:
--force— Skip confirmation prompt
import (alias: mb imp)
Read a local file and bulk-store its contents as individual memories. Supports .md, .txt, and .json. Shows staged progress (1/3, 2/3, 3/3) during execution.
mb imp ./context.md
mb import ./notes.txt --scope project.fintellyticsmb import ./memories.json
**Flags:**
- `--scope <tokens>` — Comma-separated scope tokens applied to every chunk. Repeatable.
- `--category <name>` — Category applied to every chunk.
**File handling:**
| Format | Splitting strategy |
|---|---|
| `.md` | Split by `#` or `##` headings. Falls back to paragraph split if only one section found. |
| `.txt` | Split by double newline (paragraphs). |
| `.json` | Must be a JSON array of strings. Each string becomes one memory. |
**Output:**Found 14 chunks in sprint-notes.md Ingesting... [██████████████░░░░] 14/20 ✓ 14 memories stored from sprint-notes.md
Each chunk goes through the full async ingest flow (POST → poll → confirm). Failed chunks are reported individually without stopping the batch.
---
### export
Export the full memory graph (memories + links) as JSON. Useful for backups, visualization tools (Cytoscape, D3, vis.js), and `jq` pipelines.
---
### quickstart
Launch a 4-step guided onboarding flow to quickly learn how to use MemBrain.
```bash
mb quickstartinteractive (alias: mb i)
Explicitly enter the interactive REPL mode.
mb interactivedashboard
View a local usage telemetry dashboard with visual bar charts (rendered via ervy).
mb dashboard
mb dashboard --days 7
mb dashboard --clearFlags:
--days <n>— Window in days (default30,0= all time)--clear— Delete all local usage telemetry--force— Skip confirmation when clearing
config
Manage local preferences and theme personalization.
mb config show
mb config set theme neonSubcommands:
path— Show config file pathshow— Display current configurationset <key> <value>— Update a preference
history
Manage persistent command history.
mb history list
mb history search "query"
mb history clearSubcommands:
list— Show recent command historysearch <q>— Filter history by queryclear— Wipe history filepath— Show history file path
Every command supports these global flags:
| Flag | Description |
| ----------------- | ---------------------------------------------------- |
| --json | Suppress human-readable formatting. Output raw JSON. |
| --toon | Like --json, but output TOON (Token-Oriented Object Notation): compact, LLM-oriented structured text using @toon-format/toon. Not valid together with --json. |
| --key <api_key> | Override the API key for this command only. |
| --no-banner | Suppress the ASCII art wordmark on startup. |
| --help | Show detailed usage for any command. |
Because every command supports --json, --toon, and MB_API_KEY, mb composes cleanly into shell scripts, agents, and CI pipelines.
# Add a memory silently and capture only the ID
MEM_ID=$(mb add "Secret note" --json | jq -r '.id')
# Token-efficient structured output for LLM/agent pipelines (TOON format)
mb search "architecture" --k 3 --toon
Configuration & Personalization
Preferences are stored at ~/.membrain/config.json. You can manage them via mb config.
- Themes:
classic,neon,minimal,mono. - Default Flags: Set
show_banner,tips_enabled, ormicro_interactions.
Environment Variables:
MB_THEMEMB_SHOW_BANNERMB_TIPSMB_MICRO_INTERACTIONS
Error Handling
mb uses structured error rendering with stable error codes (e.g., MBR101) to help you troubleshoot faster. Errors include:
- Code: Stable reference code
- What: Brief summary of the failure
- Why: The underlying cause
- Next: Actionable step to fix the issue
Detailed context is included by default in human-readable error output.
Scope System
Scope tokens are the primary organizational primitive in MemBrain. They are stored as a dot-separated array on every memory (e.g. type.preference, domain.ui, project.fintellytics) and serve two purposes:
- Filtering — Pass
--scopetosearch,count,graph traverse, andimportto narrow results. Each token is evaluated as a PostgreSQL~* regex. Multiple--scopevalues use AND semantics — every pattern must match at least one scope token on the memory. - Ingest narrowing — Scope tokens on an incoming memory limit which existing memories it can be linked to or merged with during the ingest pipeline.
Syntax:
# Single token
mb search "auth decisions" --scope domain.security
# Multiple tokens (AND semantics — memory must match all)
mb search "deploy events" --scope domain.deploy --scope type.event
# Comma-separated (equivalent to repeating --scope)
mb add "..." --scope type.preference,domain.ui,project.fintellyticsProject Structure
membrain-cli/
├── src/
│ ├── bin/
│ │ └── mb.ts — Entry point & flag resolution
│ ├── commands/
│ │ ├── interactive-cmd.ts — REPL entry
│ │ ├── dashboard.ts — Usage telemetry (ervy)
│ │ ├── quickstart.ts — Onboarding flow
│ │ ├── config-cmd.ts — Preferences management
│ │ ├── history-cmd.ts — command history subcommands
│ │ └── ... — Auth, Add, Search, etc.
│ ├── banner-helpers.ts — ASCII art & context detection
│ ├── interactive.ts — REPL loop implementation
│ ├── history-store.ts — Persistent history management
│ ├── settings.ts — Theme & default flag resolution
│ ├── redact.ts — Secret redaction logic
│ ├── analytics.ts — Local telemetry store
│ ├── output.ts — Structured error & results rendering
│ └── ...Building from Source
git clone https://github.com/alphanimble/membrain-cli
cd membrain-cli
npm install
npm run build # compiles TypeScript to dist/
npm link # registers mb globally from local buildFor development with live reload:
npm run dev -- auth status
npm run dev -- search "your query"Built by Alphanimble — the memory layer for every agent, accessible from every terminal.
