847850277/shrimp-memory
About
Own Your Memory. Local-first Rust MCP temporal memory server that distills AI coding sessions into versioned, traceable knowledge trees (SQLite / MySQL).
AI & Machine LearningMeasured star growth
- in 24h
- Collecting history
- in 7 days
- Collecting history
- in 15 days
- Collecting history
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README_EN.md
Original🦐 Shrimp Memory
Own Your Memory. Distill Your Daily Work into a Compounding Engineering Asset.
No manual note-taking required — every coding session silently compounds into a versioned, traceable knowledge tree that belongs 100% to you.
简体中文 | English
Why Shrimp Memory · Architecture · Quick Start · Web Console · MCP & Hooks · LLM Backends
💡 Why Shrimp Memory?
Most AI pair-programming sessions are ephemeral: thousands of turns of architectural trade-offs, debugging breakthroughs, and hard-won lessons vanish the moment you close the window. Switch models or start a fresh thread, and you are explaining your codebase from scratch again.
Shrimp Memory is a local-first, self-hosted temporal engineering memory server written in Rust:
- Turn daily coding into compounding assets: Stop hooks silently capture your Codex / Antigravity sessions, and background workers distill them into structured Topics → Knowledge Series (
v1 → v2 → v3) → Source Evidence without interrupting your flow. - Models are rented compute; your memory tree is the asset you keep: Every transcript, structured tag, and versioned memory lives 100% in your own single-file SQLite or self-hosted MySQL. Whether you use Codex today, Claude or Gemini tomorrow, or a local model next month, pointing any MCP client at
/mcpimmediately inherits your engineering history. - No silent overwrites — preserve time, parallels, and conflicts: Engineering decisions evolve and often differ across environments. Shrimp Memory models
initial/version_update/parallel/conflictrelations alongside verification levels, and ships a built-in single-binary Web Console so agents read/write via MCP while humans inspect and curate the tree.
🌳 Architecture: Evolution Trees, Not Flat Notes
flowchart LR
A["AI Agent<br/>(Codex / Antigravity / Any MCP Client)"] -- "Silent Stop Hook Capture<br/>POST /mcp" --> B["prompt_runs<br/>Raw Turns · Tool Traces · Duration"]
B -- "Async Digest & Tagging<br/>(Shared Rate Limit + Backfill Jobs)" --> C["prompt_run_tags<br/>Intent · Area · Stage · Decision State"]
C -- "Sliding-Window Extraction<br/>(Version Guard + Zero-Waste Dedup)" --> D["Topic<br/>↓<br/>Knowledge Series (v1 → v2 → v3 / parallel / conflict)<br/>↓<br/>Source Runs (Many-to-Many Evidence)"]
D -- "Cross-Project Hybrid Recall<br/>(SQL History + BM25 + Version/Trust Boost)" --> A
D <-- "Browse · Curate · Merge Topics<br/>Web Console (/ & /ui)" --> E["Developer<br/>Human-in-the-Loop"]
| Layer | What It Stores | Problem It Solves |
|---|---|---|
| Topic | Normalized module, subsystem, or long-running theme (topic_key) per project |
Keeps knowledge organized; supports merging & archiving with audit reasons |
| Knowledge Series | Versioned conclusions (v1 → v2 → v3), parallel facts, and explicit conflict records |
Gives you the latest conclusion immediately while preserving why it changed |
| Source Runs | Original prompts, responses, one-line summaries, outcomes, and tags (many-to-many) | Lets you drill from any abstract memory straight back to the raw engineering turn |
Recall Ranking: Candidate memories combine recent context with parameterized SQL full-history keyword hits, then rank via BM25, tag overlap, and lightweight semantic similarity. Matched series prioritize the latest active version, weighted by verification tier (
verified_production > verified_local > deployed_unverified > implemented_local > planned / unknown).
🖥️ Visual Evolution Tree Console
The single Rust binary embeds the full Web Evolution Tree Console (/ or /ui) with zero frontend build step: browse topics and version chains by project, inspect the exact source runs behind every version, mark memories Verified in Production / Deprecated, edit metadata, or merge duplicate topics.

