# 🚨 CRITICAL: Memory MCP Server Usage Guide

## ⚡ Tool Execution Order (MUST FOLLOW)

### 1️⃣ ALWAYS START WITH:
```
project_init
```
This MUST be the first tool called when connecting to any project. It:
- Detects if this is a new or existing project
- Initializes 20 memory slots if new
- Returns project status and instructions
- Starts background codebase indexing if needed

### 2️⃣ TOOL DEPENDENCIES:

```mermaid
graph TD
    A[project_init] --> B[memory_save]
    A --> C[memory_search]
    A --> D[memory_list]
    A --> E[project_summary]
    A --> F[codebase_index]
    F --> G[codebase_search]
```

**Tools that REQUIRE project_init first:**
- `memory_save` - Won't work without initialized slots
- `memory_search` - No memories to search
- `memory_list` - Nothing to list
- `project_summary` - No summary available

**Codebase tools:**
- `codebase_index` - Can run after project_init
- `codebase_search` - REQUIRES codebase_index first

## 🔄 Typical Workflows

### New Project (First Time)
1. `project_init` → Initializes 20 slots, starts indexing
2. `memory_save` → Store initial context
3. `codebase_index` → If not auto-started
4. Work on tasks...
5. `memory_save` → After significant changes

### Existing Project (Returning)
1. `project_init` → Loads existing memories
2. `project_summary` → Quick context refresh
3. `memory_search` → Find specific info
4. Work on tasks...
5. `memory_save` → Update memories

### Before Starting Any Task
1. `memory_search` → Check for existing solutions
2. `codebase_search` → Find relevant code
3. Implement...
4. `memory_save` → Store new learnings

## 📊 MongoDB Modes

### MongoDB Community (Local)
- **Text-only search** - No vector embeddings used
- Uses MongoDB text indexes and regex fallback
- Still maintains 20 slots per project
- Perfect for local development

### MongoDB Atlas (Cloud)
- **Vector + Text search** - Full semantic search
- Uses Voyage AI embeddings
- Better similarity matching
- Recommended for production

**Auto-Detection:**
The server automatically detects which MongoDB you're using:
- Atlas URL pattern: `mongodb+srv://` or `.mongodb.net`
- Local pattern: `mongodb://localhost`

## 🎯 Memory Slot Management

### Fixed 20 Slots (5 per type):
- **Context** (slots 1-5): Architecture, tech stack, conventions
- **Task** (slots 1-5): Recent implementations, solutions
- **Pattern** (slots 1-5): Code patterns, APIs, queries  
- **Issue** (slots 1-5): Bugs, fixes, edge cases

### Update Logic:
- **>85% similarity** → Updates existing slot
- **50-85% similarity** → Asks which slot to replace
- **<50% similarity** → Replaces least relevant slot

### Never Creates New Slots!
The system ALWAYS maintains exactly 20 slots. It updates or replaces, never adds.

## 🚀 Best Practices

### DO:
✅ Always run `project_init` first  
✅ Search before implementing (`memory_search`)  
✅ Save after significant work (`memory_save`)  
✅ Use specific memory types (context/task/pattern/issue)  
✅ Include keywords and file paths when saving  

### DON'T:
❌ Skip `project_init` - Nothing will work  
❌ Run `codebase_search` before `codebase_index`  
❌ Worry about creating too many memories (fixed slots)  
❌ Mix project contexts (each project isolated)  

## 🔍 Search Strategies

### MongoDB Community:
```javascript
// Text search first
$text: { $search: "authentication" }

// Falls back to regex if no results
{ title: /auth|login/i, content: /auth|login/i }
```

### MongoDB Atlas:
```javascript
// Vector similarity (70% weight)
cosine_similarity(query_embedding, memory_embedding)

// Plus text matching (30% weight)
title.includes(query) || content.includes(query)
```

## 🆘 Troubleshooting

### "Memory service not initialized"
→ Run `project_init` first!

### "No memories found"
→ Check if project was initialized
→ Try broader search terms
→ Use `memory_list` to see what exists

### "Codebase search returns nothing"
→ Run `codebase_index` first
→ Check if files exist in project
→ Verify file extensions are supported

### "MongoDB connection failed"
→ Check MongoDB is running
→ Verify connection string in .env
→ Check network/firewall for Atlas

## 📝 Memory Content Guidelines

### Good Memory Content:
```
"Authentication implemented using JWT with refresh tokens. 
Access tokens expire in 15min, refresh in 7 days. 
Stored in httpOnly cookies. See auth.service.ts"
```

### Poor Memory Content:
```
"Fixed auth bug"
```

### Include:
- What was implemented/decided
- Why (business/technical reason)
- Where (file references)
- Key patterns or approaches
- Important constraints or gotchas

## 🔐 Project Isolation

Each project gets a unique ID:
```javascript
SHA256(absolute_project_path).substring(0, 16)
```

This ensures:
- Memories NEVER mix between projects
- Each project has its own 20 slots
- No cross-contamination
- Safe for multiple projects

## ⚠️ Critical Notes

1. **First-run detection** is automatic - the system knows if it's new
2. **Background indexing** starts automatically for new projects with code
3. **Relevance decay** happens daily (memories become less relevant over time)
4. **Fallback embedding** works even without Voyage AI API key
5. **Text search** works even in MongoDB Community Edition

## 📊 Monitoring

Watch stderr for:
- `[MongoDB]` - Database operations
- `[Memory]` - Memory operations (Community vs Atlas mode)
- `[Embedding]` - Voyage AI status
- `[Codebase]` - Indexing progress
- `[Init]` - Project initialization
- `[Memory MCP]` - Server status

## 🎯 Quick Reference

```bash
# First connection to any project
1. project_init          # ALWAYS FIRST
2. memory_save           # Store initial context
3. codebase_index        # Enable code search

# Starting work session
1. project_init          # ALWAYS FIRST
2. project_summary       # Get overview
3. memory_search "auth"  # Find specific info

# After completing task
1. memory_save           # Update memories
   type: "task"
   content: "Implemented OAuth2..."
```

Remember: **project_init** is ALWAYS the first tool to run!