mcp server
claude-memory-gcp
Persistent memory for Claude Code with PostgreSQL + Vertex AI hybrid search
Set up
Runs on your computer. Pick your agent and operating system.
This project does not publish an install method we can turn into a config. Follow the README instead.
README
synced Oct 22, 2026claude-memory-gcp
Persistent memory for Claude Code with PostgreSQL + Vertex AI hybrid search.
Who is this for?
Anyone who wants persistent memory for Claude Code. You need:
- A Google Cloud account (free tier works for testing)
gcloudCLI installed (install guide)- ~10 minutes with Claude Code helping you set up
💡 Pro tip: Just paste this README to Claude Code and say "help me set this up" — Claude will run the commands for you.
Why?
Stop re-explaining your project every session. Claude Code forgets everything when you close the terminal. This MCP server gives Claude long-term memory that persists across sessions, with enterprise-grade hybrid search.
Uses cloud infrastructure (see FAQ.md for detailed comparison):
- Cloud SQL — managed PostgreSQL with pgvector (or any PostgreSQL 15+ with pgvector)
- Vertex AI Embeddings —
text-multilingual-embedding-002model (768 dimensions, 100+ languages) - GCE VM — runs the MCP server with automatic auth via Service Account
Vertex AI Embeddings benefits:
- 🆓 No API key — Service Account handles auth
- 🌍 Multilingual — 100+ languages native support
- 🔒 Your data stays in GCP — not sent to third parties
- ⚡ Fast — 768 dimensions, optimized for search
- 💰 Cheap — ~$0.0001 per 1K characters
💡 Note: This uses Vertex AI Embeddings, not Gemini. No API key needed — authentication is handled by the Service Account (step 4).
💡 Note: You can use any PostgreSQL with pgvector — Cloud SQL, AlloyDB, or self-hosted. Cloud SQL is recommended for simplicity.
Features
- Multi-Project Support — Work on multiple projects with isolated or shared context. Filter by project or search across all.
- Hybrid Search — Combines Full-Text Search + Vector similarity with RRF (Reciprocal Rank Fusion)
- Multilingual — Native support for Latin and Cyrillic scripts
- Cloud-Native — PostgreSQL on Cloud SQL + Vertex AI embeddings (not local SQLite)
- Smart Scoring — 5-factor relevance: FTS (25%) + Vector (35%) + Importance (20%) + Recency (15%) + Frequency (5%)
- Entity Extraction — Automatic extraction of files, technologies, concepts
Architecture
┌─────────────────┐ SSH + JSON-RPC ┌─────────────────────────────┐
│ Claude Code │◄──────────────────────►│ MCP Server (Node.js) │
│ │ │ │
│ memory_store │ │ ┌─────────────────────────┐ │
│ memory_recall │ │ │ Hybrid Search │ │
│ memory_status │ │ │ FTS + Vector + RRF │ │
│ memory_forget │ │ └───────────┬─────────────┘ │
└─────────────────┘ │ │ │
└──────────────┼───────────────┘
│
┌─────────────────────────────┼─────────────────────────────┐
│ Google Cloud │ │
│ │ │
│ ┌──────────────────┐ ┌───▼────────────────┐ │
│ │ Cloud SQL │ │ Vertex AI │ │
│ │ PostgreSQL 15 │ │ Embeddings │ │
│ │ + pgvector │ │ 768 dimensions │ │
│ │ + pg_trgm │ │ multilingual │ │
│ └──────────────────┘ └────────────────────┘ │
│ │
└────────────────────────────────────────────────────────────┘
Quick Start
Prerequisites
- Node.js 18+
- Google Cloud project (see GCP Setup below)
- Claude Code CLI installed
GCP Setup
# Set your project (replace with your project ID)
gcloud config set project YOUR_PROJECT_ID
# Enable required APIs
gcloud services enable sqladmin.googleapis.com
gcloud services enable aiplatform.googleapis.com
# Create instance (db-f1-micro for testing, db-g1-small for production)
gcloud sql instances create claude-memory \
--database-version=POSTGRES_15 \
--tier=db-f1-micro \
--region=us-central1 \
--database-flags=cloudsql.enable_pgvector=on
# Create database
gcloud sql databases create claude_memory_db \
--instance=claude-memory
# Create user (save this password!)
gcloud sql users create claude_user \
--instance=claude-memory \
--password=YOUR_SECURE_PASSWORD
# Get connection name (save this for later)
gcloud sql instances describe claude-memory --format="value(connectionName)"
# Output: YOUR_PROJECT_ID:us-central1:claude-memory
Connect to your database via Cloud SQL Proxy and enable extensions:
# Install proxy (choose your platform)
# macOS ARM:
curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.8.0/cloud-sql-proxy.darwin.arm64
# macOS Intel:
curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.8.0/cloud-sql-proxy.darwin.amd64
# Linux:
curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.8.0/cloud-sql-proxy.linux.amd64
chmod +x cloud-sql-proxy
# Start proxy (use connection name from step 1)
# Run in separate terminal or add & at the end
./cloud-sql-proxy YOUR_PROJECT_ID:us-central1:claude-memory --port 5432 &
# Connect and enable extensions (enter password from step 1)
# Note: psql required. macOS: brew install libpq, Linux: apt install postgresql-client
psql "host=127.0.0.1 port=5432 user=claude_user dbname=claude_memory_db" << 'EOF'
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
\q
EOF
Already done in step 1! Verify with:
gcloud services list --enabled | grep aiplatform
# Should show: aiplatform.googleapis.com
# Get your project ID
PROJECT_ID=$(gcloud config get-value project)
# Create service account
gcloud iam service-accounts create claude-memory-sa \
--display-name="Claude Memory Service Account"
# Grant Vertex AI access
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:claude-memory-sa@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/aiplatform.user"
# Grant Cloud SQL access
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:claude-memory-sa@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="roles/cloudsql.client"
# Get project ID
PROJECT_ID=$(gcloud config get-value project)
# Create VM with service account
gcloud compute instances create claude-memory-vm \
--zone=us-central1-a \
--machine-type=e2-small \
--service-account=claude-memory-sa@${PROJECT_ID}.iam.gserviceaccount.com \
--scopes=cloud-platform
# SSH into VM
gcloud compute ssh claude-memory-vm --zone=us-central1-a
Run these commands on the VM:
# Install Node.js 18+
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs git
# Install Cloud SQL Proxy
curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.8.0/cloud-sql-proxy.linux.amd64
chmod +x cloud-sql-proxy
sudo mv cloud-sql-proxy /usr/local/bin/
# Clone and build
git clone https://github.com/alexpo-hf/claude-memory-gcp.git
cd claude-memory-gcp
npm install
npm run build
# Set up environment (replace YOUR_PROJECT_ID and YOUR_PASSWORD)
cat >> ~/.bashrc << 'EOF'
export CLAUDE_MEMORY_DB_URL="postgresql://claude_user:YOUR_PASSWORD@127.0.0.1:5432/claude_memory_db"
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
EOF
source ~/.bashrc
# Start Cloud SQL Proxy in background (replace YOUR_PROJECT_ID)
cloud-sql-proxy YOUR_PROJECT_ID:us-central1:claude-memory --port 5432 &
# Run migrations
npm run migrate
# Test that it works
node dist/index.js
# Should output: [claude-memory-gcp] Server running
# Press Ctrl+C to stop
Set up SSH config on your local machine (~/.ssh/config):
# Get VM external IP
gcloud compute instances describe claude-memory-vm \
--zone=us-central1-a \
--format="value(networkInterfaces[0].accessConfigs[0].natIP)"
Add to ~/.ssh/config:
Host claude-memory-vm
HostName <EXTERNAL_IP from above>
User <your-gcp-username> # same as shown in gcloud compute ssh prompt
IdentityFile ~/.ssh/google_compute_engine
Test: ssh claude-memory-vm "echo ok" should print ok.
Configure Claude Code
After completing GCP Setup (steps 1-5 above), add to your local ~/.mcp.json:
{
"mcpServers": {
"claude-memory-gcp": {
"command": "ssh",
"args": [
"claude-memory-vm",
"cloud-sql-proxy YOUR_PROJECT_ID:us-central1:claude-memory --port 5432 & sleep 2 && cd ~/claude-memory-gcp && node dist/index.js"
]
}
}
}
Replace YOUR_PROJECT_ID with your actual GCP project ID.
Claude Code will SSH to your VM, start Cloud SQL Proxy, and run the MCP server.
Environment Variables (already set on VM in step 5):
| Variable | Required | Description |
|---|---|---|
CLAUDE_MEMORY_DB_URL | Yes | PostgreSQL connection string |
GOOGLE_CLOUD_PROJECT | Yes | GCP project ID for Vertex AI |
VERTEX_AI_LOCATION | No | Vertex AI region (default: us-central1) |
Verify Installation
Restart Claude Code, then ask Claude:
Check memory status
Claude should call memory_status and show connected status with 0 memories.
MCP Tools
memory_store
Save a new memory:
{
"content": "Implemented JWT authentication with refresh tokens",
"type": "decision",
"importance": 8,
"project": "my-api",
"expiresIn": "30d"
}
Parameters:
| Parameter | Type | Description |
|---|---|---|
content | string | The memory content (required) |
type | enum | general, code, decision, context, error, task |
importance | 1-10 | Priority level (default: 5) |
project | string | Project name for filtering |
expiresIn | string | Expiration: 7d, 30d, never |
memory_recall
Search memories with hybrid search:
{
"query": "authentication JWT",
"limit": 5,
"project": "my-api",
"searchMode": "hybrid"
}
Parameters:
| Parameter | Type | Description |
|---|---|---|
query | string | Search query (required) |
limit | number | Max results (default: 10) |
searchMode | enum | hybrid, fts, vector |
project | string | Filter by project |
type | enum | Filter by memory type |
minImportance | 1-10 | Minimum importance |
memory_status
Get system status:
{
"memoryCount": 42,
"searchMode": "hybrid",
"dbStatus": "connected",
"topEntities": ["TypeScript", "PostgreSQL", "API"],
"recentMemories": 10,
"expiringMemories": 2
}
memory_forget
Delete memories:
{
"id": "uuid-here"
}
Or bulk delete:
{
"query": "test",
"olderThan": "30d",
"confirm": true
}
Hybrid Search Algorithm
RRF (Reciprocal Rank Fusion)
Combines FTS and Vector search results:
rrf_score = 1/(k + fts_rank) + 1/(k + vector_rank)
Where k = 60 (standard RRF constant).
Final Scoring
final_score =
0.25 × fts_score +
0.35 × vector_similarity +
0.20 × (importance / 10) +
0.15 × recency_decay +
0.05 × access_frequency
Multilingual Support
Uses PostgreSQL simple text search configuration + Vertex AI text-multilingual-embedding-002 model:
- FTS: Works with any language (no stemming, exact matching)
- Vector: 768-dimensional embeddings trained on 100+ languages
- Result: Cross-language search (Latin query finds Cyrillic content and vice versa)
Query: "deploy server"
Finds: "деплой на сервер" (Cyrillic)
"implementar servidor" (Latin)
Database Schema
-- Main memories table
CREATE TABLE memories (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
content TEXT NOT NULL,
summary TEXT,
type VARCHAR(50) DEFAULT 'general',
project VARCHAR(255) DEFAULT 'default',
importance INTEGER DEFAULT 5,
embedding VECTOR(768),
metadata JSONB DEFAULT '{}',
fts_vector TSVECTOR, -- Full-text search (auto-generated)
created_at TIMESTAMPTZ DEFAULT NOW(),
last_accessed TIMESTAMPTZ DEFAULT NOW(),
access_count INTEGER DEFAULT 0,
expires_at TIMESTAMPTZ,
is_deleted BOOLEAN DEFAULT FALSE
);
-- Extracted entities
CREATE TABLE entities (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(255) NOT NULL UNIQUE,
type VARCHAR(50) NOT NULL,
metadata JSONB DEFAULT '{}'
);
-- Memory-entity relationships
CREATE TABLE memory_entities (
memory_id UUID REFERENCES memories(id) ON DELETE CASCADE,
entity_id UUID REFERENCES entities(id) ON DELETE CASCADE,
PRIMARY KEY (memory_id, entity_id)
);
Performance
Startup Time
Optimized with lazy loading:
| Stage | Time |
|---|---|
| SSH connection | ~150ms |
| Node.js startup | ~200ms |
| Database connection | ~400ms |
| Total cold start | ~5s |
Vertex AI SDK loads on first embedding request (not at startup).
Search Performance
| Memories | Hybrid Search |
|---|---|
| 100 | ~200ms |
| 1,000 | ~500ms |
| 10,000 | ~2s |
Comparison with Other Solutions
| Feature | claude-memory-gcp | SQLite-based | Neo4j-based |
|---|---|---|---|
| Backend | Cloud SQL | Local file | Local/Cloud |
| Embeddings | Vertex AI | OpenAI/Local | None |
| Search | Hybrid (FTS+Vector) | FTS only | Graph queries |
| Multilingual | Native | Limited | Limited |
| Scalability | Cloud-native | Single machine | Moderate |
| Scoring | 5-factor | Basic | Graph-based |
Usage Examples
How Claude Uses Memory
Claude automatically has access to these tools. Here's how a typical workflow looks:
Starting a new session:
User: "Let's continue working on the API"
Claude: [Calls memory_recall with query "API project context"]
"I see from my memory that we were working on the authentication
module. Last session we implemented JWT refresh tokens..."
Saving important decisions:
User: "Let's use Redis for session storage instead of PostgreSQL"
Claude: [Calls memory_store with type "decision", importance 8]
"Got it. I've noted this architectural decision about using Redis
for sessions."
Recalling error solutions:
User: "I'm getting that CORS error again"
Claude: [Calls memory_recall with query "CORS error fix"]
"I found a previous solution: we needed to add the
'credentials: include' option..."
Multi-project workflow:
User: "Let's work on the discord-bot project"
Claude: [Calls memory_recall with project "discord-bot"]
"Loading context for discord-bot... I see we're using
discord.py with slash commands..."
User: "What auth pattern did we use in the api project?"
Claude: [Calls memory_recall with query "auth" project "api"]
"In the api project, we used JWT with refresh tokens..."
Prompt Engineering Tips
Add to your CLAUDE.md or system prompt:
## Memory Usage
When starting a session:
1. Call memory_recall with project name to load context
2. Check memory_status for system health
When to save memories:
- Architectural decisions (importance: 8-10)
- Bug fixes and workarounds (importance: 7-9)
- Project-specific configurations (importance: 5-7)
Troubleshooting
Symptom: Claude Code shows "Server failed to start" or hangs.
Cause: Vertex AI SDK loading takes too long.
Solution: This is fixed in v0.5.0+ with lazy loading. If still occurring:
- Check SSH connection speed
- Verify Node.js version is 18+
- Check VM has sufficient memory (512MB+)
Symptom: Memories save but vector search returns no results.
Check:
# Verify Vertex AI API is enabled
gcloud services list --enabled | grep aiplatform
# Check service account permissions
gcloud projects get-iam-policy PROJECT_ID \
--filter="bindings.members:claude-memory-sa"
Symptom: ECONNREFUSED or Connection refused
Solutions:
- Check Cloud SQL Proxy is running on the VM:
ssh claude-memory-vm "pgrep -f cloud-sql-proxy" - Start proxy manually if not running:
ssh claude-memory-vm "cloud-sql-proxy YOUR_PROJECT_ID:us-central1:claude-memory --port 5432 &" - Test connection:
ssh claude-memory-vm "psql \$CLAUDE_MEMORY_DB_URL -c 'SELECT 1'"
Symptom: ERROR: type "vector" does not exist
Solution:
-- Connect as postgres user
CREATE EXTENSION IF NOT EXISTS vector;
-- Verify
SELECT * FROM pg_extension WHERE extname = 'vector';
For Cloud SQL, ensure cloudsql.enable_pgvector=on flag is set.
Cost Estimation
Monthly costs for a small deployment (~100 memories/month):
| Resource | Specification | Cost/month |
|---|---|---|
| Cloud SQL | db-f1-micro (shared) | ~$7 |
| Vertex AI | ~100 embedding calls | ~$0.01 |
| VM (optional) | e2-small | ~$12 |
| Total | ~$7-19 |
Cost optimization tips:
- Use db-f1-micro for testing, upgrade only if needed
- VM is optional if you have another way to access Cloud SQL
- Embeddings are very cheap (~$0.0001 per 1K characters)
Security
Data Storage
- All memories stored in your own Cloud SQL instance
- Embeddings generated via Vertex AI (data processed but not stored by Google)
- No data leaves your GCP project
Recommendations
- Use Cloud SQL Proxy — secure tunnel, no public IP needed
- Restrict service account permissions — minimal required roles only
- Enable SSL for database connections
- Don't store secrets in memories — treat as semi-public data
Encryption
- Cloud SQL: encrypted at rest by default (Google-managed keys)
- Optional: Customer-managed encryption keys (CMEK)
- In transit: SSL/TLS for all connections
Development
# Install dependencies
npm install
# Development mode
npm run dev
# Build
npm run build
# Run migrations
npm run migrate
# Run tests
npm test
# Type check
npm run typecheck
License
MIT
Contributing
Contributions welcome! Please read the contributing guidelines first.
Built for Claude Code on Google Cloud Platform.