MCP Memory

repository·main·Indexed 40 days ago

https://github.com/puliczek/mcp-memory

An MCP (Model Context Protocol) Server that enables AI clients like Cursor, Claude, and Windsurf to maintain long-term memory across conversations. Built on Cloudflare's serverless stack, it uses Workers AI (@cf/baai/bge-m3), Vectorize, D1, and Durable Objects to provide semantic retrieval and persistent storage of user preferences and behaviors.

Tokens
2.4K
Snippets
8
Records
11
Agent score
51%

What's inside MCP Memory

  1. What is MCP Memory

    main

    MCP Memory is an MCP (Model Context Protocol) Server designed to give MCP Clients (such as Cursor, Claude, and Windsurf) the ability to remember user information, preferences, and behaviors across different conversations.

    It utilizes vector search technology to perform semantic retrieval, meaning it can find relevant information based on the meaning of a query rather than just exact keyword matches. The system is built on Cloudflare's infrastructure, utilizing Workers, D1, Vectorize, Durable Objects, and Workers AI.

  2. How MCP Memory works: Storage and Retrieval

    main

    MCP Memory uses a RAG (Retrieval-Augmented Generation) architecture powered by Cloudflare services:

    Storing Memories

    1. Embedding Generation: Text is processed by Cloudflare Workers AI using the @cf/baai/bge-m3 model to generate 1024-dimensional embeddings.
    2. Vector Storage: The embeddings are stored in Cloudflare Vectorize for similarity searching.
    3. Text Persistence: The original text and associated metadata are stored in Cloudflare D1.
    4. State Management: A Durable Object (MyMCP) manages state and ensures consistency.
    5. Protocol: The Agents framework handles communication via the MCP protocol.

    Retrieving Memories

    1. Query Embedding: The user query is converted into a vector using the same @cf/baai/bge-m3 model.
    2. Similarity Search: Vectorize performs a search to find the most relevant vector embeddings.
    3. Data Fetching: The D1 database retrieves the original text corresponding to the matched vectors.
    4. Coordination: The Durable Object coordinates the entire retrieval process to return the results.
  3. Security and Rate Limiting in MCP Memory

    main

    MCP Memory implements several security layers:

    • Data Isolation: Each user's memories are stored in isolated namespaces within Vectorize to ensure data separation.
    • Rate Limiting: A built-in rate limit is set to 100 req/min. This can be modified in the wrangler.jsonc configuration file.
    • Authentication: Currently, authentication is based on userId only. While sufficient for basic use with rate limiting, additional layers like API keys or OAuth can be added.
    • Encryption: All communications are secured via TLS encryption provided by Cloudflare.
  4. Deploy MCP Memory to Cloudflare with One-Click

    main

    You can deploy your own instance of MCP Memory to Cloudflare using the one-click deployment button.

    When prompted in the Create Vectorize section, you must use the following configuration:

    • Dimensions: 1024
    • Metric: cosine

    After clicking "Create and Deploy", you can access your deployed worker via the Cloudflare dashboard under "Workers & Pages".

    [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/puliczek/mcp-memory)
  5. Manual Setup and Deployment (Template/CLI users)

    main

    If you are using the repository template or the Cloudflare CLI method, follow these steps to set up and deploy your local environment:

    1. Install dependencies:

      npm install
    2. Create a Vectorize index: You must create a Vectorize index with specific dimensions and a cosine metric to ensure compatibility with the embedding model.

      npx wrangler vectorize create mcp-memory-vectorize --dimensions 1024 --metric cosine
    3. Run locally for development:

      npm run dev
    4. Deploy to Cloudflare:

      npm run deploy
    npm install
    npx wrangler vectorize create mcp-memory-vectorize --dimensions 1024 --metric cosine
    npm run dev
    npm run deploy
  6. Use the addToMCPMemory tool to store information

    main

    The addToMCPMemory tool allows an agent to store important user information, preferences, traits, or technical details in a persistent memory layer. This information is stored in both a Vectorize index (for semantic search) and a D1 database.

    When to use:

    1. When a user explicitly asks to remember something.
    2. When you detect significant user preferences or patterns.
    3. When technical details or emotional responses emerge that are valuable for future context.

    Note: This tool requires explicit invocation via a function call; it is not a passive resource.

    {
      "name": "addToMCPMemory",
      "arguments": {
        "thingToRemember": "string"
      }
    }
  7. Mount the MyMCP agent with a userId

    main

    The MyMCP instance can be mounted within a Hono application. When mounting, the service extracts the userId from the URL path and passes it to the MCP agent's properties (ctx.props). This ensures that the MCP agent operates within the correct user context.

    To mount the agent, use the app.mount pattern where the path is constructed as /${userId}/sse.

    // Example of how the mounting logic is structured internally
    app.mount("/", async (req, env, ctx) => {
      const url = new URL(req.url);
      const pathSegments = url.pathname.split("/");
      const userId = pathSegments[1];
    
      ctx.props = {
        userId: userId,
      };
    
      // The MCP agent handles requests under the /:userId/sse path
      return await MyMCP.mount(`/${userId}/sse`).fetch(req, env, ctx);
    });
  8. Use the searchMCPMemory tool to retrieve context

    main

    The searchMCPMemory tool performs a semantic search across the user's persistent memory layer. It uses semantic matching to find relevant information even if the query doesn't use exact keywords.

    When to use:

    1. When you need historical context about user preferences.
    2. When a user refers to something previously mentioned.
    3. When you need to verify if specific information about the user exists in memory.

    Returns: A list of found memories including their content and a similarity score (e.g., content (score: 0.XXXX)). If no matches are found, it returns a message indicating no relevant memories were found.

    {
      "name": "searchMCPMemory",
      "arguments": {
        "informationToGet": "string"
      }
    }
  9. HTTP API Reference for MCP Memory

    main

    The MCP Memory service exposes a RESTful HTTP API via Hono to manage user memories. These endpoints interact with both a D1 database (for structured storage) and a Vectorize index (for semantic search).

    ### GET /:userId/memories
    Retrieve all memories associated with a specific user.
    
    **Response:**
    - `200 OK`: `{ "success": true, "memories": [...] }`
    - `500 Internal Server Error`: `{ "success": false, "error": "Failed to retrieve memories" }`
    
    ### DELETE /:userId/memories/:memoryId
    Delete a specific memory. This operation removes the record from the D1 database and attempts to remove the corresponding vector from the Vectorize index.
    
    **Response:**
    - `200 OK`: `{ "success": true }`
    - `500 Internal Server Error`: `{ "success": false, "error": "Failed to delete memory" }`
    
    ### PUT /:userId/memories/:memoryId
    Update the content of an existing memory. The request body must contain a `content` string.
    
    **Request Body:**
    ```json
    {
      "content": "the new memory content"
    }

    Response:

    • 200 OK: { "success": true }
    • 400 Bad Request: { "success": false, "error": "Invalid or missing content in request body" }
    • 404 Not Found: { "success": false, "error": "[error message containing 'not found']" }
    • 500 Internal Server Error: { "success": false, "error": "[error message]" }