◉CLAUDE LABJP
●2.1.301 — Adds the vim % motion, LaTeX math rendering in the VS Code panel, and a retry-watchdog limit for usage-limit waits (10/15)●2.1.299 — Conversations over 200K tokens left idle about 54 minutes get compacted; MCP allow rules now match only the server they name●SONNET 4.5 — Retires on the Claude API on 11/30, 45 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST MODE — Opus 5.5 fast mode is out of research preview and no longer needs the beta header (10/15)●NEW — I Put a Ten-Line Promise File at the To…●2.1.301 — Adds the vim % motion, LaTeX math rendering in the VS Code panel, and a retry-watchdog limit for usage-limit waits (10/15)●2.1.299 — Conversations over 200K tokens left idle about 54 minutes get compacted; MCP allow rules now match only the server they name●SONNET 4.5 — Retires on the Claude API on 11/30, 45 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST MODE — Opus 5.5 fast mode is out of research preview and no longer needs the beta header (10/15)●NEW — I Put a Ten-Line Promise File at the To…
Articles/API & SDK
⬡ API & SDK/2026-03-29Advanced

Claude Long-Term Memory with MCP — Production Implementation Guide

A production-grade walkthrough of long-term memory with MCP — vector DB metrics, scale-based DB selection, and the embedding-model pitfalls the official docs don't mention.

Long-Term MemoryMCP54PersonalizationVector DBClaude API128Memory Management

✦ Premium Article

"Pick up where we left off" is the first wall you hit when you try to embed Claude seriously into an app. I've been shipping iOS and Android apps as a solo developer since 2014 — the apps have crossed 50 million downloads in total — and the inability to remember user preferences has consistently held back experience quality. Long-term memory built on MCP (Model Context Protocol) is the first design I've used that actually lifts that ceiling.

Once you put it into production, though, the official docs leave several pitfalls untouched. This article shares the metrics I've measured running vector DBs in production, scale-based recommendations for vector DB selection, and the design judgment calls I've made running four Stripe-billed sites (Claude Lab, Gemini Lab, Antigravity Lab, Rork Lab) side by side.

Long-Term Memory Architecture

Integrating MCP with Persistent Storage

Long-term memory in AI systems requires a three-layer architecture:

┌─────────────────────────────────────────┐
│        Claude API                       │
│   (Message + Context Window)            │
└──────────────────┬──────────────────────┘
                   │
        ┌──────────▼──────────┐
        │   MCP Protocol      │
        │  (Tool Definitions) │
        └──────────┬──────────┘
                   │
    ┌──────────────┼──────────────┐
    │              │              │
┌───▼───┐  ┌──────▼──────┐ ┌────▼─────┐
│ Memory│  │ Vector DB   │ │ User DB  │
│ Store │  │ (Pinecone)  │ │(PostgreSQL)
└───────┘  └─────────────┘ └──────────┘

API Layer: Handles messages and token management MCP Layer: Defines tools and memory operations Persistence Layer: Vector embeddings, user metadata, audit logs

Complete Memory Lifecycle

// lib/memory-lifecycle.ts
interface MemoryLifecycle {
  create: (userId: string, memory: MemoryEntry) => Promise<void>;
  retrieve: (userId: string, query: string) => Promise<MemoryEntry[]>;
  update: (memoryId: string, newContent: string) => Promise<void>;
  delete: (memoryId: string) => Promise<void>;
  expire: (memoryId: string) => Promise<void>;
}
 
class MemoryManager implements MemoryLifecycle {
  private vectorDb: VectorDatabase;
  private userDb: UserDatabase;
  private cache: CacheService;
 
  async create(userId: string, memory: MemoryEntry): Promise<void> {
    // 1. Convert text to embeddings
    const embedding = await this.embedText(memory.content);
 
    // 2. Store in vector database
    const vectorId = await this.vectorDb.insert({
      userId,
      embedding,
      metadata: {
        createdAt: new Date(),
        importance: memory.importance,
        category: memory.category,
        expiresAt: this.calculateExpiration(memory.ttl),
      },
    });
 
    // 3. Store reference in user database
    await this.userDb.insertMemoryRef({
      userId,
      vectorId,
      originalContent: memory.content,
      category: memory.category,
      createdAt: new Date(),
    });
 
    // 4. Invalidate cache
    this.cache.invalidate(`memories:${userId}`);
  }
 
