# Mem0 Server Mcp

> 🧠 Production-ready MCP server providing intelligent memory for Claude Code with async architecture, Neo4j knowledge graphs, smart chunking & enterprise security. One-command Docker deployment.

- **Type:** MCP server
- **Install:** `agentstack add mcp-subhashdasyam-mem0-server-mcp`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [subhashdasyam](https://agentstack.voostack.com/s/subhashdasyam)
- **Installs:** 0
- **Category:** [Databases](https://agentstack.voostack.com/c/databases)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [subhashdasyam](https://github.com/subhashdasyam)
- **Source:** https://github.com/subhashdasyam/mem0-server-mcp

## Install

```sh
agentstack add mcp-subhashdasyam-mem0-server-mcp
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# 🧠 Mem0 MCP Server - Self-Hosted Memory for AI

A production-ready, self-hosted Model Context Protocol (MCP) server that provides persistent, intelligent memory for Claude Code and other AI assistants. Features async/await architecture, knowledge graph intelligence, smart text chunking, and enterprise-grade security. Built with Docker Compose for one-command deployment.

[](https://opensource.org/licenses/MIT)
[](https://docs.docker.com/compose/)
[](https://www.python.org/downloads/)

## ✨ Features

### Core Features
- 🚀 **One-Command Deployment** - Start the entire stack with a single script
- 🔒 **100% Self-Hosted** - No external API dependencies (when using Ollama)
- 🔐 **Token-Based Authentication** - Secure multi-user access with PostgreSQL-backed token management
- 🌐 **Multi-LLM Support** - Works with Ollama, OpenAI, or Anthropic
- 🎯 **Project Isolation** - Automatic memory isolation per project directory
- 📊 **Semantic Search** - Vector-based search with pgvector
- ⚡ **13 MCP Tools** - Complete memory management + intelligence analysis
- 🔌 **Dual Transport Support** - Modern HTTP Stream (recommended) + legacy SSE transport
- 🐳 **Docker Compose** - Easy orchestration of all services
- 🧪 **Comprehensive Tests** - Automated test suite included
- 📝 **Audit Logging** - Track all authentication attempts and token usage

### 🧠 Memory Intelligence System
- 🔗 **Knowledge Graphs** - Link memories with typed relationships (RELATES_TO, DEPENDS_ON, SUPERSEDES, etc.)
- 🕒 **Temporal Tracking** - Track how knowledge evolves over time
- 🏗️ **Architecture Mapping** - Map system components and dependencies
- 📊 **Impact Analysis** - Understand cascading effects of changes
- 📝 **Decision Tracking** - Record technical decisions with pros/cons/alternatives
- 🎯 **Topic Clustering** - Automatically detect knowledge groups
- ⭐ **Quality Scoring** - Trust scores based on validations and citations
- 🚀 **Intelligence Analysis** - Comprehensive health reports with actionable recommendations

### 📦 Smart Text Chunking System
- ✂️ **Semantic Chunking** - Automatically splits large text at paragraph/sentence boundaries
- 🔄 **Context Preservation** - 150-character overlap between chunks maintains context continuity
- ⚡ **Performance Optimization** - Prevents timeouts on large text inputs with 8B+ embedding models
- 🏷️ **Chunk Metadata** - Full tracking with chunk index, total chunks, size, and overlap indicators
- 🔗 **Session Continuity** - All chunks share the same `run_id` for related memory grouping
- 🎯 **Transparent Operation** - Small texts (1000 characters):** Automatically chunked at semantic boundaries with context preservation

**Chunking Strategy:**

1. **Paragraph-based splitting:** Text is first split at paragraph boundaries (double newlines)
2. **Sentence-based fallback:** If paragraphs exceed 1000 characters, they're split at sentence boundaries
3. **Context preservation:** 150-character overlap between chunks maintains semantic continuity
4. **Session tracking:** All chunks from the same text share a single `run_id` for relationship tracking

**Chunk Metadata:**

Each chunk includes comprehensive metadata for traceability:

```json
{
  "chunk_index": 0,           // Position in sequence (0-indexed)
  "total_chunks": 5,          // Total number of chunks in this text
  "chunk_size": 982,          // Number of characters in this chunk
  "has_overlap": true         // Whether this chunk includes overlap from previous chunk
}
```

**Configuration:**

Chunking parameters are configurable via `.env` file:

```bash
# Smart Text Chunking Configuration
CHUNK_MAX_SIZE=1000         # Maximum characters per chunk
CHUNK_OVERLAP_SIZE=150      # Overlap between chunks for context continuity
```

To adjust chunking behavior:
1. Edit `.env` file with your preferred values
2. Restart MCP server: `docker compose restart mcp`

**Benefits:**

- ✅ **Prevents timeouts** - No more 30-second timeout errors with large code snippets or documentation
- ✅ **Maintains context** - 150-character overlap ensures semantic relationships aren't lost at boundaries
- ✅ **Transparent operation** - Users don't need to manually split text; it happens automatically
- ✅ **Performance optimized** - Small texts bypass chunking entirely for zero overhead
- ✅ **Full traceability** - Metadata allows reconstruction and tracking of chunked memories
- ✅ **Extended timeout** - MCP client timeout increased from 30s to 180s for large text processing

**Implementation Details:**

- **Location:** `mcp-server/text_chunker.py` (chunking algorithm)
- **Integration:** `mcp-server/main.py` in `add_coding_preference()` function
- **Transport:** All chunks sent sequentially via HTTP to Mem0 REST API
- **Storage:** Each chunk stored as separate memory with linking metadata

**Example:**

```python
# User stores large code file (5000 characters)
# System automatically:
# 1. Detects text > 1000 chars
# 2. Splits into 5 semantic chunks at paragraph boundaries
# 3. Adds 150-char overlap between chunks
# 4. Sends chunks sequentially with metadata
# 5. All chunks share same run_id for session tracking
# 6. Returns success message indicating chunking occurred
```

## 📊 Endpoints

### Mem0 REST API (Port 8000)

#### Core Endpoints (13)

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/health` | GET | Health check |
| `/docs` | GET | OpenAPI documentation |
| `/memories` | POST | Create memory |
| `/memories` | GET | Get all memories |
| `/memories/{id}` | GET | Get specific memory |
| `/memories/{id}` | PUT | Update memory |
| `/memories/{id}` | DELETE | Delete memory |
| `/memories/{id}/history` | GET | Get history |
| `/search` | POST | Semantic search |
| `/reset` | POST | Reset all memories |
| `/configure` | POST | Configure Mem0 |

#### Memory Intelligence Endpoints (15)

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/graph/link` | POST | Link memories with relationships |
| `/graph/related/{id}` | GET | Get related memories (graph traversal) |
| `/graph/path` | GET | Find path between memories |
| `/graph/evolution/{topic}` | GET | Track knowledge evolution |
| `/graph/superseded` | GET | Find obsolete memories |
| `/graph/thread/{id}` | GET | Get conversation thread |
| `/graph/component` | POST | Create component node |
| `/graph/component/dependency` | POST | Link component dependencies |
| `/graph/component/link-memory` | POST | Link memory to component |
| `/graph/impact/{name}` | GET | Analyze component impact |
| `/graph/decision` | POST | Create decision with pros/cons |
| `/graph/decision/{id}` | GET | Get decision rationale |
| `/graph/communities` | GET | Detect memory communities |
| `/graph/trust-score/{id}` | GET | Calculate trust score |
| `/graph/intelligence` | GET | 🚀 **Comprehensive intelligence analysis** |

### MCP Server (Port 8080)

| Endpoint | Description |
|----------|-------------|
| `/mcp` | HTTP Stream endpoint (recommended) |
| `/sse` | SSE endpoint (legacy) |
| `/` | Health check |

### Neo4j Browser (Port 7474)

Access the Neo4j browser at `http://localhost:7474`
- Username: `neo4j`
- Password: `mem0graph`

## 🧪 Testing

```bash
# Run all tests
./scripts/test.sh

# Individual test suites
./tests/test_api.sh                         # REST API tests
./tests/test_mcp.sh                         # MCP server tests
./tests/test_integration.sh                 # Full integration test
./tests/test_memory_intelligence_fixed.sh   # Memory Intelligence integration test
./tests/test_mcp_intelligence.sh            # MCP Intelligence verification
./tests/test_auth.sh                        # Authentication tests
./tests/test_ownership_simple.sh            # Memory ownership tests
```

## 📚 Documentation

Detailed documentation is available in the `docs/` directory:

- **[QUICKSTART.md](docs/QUICKSTART.md)** - Quick start guide with authentication setup
- **[AUTHENTICATION.md](docs/AUTHENTICATION.md)** - Complete authentication guide
- **[SECURITY.md](docs/SECURITY.md)** - Security features and best practices
- **[ARCHITECTURE.md](docs/ARCHITECTURE.md)** - System design and components
- **[API.md](docs/API.md)** - Complete API reference
- **[MCP_TOOLS.md](docs/MCP_TOOLS.md)** - MCP tools usage guide
- **[CONFIGURATION.md](docs/CONFIGURATION.md)** - All configuration options
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - Common issues and solutions
- **[PERFORMANCE.md](docs/PERFORMANCE.md)** - Performance optimization

## 🔒 Security

The Mem0 MCP Server implements enterprise-grade security:

### Memory Ownership & Isolation

**All memory operations validate ownership:**
- ✅ Users can only access their own memories
- ✅ Read, update, delete, and history operations are protected
- ✅ Automatic validation at both REST API and MCP tool levels

```bash
# User A cannot access User B's memory
curl "http://localhost:8000/memories/{memory_id}?user_id=user_b"
# Returns: 403 Forbidden - "Access denied"
```

### Production Security Checklist

1. **Change default passwords** in `.env`:
   ```bash
   POSTGRES_PASSWORD=
   NEO4J_PASSWORD=
   ```

2. **Rotate authentication tokens** regularly:
   ```bash
   python3 scripts/mcp-token.py create --user-id user@company.com
   ```

3. **Restrict network access** - Don't expose ports publicly

4. **Use HTTPS** - Add TLS termination via reverse proxy (nginx, Traefik)

5. **Monitor audit logs**:
   ```bash
   python3 scripts/mcp-token.py audit --days 7
   ```

6. **Test security**:
   ```bash
   ./tests/test_ownership_simple.sh
   ./tests/test_auth.sh
   ```

For complete security documentation, see [SECURITY.md](docs/SECURITY.md).

## 🐛 Troubleshooting

### Authentication Issues

**"Missing authentication headers"**
- Ensure `MEM0_TOKEN` and `MEM0_USER_ID` are exported in your shell
- Verify Claude Code config has headers section
- Restart your shell and Claude Code

**"Invalid authentication token"**
- Check token exists: `python3 scripts/mcp-token.py list`
- Verify token is not expired or disabled
- Ensure you're using the correct token value

**"User ID mismatch"**
- Token belongs to different user
- Check which user owns the token: `python3 scripts/mcp-token.py list`
- Create a new token for your user ID

**"Token has been disabled"**
- Token was revoked
- Re-enable: `python3 scripts/mcp-token.py enable `
- Or create a new token

**Server doesn't show in `claude mcp list`**
- Check the URL has a trailing slash: `http://localhost:8080/mcp/` (not `/mcp`)
- Verify environment variables are set: `echo $MEM0_TOKEN $MEM0_USER_ID`
- Remove and re-add: `claude mcp remove mem0` then add again
- Check server is running: `docker compose ps` and `curl http://localhost:8080/`

### Services won't start

```bash
# Check logs
./scripts/logs.sh

# Check health
./scripts/health.sh

# Ensure ports are free
lsof -i :8000  # Mem0 API
lsof -i :8080  # MCP Server
lsof -i :5432  # PostgreSQL
lsof -i :7474  # Neo4j
```

### Slow performance

1. **Use smaller embedding model:**
   ```bash
   OLLAMA_EMBEDDING_MODEL=nomic-embed-text
   OLLAMA_EMBEDDING_DIMS=768
   ```

2. **Switch to OpenAI:**
   ```bash
   LLM_PROVIDER=openai
   OPENAI_API_KEY=sk-...
   ```

3. **Pre-warm Ollama models** - Keep them loaded in memory

### Memory not storing

1. **Check Ollama connectivity:**
   ```bash
   curl http://192.168.1.2:11434/api/tags
   ```

2. **Verify models are available:**
   ```bash
   ollama list
   ```

3. **Check mem0 logs:**
   ```bash
   ./scripts/logs.sh mem0
   ```

See [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) for more help.

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- [Mem0](https://mem0.ai) - Memory layer for AI applications
- [Model Context Protocol](https://modelcontextprotocol.io) - MCP specification
- [FastMCP](https://github.com/jlowin/fastmcp) - FastMCP framework
- [pgvector](https://github.com/pgvector/pgvector) - Vector similarity search for Postgres
- [Neo4j](https://neo4j.com) - Graph database

## 📞 Support

- **Documentation:** See the `docs/` directory
- **Issues:** Open an issue on GitHub
- **Questions:** Check [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)

---

**Made with ❤️ for the AI community**

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [subhashdasyam](https://github.com/subhashdasyam)
- **Source:** [subhashdasyam/mem0-server-mcp](https://github.com/subhashdasyam/mem0-server-mcp)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-subhashdasyam-mem0-server-mcp
- Seller: https://agentstack.voostack.com/s/subhashdasyam
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
