# 🧠 Memory Forge - Universal AI Context & Memory System

[![smithery badge](https://smithery.ai/badge/@cpretzinger/ai-assistant-simple)](https://smithery.ai/server/@cpretzinger/ai-assistant-simple)
[![MIT License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

> A production-ready MCP (Model Context Protocol) server for persistent AI memory across Claude, ChatGPT, and any LLM.

## 🎯 What is Memory Forge?

Memory Forge is a complete infrastructure solution that gives AI assistants persistent memory and context awareness. It includes:

- **MCP Server**: TypeScript-based context server following the Model Context Protocol
- **Multi-Storage**: PostgreSQL for persistence + Redis for speed + Qdrant for vector search
- **Auto-Save**: Automatic conversation backup every 30 seconds
- **Multi-User**: Support for unlimited users with isolated contexts
- **Deploy Anywhere**: Local Docker, Railway, Vercel, or Smithery

## 🚀 Quick Start (Under 5 Minutes!)

### Option 1: One-Command Setup (Recommended)
```bash
curl -sSL https://raw.githubusercontent.com/cpretzinger/memory-forge/main/scripts/setup.sh | bash
```

### Option 2: Manual Setup
```bash
git clone https://github.com/cpretzinger/memory-forge.git
cd memory-forge
npm install
npm run setup
```

## 📦 What's Included

```
memory-forge/
├── src/                    # TypeScript source code
│   ├── server.ts          # Main MCP server
│   ├── handlers/          # Request handlers
│   ├── storage/           # Storage adapters
│   └── types/             # TypeScript definitions
├── docs/                   # Documentation
│   ├── SERVICES.md        # Service architecture
│   ├── DOCKER.md          # Docker setup guide
│   ├── RAILWAY.md         # Railway deployment
│   └── SMITHERY.md        # Smithery deployment
├── scripts/               # Setup & deployment scripts
│   ├── setup.sh          # Universal setup script
│   ├── deploy.ts         # Deployment helper
│   └── test.ts           # System test script
├── config/               # Configuration files
│   ├── docker-compose.yml
│   ├── railway.toml
│   └── smithery.yml
└── examples/             # Example implementations
    ├── .env.example      # Environment template
    └── claude-config.json

```

## 🛠️ Installation

### Prerequisites
- Node.js 20+ 
- Docker (for local deployment)
- 2GB RAM minimum
- 10GB disk space

### Step-by-Step Setup

1. **Clone and Install**
```bash
git clone https://github.com/cpretzinger/memory-forge.git
cd memory-forge
npm install
```

2. **Configure Environment**
```bash
cp examples/.env.example .env
# Edit .env with your settings (see Configuration section)
```

3. **Run Setup Script**
```bash
npm run setup
# This will:
# - Check prerequisites
# - Generate secure passwords
# - Set up databases
# - Configure services
# - Start everything
```

4. **Test Installation**
```bash
npm test
# Should show all services as ✅ Running
```

## ⚙️ Configuration

### Environment Variables

Create a `.env` file from the example:

```env
# Project Configuration
PROJECT_NAME=my-ai-assistant
NODE_ENV=production

# Database Credentials (generated by setup script)
POSTGRES_PASSWORD=<auto-generated>
REDIS_PASSWORD=<auto-generated>
QDRANT_API_KEY=<auto-generated>

# MCP Configuration
MCP_AUTH_TOKEN=<auto-generated>
MCP_PORT=3005

# API Keys (optional - add your own)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...

# Service URLs (for production)
DATABASE_URL=postgresql://user:pass@host:5432/dbname
REDIS_URL=redis://:password@host:6379
QDRANT_URL=http://host:6333
```

### Claude Code Configuration

Add to your Claude desktop config (`~/.config/claude/claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "memory-forge": {
      "command": "node",
      "args": ["/path/to/memory-forge/dist/bridge.js"],
      "env": {
        "MCP_SERVER_URL": "http://localhost:3005/mcp",
        "MCP_AUTH_TOKEN": "your-token-here",
        "AUTO_SAVE": "true"
      }
    }
  }
}
```

## 🚢 Deployment Options

### Local Docker (Development)
```bash
npm run docker:up
# Access at http://localhost:3005
```

### Railway (Production)
```bash
npm run deploy:railway
# Follow prompts to configure
```

### Smithery (Managed MCP)
```bash
npm run deploy:smithery
# Or use Smithery CLI:
smithery publish cpretzinger/memory-forge
```

### Vercel (Serverless)
```bash
npm run deploy:vercel
# Configure environment variables in Vercel dashboard
```

## 🔌 Using with Smithery

### Installing from Smithery Registry

1. **Find the server**:
```bash
smithery search memory-forge
```

2. **Install directly into Claude**:
```bash
smithery install cpretzinger/memory-forge
```

3. **Or add to your config manually**:
```json
{
  "mcpServers": {
    "memory-forge": {
      "command": "npx",
      "args": ["-y", "@smithery/memory-forge"],
      "env": {
        "API_KEY": "your-api-key"
      }
    }
  }
}
```

### Publishing Your Own Fork

1. **Create Smithery account**:
```bash
smithery auth
```

2. **Configure smithery.yml**:
```yaml
name: memory-forge
version: 1.0.0
description: Universal AI memory system
author: yourname
runtime: typescript
```

3. **Publish**:
```bash
smithery publish
```

## 📊 Architecture

### Services Overview

| Service | Purpose | Port | Technology |
|---------|---------|------|------------|
| MCP Server | Context API | 3005 | TypeScript/Express |
| PostgreSQL | Persistent storage | 5432 | PostgreSQL 16 |
| Redis | Cache & sessions | 6379 | Redis 7 |
| Qdrant | Vector search | 6333 | Qdrant |
| n8n | Automation | 5678 | n8n (optional) |

### Data Flow

```mermaid
graph LR
    A[Claude/LLM] -->|MCP Protocol| B[MCP Server]
    B --> C[Redis Cache]
    B --> D[PostgreSQL]
    B --> E[Qdrant Vectors]
    C -->|Fast Read| B
    D -->|Persistent| B
    E -->|Semantic Search| B
```

## 🔧 API Reference

### Available Tools

#### `store_context`
Store conversation context with auto-save
```typescript
{
  sessionId?: string,  // Optional, auto-generated if not provided
  userId?: string,     // Optional user identifier
  context: object,     // Required context data
  metadata?: object    // Optional metadata
}
```

#### `retrieve_context`
Retrieve conversation context
```typescript
{
  sessionId?: string,  // Optional, gets latest if not provided
  userId?: string      // Optional user filter
}
```

#### `search_context`
Search through all contexts
```typescript
{
  query: string,       // Required search query
  limit?: number,      // Optional result limit (default: 10)
  semantic?: boolean   // Use vector search (default: false)
}
```

#### `list_sessions`
List all available sessions
```typescript
{
  userId?: string,     // Optional user filter
  limit?: number       // Optional limit (default: 10)
}
```

## 🧪 Testing

### Run All Tests
```bash
npm test
```

### Test Specific Service
```bash
npm run test:mcp      # Test MCP server
npm run test:storage  # Test storage layer
npm run test:e2e      # End-to-end tests
```

### Manual Testing
```bash
# Test MCP endpoint
curl -X POST http://localhost:3005/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
```

## 🔒 Security

### Default Security Features
- Auto-generated secure passwords (32+ characters)
- Bearer token authentication on all endpoints
- Isolated user contexts
- Encrypted storage for sensitive data
- No passwords in logs or error messages

### Production Hardening
1. Use environment-specific `.env` files
2. Enable HTTPS/TLS in production
3. Set up firewall rules
4. Use secrets management (AWS Secrets Manager, etc.)
5. Enable audit logging

## 📈 Monitoring

### Health Checks
```bash
# Check all services
npm run health

# Individual checks
curl http://localhost:3005/health
```

### Metrics
- Request latency
- Storage usage
- Active sessions
- Cache hit rate

## 🤝 Contributing

We welcome contributions! Please see [CONTRIBUTING.md](docs/CONTRIBUTING.md) for guidelines.

### Development Setup
```bash
# Install dev dependencies
npm install --save-dev

# Run in development mode
npm run dev

# Run with hot reload
npm run dev:watch
```

## 📝 License

MIT License - see [LICENSE](LICENSE) file

## 🆘 Support

### Common Issues

**Q: Services won't start?**
```bash
# Reset everything
npm run reset
npm run setup
```

**Q: Can't connect to MCP server?**
```bash
# Check if running
npm run health

# Check logs
docker logs memory-forge-mcp
```

**Q: How to upgrade?**
```bash
git pull
npm install
npm run migrate
```

### Get Help
- 📧 Email: support@memory-forge.ai
- 💬 Discord: [Join our server](https://discord.gg/memory-forge)
- 🐛 Issues: [GitHub Issues](https://github.com/yourusername/memory-forge/issues)

## 🚀 Roadmap

- [ ] OpenAI function calling support
- [ ] LangChain integration
- [ ] Web UI dashboard
- [ ] Backup/restore tools
- [ ] Multi-region support
- [ ] GraphQL API

---

Built with ❤️ by the Memory Forge team