  async retrieve(userId: string, query: string): Promise<MemoryEntry[]> {
    // 1. Check cache first
    const cached = this.cache.get(`memories:${userId}:${query}`);
    if (cached) return cached;
 
    // 2. Convert query to embedding
    const queryEmbedding = await this.embedText(query);
 
    // 3. Vector similarity search
    const matches = await this.vectorDb.search({
      embedding: queryEmbedding,
      userId,
      limit: 5,
      filter: {
        expiresAt: { $gt: new Date() }, // Only non-expired
      },
    });
 
    // 4. Return memories ranked by relevance
    const memories = matches.map((m) => ({
      id: m.id,
      content: this.decryptContent(m.metadata.content),
      importance: m.metadata.importance,
      relevanceScore: m.similarity,
      category: m.metadata.category,
    }));
 
    // 5. Cache result (5-minute TTL)
    this.cache.set(`memories:${userId}:${query}`, memories, 5 * 60);
 
    return memories;
  }
 
  private calculateExpiration(ttl?: number): Date {
    const days = ttl || 30;
    const expiry = new Date();
    expiry.setDate(expiry.getDate() + days);
    return expiry;
  }
}

MCP Tool Definition

Memory Operations

Claude interacts with long-term memory through MCP tools:

// mcp-tools/memory-tools.ts
const memoryTools = {
  save_memory: {
    name: "save_memory",
    description: "Save important information to long-term memory",
    inputSchema: {
      type: "object",
      properties: {
        content: {
          type: "string",
          description: "Memory content (max 1000 chars)",
        },
        category: {
          type: "string",
          enum: [
            "user_preference",
            "project_context",
            "skill_profile",
            "past_conversation",
            "decision_log",
          ],
        },
        importance: {
          type: "number",
          enum: [1, 2, 3, 4, 5],
          description: "Importance level",
        },
        ttl_days: {
          type: "number",
          description: "Time to live in days (default: 30)",
        },
      },
      required: ["content", "category", "importance"],
    },
  },
 
  retrieve_memory: {
    name: "retrieve_memory",
    description: "Search and retrieve relevant memories",
    inputSchema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description: "Search query",
        },
        category: {
          type: "string",
          description: "Optional category filter",
        },
        limit: {
          type: "number",
          description: "Max results (default: 5)",
        },
      },
      required: ["query"],
    },
  },
 
  update_memory: {
    name: "update_memory",
    description: "Update an existing memory",
    inputSchema: {
      type: "object",
      properties: {
        memory_id: {
          type: "string",
        },
        content: {
          type: "string",
        },
        importance: {
          type: "number",
          enum: [1, 2, 3, 4, 5],
        },
      },
      required: ["memory_id", "content"],
    },
  },
 
  delete_memory: {
    name: "delete_memory",
    description: "Delete a memory entry",
    inputSchema: {
      type: "object",
      properties: {
        memory_id: {
          type: "string",
        },
      },
      required: ["memory_id"],
    },
  },
 
  get_memory_summary: {
    name: "get_memory_summary",
    description: "Get summary of all memories",
    inputSchema: {
      type: "object",
      properties: {
        category: {
          type: "string",
          description: "Optional category filter",
        },
      },
    },
  },
};

MCP Handler Implementation

// mcp-handlers/memory-handler.ts
class MemoryMCPHandler {
  private memoryManager: MemoryManager;
  private auditLog: AuditLogger;
 
  async handleToolCall(
    userId: string,
    toolName: string,
    toolInput: Record<string, any>
  ): Promise<string> {
    switch (toolName) {
      case "save_memory":
        return this.handleSaveMemory(userId, toolInput);
 
      case "retrieve_memory":
        return this.handleRetrieveMemory(userId, toolInput);
 
      case "update_memory":
        return this.handleUpdateMemory(userId, toolInput);
 
      case "delete_memory":
        return this.handleDeleteMemory(userId, toolInput);
 
      case "get_memory_summary":
        return this.handleGetSummary(userId, toolInput);
 
      default:
        throw new Error(`Unknown tool: ${toolName}`);
    }
  }
 