| JSON Endpoint | Purpose |
|---|---|
GET /api/v1/projects |
Active topics, active memories, total runs, and pending extraction counts per project |
GET /api/v1/projects/{project}/tree?include_inactive=true&q=... |
Full project evolution tree; preserves entire version chains on search matches |
GET /api/v1/runs/{run_id} |
Full request, response, summary, and structured tags for one source run |
POST /api/v1/memories/{memory_id}/curate |
Curate status, verification level, environment, remark, or target topic |
POST /api/v1/topics/merge |
Merge multiple topics and all linked memories inside a project, archiving sources |
- Write Protection: Set
ADMIN_TOKENto requireAuthorization: Bearer <token>orX-Admin-Tokenon JSON write endpoints and the two MCP governance tools (stored in browsersessionStoragewhen entered in the console header). - Public Reverse Proxy Security:
ADMIN_TOKENguards write endpoints only. If exposing/uiand/api/v1/over the internet, protect read routes with reverse-proxy authentication (e.g. Nginx Basic Auth) or access them through anssh -N -Ltunnel.
⚡ Quick Start
One binary supports both zero-dependency local SQLite and multi-device MySQL 8.4 with identical MCP, background extraction, and Web Console behavior.
Option 1: Zero-Dependency Local Mode (SQLite, 30 Seconds)
SQLite is statically bundled via rusqlite (bundled) — no Docker, MySQL, or external SQLite runtime required (building from source requires a Rust toolchain and C compiler):
cp .env.example .env
# Edit .env and set OPENAI_API_KEY and OPENAI_MODEL (leave OPENAI_API_KEY empty for local Ollama/vLLM)
cargo run -p shrimp-memory-rs
- Evolution Tree Console:
http://127.0.0.1:7879/ - MCP Endpoint:
http://127.0.0.1:7879/mcp - Database file defaults to
~/.shrimp-memory/memory.db(WAL mode, auto-created on first boot; customize viaSQLITE_PATH/SQLITE_URL, or use:memory:for ephemeral runs). - Backward-Compatible Auto-Detection: When
STORAGE_BACKENDis unset, an existingMYSQL_URLselects MySQL,POSTGRES_URLselects PostgreSQL (driver reserved), and leaving both unset selects local SQLite.
Option 2: Docker Compose + MySQL 8.4 (Multi-Device Sync)
Share one evolving memory tree across multiple machines using the root compose.yaml (requires Docker Compose v2.23.1+):
cp .env.example .env
# Edit .env with your LLM settings (optionally set QUICKSTART_MYSQL_PASSWORD before first start)
docker compose up -d
- Binds to
127.0.0.1:7879by default; MySQL is reachable only inside the Compose network. - Share securely from multiple dev machines over SSH port forwarding:
Then point each machine's MCP client tossh -N -L 7879:127.0.0.1:7879 user@cloud-hosthttp://127.0.0.1:7879/mcp.
Option 3: External MySQL (Standalone Docker Deployment)
For an existing MySQL 8.x instance, deploy from deploy/server/:
cd deploy/server
cp server.env.example server.env
# Edit server.env with MYSQL_URL, ADMIN_TOKEN, and LLM settings
sh start.sh
- On an empty database, the server auto-creates all 8 tables in
utf8mb4_unicode_ci(no physical foreign keys — links are application-managed with lookup and unique indexes). To initialize database and tables manually, run docs/schema.mysql.sql:mysql --default-character-set=utf8mb4 -u your_mysql_user -p < docs/schema.mysql.sql - Binds
127.0.0.1:7879by default; setSERVER_BIND_HOST=0.0.0.0inserver.envif external binding is required.
🤖 LLM Backend Configuration
Digest generation, tagging, and memory extraction share one LLM backend and process-wide rate limiter (defaults: LLM_MAX_RPM=20, LLM_MAX_CONCURRENCY=1, automatic global cooldown on HTTP 429 with persistent job retry).
Default: OpenAI-Compatible Chat Completions (Recommended)
Works with any OpenAI-compatible provider or local inference engine:
PROMPT_RUN_DIGEST_BACKEND=openai
OPENAI_BASE_URL=https://api.deepseek.com/chat/completions
OPENAI_MODEL=deepseek-flash
OPENAI_API_KEY=YOUR_API_KEY
| Provider / Runtime | OPENAI_BASE_URL |
Example OPENAI_MODEL |
Docs |
|---|---|---|---|
| DeepSeek | https://api.deepseek.com/chat/completions |
deepseek-flash |
DeepSeek Docs |
| OpenAI | https://api.openai.com/v1 (default) |
gpt-4o-mini |
OpenAI Docs |
| OpenRouter | https://openrouter.ai/api/v1 |
openai/gpt-4o-mini |
OpenRouter Docs |
| SiliconFlow | https://api.siliconflow.cn/v1 |
Platform chat model ID | SiliconFlow Docs |
| Local Ollama | http://127.0.0.1:11434/v1 |
llama3.2 (installed model) |
OPENAI_API_KEY= can be empty; use host.docker.internal from Docker |
| Local vLLM | http://127.0.0.1:8000/v1 |
Served vLLM model name | OPENAI_API_KEY= can be empty |
Optional settings:
OPENAI_MAX_TOKENS=8192,OPENAI_TEMPERATURE=0.1,OPENAI_TIMEOUT_SECONDS=120(all acceptOPENAI_LLM_*aliases). SetPROMPT_RUN_DIGEST_BACKEND=disabledto record raw runs without LLM extraction.
Expand: Vertex AI (DeepSeek MaaS / Gemini) & AI Ping Configuration
Vertex AI (Google Cloud Service-Account API Key)
Authenticates via x-goog-api-key — no gcloud CLI or mounted ADC file needed. Enable aiplatform.googleapis.com, grant roles/aiplatform.user to the service account, and create an authorization key restricted to aiplatform.googleapis.com:
PROMPT_RUN_DIGEST_BACKEND=vertex
VERTEX_API_KEY=YOUR_VERTEX_API_KEY
VERTEX_PROJECT_ID=YOUR_GCP_PROJECT_ID
VERTEX_LOCATION=global
VERTEX_LLM_MODEL=deepseek-ai/deepseek-v4.1-flash-maas
VERTEX_LLM_MAX_TOKENS=8192
VERTEX_LLM_TEMPERATURE=0.1
VERTEX_LLM_TIMEOUT_SECONDS=120
- For DeepSeek V4.1 Flash use
deepseek-ai/deepseek-v4.1-flash-maaswithVERTEX_LOCATION=global; for Gemini usegemini-…orgoogle/gemini-….
AI Ping
PROMPT_RUN_DIGEST_BACKEND=aiping
AIPING_API_KEY=YOUR_AIPING_API_KEY
AIPING_LLM_BASE_URL=https://aiping.cn/api
AIPING_LLM_MODEL=DeepSeek-V4-Flash
AIPING_LLM_MAX_TOKENS=8192
AIPING_LLM_TEMPERATURE=0.1
AIPING_LLM_TIMEOUT_SECONDS=360
🔌 MCP Protocol & Capture Hooks
1. Remote MCP Tool Surface (POST /mcp)
Implements Streamable HTTP MCP (initialize / ping / resources/list / resources/read for memory://protocol / tools/list / tools/call) and delivers the full MEMORY_PROTOCOL.md in initialize.instructions.
| Tool | Description |
|---|---|
memory_record_prompt_run |
Persist a real engineering turn synchronously; async worker fills summary & tags |
memory_get_current_project_context |
Aggregate active memories, recent runs, and top tags for a project |
memory_find_similar_work |
Search memories & historical runs by query; omit project for cross-project full-history recall |
memory_get_topic_knowledge |
Browse topics & version chains, or drill down by topic_id / knowledge_series_id / topic_key (project optional) |
memory_summarize_project_activity |
Compress recent project activity by theme clusters and run types |
memory_get_ingest_health |
Audit capture quality, summary/tag coverage, and memory linkage rates |
memory_list_project_prompt_runs / memory_get_prompt_run_detail |
Paginate and inspect raw runs with millisecond-precision durations |
memory_tag_prompt_run / memory_list_prompt_run_tags |
Manually curate, override, or query structured tags |
memory_curate_prompt_memory / memory_merge_topics |
Curate memory lifecycle or merge topics (guarded by ADMIN_TOKEN) |
2. Build & Install the Capture CLI (shrimp-memory-bin)
cargo build --release -p shrimp-memory-bin
install -m 755 target/release/shrimp-memory-bin ~/.cargo/bin/shrimp-memory-bin
Both Stop hooks safely default to local
http://127.0.0.1:7879/mcp. For a remote server, explicitly setSHRIMP_MEMORY_MCP_URL=https://your-shrimp-memory.example.com/mcp.
3. Connect Antigravity / Codex
Antigravity MCP (~/.gemini/config/mcp_config.json, or run agy mcp add shrimpMemory "http://127.0.0.1:7879/mcp?inline_structured=1"):
{
"mcpServers": {
"shrimpMemory": {
"url": "http://127.0.0.1:7879/mcp?inline_structured=1"
}
}
}
Antigravity Stop Hook (~/.gemini/config/hooks.json):
{
"shrimp-memory-recorder": {
"Stop": [
{
"type": "command",
"command": "~/.cargo/bin/shrimp-memory-bin antigravity-stop-hook",
"timeout": 45
}
]
}
}
Codex: configure [mcp_servers.shrimpMemory] in ~/.codex/config.toml pointing to http://127.0.0.1:7879/mcp, and invoke ~/.cargo/bin/shrimp-memory-bin stop-record-prompt-run-hook from your Stop hook.
Expand: Hook Capture Details, Duration Precision & Background Workers
- Codex Stop Hook: Matches transcripts by
turn_idand skips internal non-interactive triggers without a transcript; logs to~/.codex/log/stop_record_prompt_run.log. - Antigravity Stop Hook: Parses camelCase Stop payloads, prefers sibling
transcript_full.jsonlfor full tool traces, skips mid-turnfullyIdle=falsepauses, skips internal subagents withparentConversationIdby default (SHRIMP_MEMORY_RECORD_SUBAGENTS=trueto opt in), and retries up to 4 times with backoff; logs to~/.gemini/antigravity/log/stop_record_prompt_run.log. - Millisecond Duration Precision:
prompt_runs.duration_secondsusesDECIMAL(12,3)(BigDecimalend-to-end in Rust, never throughf64). - 8 MiB Payload Limit: MCP JSON requests allow up to 8 MiB to preserve full tool calls and responses (
413 Payload Too Largeabove limit). - Prompt Customization: Edit prompts/prompt_run_digest.md, prompts/prompt_memory_extract.md, and prompts/prompt_memory_dedup.md without recompiling Rust.
- Background Workers:
PROMPT_RUN_DIGEST_JOB_*: Backfills missing summaries/tags with lease recovery and bounded retries.PROMPT_MEMORY_EXTRACT_JOB_*: Rotates across eligible projects (default ≥ 3 unextracted tagged runs) every 10 minutes; setPROMPT_MEMORY_EXTRACT_JOB_FULL_SWEEP=trueto drain historical backlogs continuously with zero idle LLM calls once caught up.PROMPT_RUN_LOG_MODE:compact(default production logging) orfull(temporary payload debugging).
📁 Repository Layout
shrimp-memory/
├── server/ # Rust server (Salvo HTTP + MCP + Web Console + SQLite/MySQL storage & workers)
├── bin/ # Capture hook CLI (Codex / Antigravity Stop Hooks)
├── prompts/ # MCP memory protocol and digest / extraction / dedup prompts
├── docs/
│ ├── schema.mysql.sql # Unified MySQL 8.x database & 8-table initialization DDL
│ └── assets/ # Documentation preview images
├── deploy/server/ # Standalone external-MySQL Docker deployment & Dockerfile
├── compose.yaml # Root quickstart Docker Compose (MySQL 8.4 + Server)
└── LICENSE # MIT License
📄 License
Licensed under the MIT License.
Explore related projects
Loading…