  private async handleSaveMemory(
    userId: string,
    input: Record<string, any>
  ): Promise<string> {
    const { content, category, importance, ttl_days } = input;
 
    // Validation
    if (!content || content.length > 1000) {
      throw new Error("Content must be 1-1000 characters");
    }
 
    const validCategories = [
      "user_preference",
      "project_context",
      "skill_profile",
      "past_conversation",
      "decision_log",
    ];
 
    if (!validCategories.includes(category)) {
      throw new Error("Invalid category");
    }
 
    // Save memory
    const memoryId = await this.memoryManager.create(userId, {
      content,
      category,
      importance,
      ttl: ttl_days,
    });
 
    // Audit log
    await this.auditLog.log({
      userId,
      action: "save_memory",
      memoryId,
      timestamp: new Date(),
    });
 
    return JSON.stringify({
      success: true,
      memoryId,
      message: `Memory saved (importance: ${importance}/5)`,
    });
  }
 
  private async handleRetrieveMemory(
    userId: string,
    input: Record<string, any>
  ): Promise<string> {
    const { query, category, limit = 5 } = input;
 
    const memories = await this.memoryManager.retrieve(userId, query);
 
    // Audit search (without logging query content)
    await this.auditLog.log({
      userId,
      action: "retrieve_memory",
      resultCount: memories.length,
      timestamp: new Date(),
    });
 
    return JSON.stringify({
      count: memories.length,
      memories: memories.map((m) => ({
        id: m.id,
        content: m.content,
        importance: m.importance,
        relevanceScore: m.relevanceScore,
      })),
    });
  }
 
  private async handleUpdateMemory(
    userId: string,
    input: Record<string, any>
  ): Promise<string> {
    const { memory_id, content, importance } = input;
 
    // Permission check
    const owner = await this.memoryManager.getMemoryOwner(memory_id);
    if (owner !== userId) {
      throw new Error("Unauthorized");
    }
 
    await this.memoryManager.update(memory_id, { content, importance });
 
    return JSON.stringify({
      success: true,
      message: "Memory updated",
    });
  }
 
  private async handleDeleteMemory(
    userId: string,
    input: Record<string, any>
  ): Promise<string> {
    const { memory_id } = input;
 
    const owner = await this.memoryManager.getMemoryOwner(memory_id);
    if (owner !== userId) {
      throw new Error("Unauthorized");
    }
 
    await this.memoryManager.delete(memory_id);
 
    return JSON.stringify({
      success: true,
      message: "Memory deleted",
    });
  }
 
  private async handleGetSummary(
    userId: string,
    input: Record<string, any>
  ): Promise<string> {
    const summary = await this.memoryManager.getSummary(userId);
 
    return JSON.stringify({
      totalMemories: summary.totalCount,
      byCategory: summary.byCategory,
      summary: summary.contentSummary,
    });
  }
}
✦

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
✦Embedding model upgrades replace ~23% of top-5 hits — full migration playbook with parallel dual-vector retention and fallback code included
✦Vector DB selection by scale: pgvector (under 1k MAU), Pinecone Serverless (1k–50k MAU), self-hosted Weaviate/Qdrant (50k+ MAU) with monthly cost ranges
✦Production-measured numbers: $1.5/month embedding cost per 1,000 MAU, +28% hit-rate from recency boost, full p50/p95 latency breakdown
Secure payment via Stripe · Cancel anytime
✦

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

Related Articles

⬡ API & SDK2026-10-16
Sending 40 Rows From Make to the Claude API Stops at Row 14 — Avoiding the 429 With One Subtraction
Why a no-code automation that sends spreadsheet rows to the Claude API one by one hits a 429 partway through, and how to fix it. Seven spacing strategies tested on a mock bucket, a formula for the Sleep delay, and settings that stop failed rows from vanishing.
⬡ API & SDK2026-10-13
Haiku 5.5 is cheaper per token, but your bill jumps fivefold past about 77k Haiku 4.5 tokens
On the price sheet, Haiku 5.5 costs roughly a tenth of Haiku 4.5. But the same text becomes about 30% more tokens, and a prompt over 100k tokens is billed at five times the rate. Here is the boundary in Haiku 4.5 terms, a script I actually ran, and the changes that return a 400.
⬡ API & SDK2026-10-08
Before Sonnet 4.5 retires, one script to find the arguments that will return a 400
claude-sonnet-4-5 retires on November 30. Swapping the model ID is not enough: budget_tokens, prefill, and tool_choice will fail. Here is a scanner built from the official migration guide, its real output, and the order I would fix things in.