Skip to main content

Building MemPalace: Secure Local AI Memory with Cloudflare Zero Trust and Antigravity IDE

Build a private long-term AI memory system. Step-by-step guide to self-hosting MemPalace on a homelab, securing remote access with Cloudflare Zero Trust, and integrating Model Context Protocol (MCP) in Antigravity IDE for automated code context.
Contents

MemPalace

“Memory is identity.”
mempalaceofficial.com

MemPalace recently went viral – partly due to celebrity backing from Milla Jovovich, and partly due to some highly controversial benchmark claims that the AI community quickly debunked. But if you look past the marketing hype and the synthetic benchmark drama, the underlying architecture provides something genuinely useful: a local, persistent vector database connected to your IDE via the Model Context Protocol (MCP).

It has become a perfect catalyst for the promotion of Anthropic’s Model Context Protocol (MCP) in use with selected AI tools.

MemPalace is a local-first memory solution for AI Agents, hosted on GitHub under the MIT license and released for free to the community.

The main goal is, through its memory, to significantly reduce selected AI model context usage and help users stay well within rate limits (whatever they may be).

What it brings to the table

Usually, when you start a new chat with an AI tool, it has no idea who you are or what you worked on yesterday. Unless it has its own memory and personalisation activated, which is very limited, each chat is a new conversation with just a minimum background about yourself. MemPalace saves your entire conversation history, in a smart way, so the AI can recall specific decisions or details from some time ago, avoiding so-called Digital Amnesia.

Each chat with whatever AI tool you are using has a so-called context window (a small brain). It can remember and process (work on) a limited amount of information. If its context window is full, it needs to dump some of the information from it. Usually, the information or prompt that was given at the beginning is lost, and at some point in the same chat, you start experiencing hallucinations and feeling like it forgot something important.

The project is privacy-oriented from the start. Because it can work offline or in a secure, isolated environment, your data never leaves your designated machine. There are no cloud fees, and you don’t have to worry about a company training its models on your private files.

It uses an outstanding organisation method for data. Different projects are stored in specific “wings,” topics in “rooms,” and details in “drawers”. This makes it much faster and more accurate at finding the right information than just searching a giant, messy list of files or going through lengthy chats, where at some point, the context from the beginning starts getting lost.

Why it’s so good

Most systems try to “summarise” what you said, which often loses the original meaning. MemPalace saves your words exactly as you said them, ensuring nothing is lost in translation.

It doesn’t need to call an expensive AI just to store or find a memory; it uses smart local search to do the heavy lifting for free.

It’s built to feel like a real Memory Palace, a technique used since ancient Greece to remember huge amounts of information by imagining them in a physical space.


All sounds very inspirational.

While currently online AI web chats, like Gemini, do not support the MCP protocol, there are some tools that can support it. If you are editing files on your computer, from programming and web development to simply working on markdown-formatted text, you may come across an app called VS Code.

Through the MCP protocol in VS Code (or an equivalent fork of the app), you can connect various things to it. Adding MemPalace through the MCP protocol will give your AI tool a unique memory, potentially saving you time and, what’s more important, tokens.

Each AI tool has its limit. The more you pay, the more you can do, so your limits are not reached as quickly, yet none of the tools allow you to work non-stop without limits. Repeating yourself and some of the information you remember, but your tool does not, wastes your usage limits.

Imagine that…

Each project you are working on can become a wing. Wings will not mix, unless you decide to use Cross-Wing Tunnels.

When you are working on a website project in VS Code, this project can become your Wing1. Through this project, you develop some smart code that you would like to reuse in the next project you create, so you don’t need to reinvent the wheel; this project will be your Wing2.

Without needing to remember how you did that or in which files you stored those things, you can recall the memory from your MemPalace and through a cross-wing tunnel work along and share what you have already solved.

It’s like Google Gemini: when you are starting your new chat, you can add a Gemini Notebook where you gather all sources that may be important for the conversation. Your conversation starts with some sources and some memory at the beginning.


It’s like you starting a job in one workplace, where you learn stuff. When you leave and go to another company, you are not starting from scratch; you recall, from your memory, what you learned in the other place and reuse this in the new workplace. This is the ideology of MemPalace at its merit.

How it stores information

MemPalace doesn’t just “save a giant chat”; it breaks your information into tiny, organised LEGO bricks.

Instead of making the AI read a 100-page long chat history every time you ask a question, MemPalace will:

  • Extract the essence – identify key facts, people, and decisions.
  • Categorise by “Room” – file those facts into “closets” and “drawers” based on the topic.
  • Find only what’s needed – when you ask a question, it only pulls the specific “bricks” required to answer, rather than the whole bucket.

This makes it fast and efficient because the AI doesn’t get overwhelmed by “noise” and it only sees the relevant facts. But what’s more important, your long chats are not burning your usage limits like crazy when responding to a simple query that you could Google.

Unlike many AI memory tools that rely on a model to write a compressed summary of a chat, MemPalace stores your exact words in their original form. Your “bricks” are original transcripts, meaning no nuance is lost.

When a conversation happens, the system slices the text into smaller, overlapping chunks – typically around 512 tokens – so that context is not lost at the boundaries of long messages.

The data is sorted into a mental building:

  • Wings: Top-level categories for entire projects or people.
  • Rooms: Specific topics within a wing – such as technical discussions, meetings, or planning.
  • Halls: Classifications of the memory type – like facts, events, or preferences.
  • Drawers: The final destination where the individual text chunks live.

Each drawer is converted into a mathematical vector and safely stored in a local database (called ChromaDB).

When you ask a question, the system mathematically compares your prompt to the stored vectors. It calculates the relevance score to open only the relevant “drawers,” delivering precise context to the AI without dumping the entire chat history.

Essentially, it merges a highly structured tagging system with mathematical search – giving the AI exactly the context it needs whilst keeping everything entirely local and efficiently organised.

Gemini AI Pro and Antigravity IDE

As my daily code editor, I am utilising VS Code or VS Codium, which works the same, but is open-source and has all Microsoft and default AI services removed.

Once I started testing Gemini in the AI Pro plan, I started utilising Antigravity IDE, which is an equivalent of VS Codium but with added deep integration with AI and agentic coding.

With the AI Pro plan, I am getting access to AI Agents based on Gemini models and Claude. All at much higher usage limits.

Despite higher limits in a higher-paid plan, I can easily exhaust my quota, which is divided into a 5-hour allowance (reset after 5 hours) and total usage accounted for in a weekly allowance (reset after a week).

The problem is that sometimes a chat with an Agent can quickly use your allowance, even with simple tasks. Every conversation and every output generated are tokens that are used. The ability to reduce unnecessary use of tokens on repeated tasks would be very beneficial; this is where the memory of MemPalace may come in useful.

MCP MemPalace will help me stretch my token allowance over time by preventing token inflation in long conversations.

How MemPalace Reduces Token Usage in Antigravity IDE

  1. Replaces Massive Context Dumps with Targeted Search (RAG)
  • Without MemPalace: As my conversation grows or I ask Antigravity to analyse large codebases/past decisions, the agent has to continually resend massive chunks of transcript history or whole files back into the prompt window.

  • With MemPalace: MemPalace mines my codebase, past decisions, and chat history locally. Using semantic retrieval and text chunking, it injects only tiny, relevant snippets (often just ~100–300 tokens) into the context window exactly when needed.

  1. Prevents Agent “Re-derivation” Loops
  • Without persistent memory, an agent in a new session often re-analyses the same architectural patterns, re-reads configuration files, or repeats trial-and-error steps it already solved yesterday.

  • By persisting lessons into its local memory graph (drawers and diary entries), the agent skips redundant reasoning loops, saving thousands of tokens per session. This will allow me to use the powerful, yet limited, Gemini AI Pro plan for longer.

  1. Optimised Antigravity Integration
  • MemPalace includes native lifecycle hooks (mempalace-wake and mempalace-save) specifically designed for Google Antigravity.

  • It injects background memory as an ephemeral single-turn message, meaning memory context is loaded for the exact task and automatically discarded from future prompt turns so it does not permanently bloat my context window.

Nothing is free - Token Tax

While MemPalace saves tokens on context length, MCP integration itself carries a small token tax:

  • Tool Schema Overhead: Adding an MCP server registers its tool definitions (like mempalace_search, mempalace_add_drawer, etc.) into the system prompt. Every message sent includes a few hundred tokens just describing those available tools to the LLM.

  • Tool Calling Cycles: When Antigravity decides to query MemPalace, it executes an extra model generation turn (Agent: “I will search MemPalace” → MCP Tool Runs → Agent receives result → Agent answers).

In short, for single-turn tasks, having MemPalace will cause a slight increase in token use; however, the longer and more complex a conversation becomes (30+ messages), the more we will start seeing higher reliance on memory and a huge reduction in token use.

If we are working on a project over a period of time, it will be present in memory. Each interaction will not require the agent to learn about it and the things that have already been implemented.

MemPalace will significantly extend my token allowance over time when used correctly.

Good news for current Antigravity IDE users who already have some chats: once MemPalace is integrated, you can always come back to past chats and, with a simple command, “dump” things into memory using a special command. More about this at a later stage.

The Framework

To get started with MemPalace, I will use a 4-step approach with an extra one to bring past chats into memory.

The goal is to give my AI assistant a persistent, self-hosted long-term memory (a “Palace”) across all my projects and repositories without sending private notes to third-party memory services.

  1. Local Homelab Setup

We will deploy MemPalace in Docker on a local server with persistent vector storage and embedding models. We will set things up and verify that at least a local connection to the memory is working on the local network.

  1. Secure Remote Access

Next, we will expose the endpoint via a Cloudflare Tunnel and secure it with Cloudflare Access headers (Client ID & Secret).

Because my server is behind NAT, if I would like to access it – specifically, my MemPalace – in another instance of Agentic Coding, I will need to expose it first.

For this purpose, I will utilise the SSE endpoint over HTTPS through a Cloudflare Tunnel, locked down behind Cloudflare Access using Service Tokens (CF-Access-Client-Id and CF-Access-Client-Secret).

My OpenWrt router at home already has an active Cloudflare Tunnel, so I will use an isolated, secured, and authenticated connection to my MemPalace without exposing my whole server to the internet.

  1. Agent MCP Integration

We will connect Antigravity IDE natively via .agents/mcp_config.json or a global configuration.

With some changes in configuration, we will enable the Agent to access our MemPalace, and with defined Cross-Wing Topic Tunnels, we will allow the agent to search across different repositories and learn from them. Sometimes, something that we have already built somewhere else can simply be reused elsewhere. With knowledge of it, we will make the utilisation of tokens needed for communication much more cost-effective.

  1. Instruction Protocols

We will write system instructions to handle automatic Wing discovery and Room taxonomy.

  1. The “Dump” Command

With a simple command, we will dump some of our past chats into memory, so when we continue to use them, we will effectively save tokens.

The Setup

This guide assumes you already have a working home server running Docker and a management UI like Portainer, so I won’t be covering initial server setup, base Docker configuration, or setting up a Cloudflare Tunnel (which is already described on my website). If you need help with any of these prerequisites, feel free to ask your preferred AI to walk you through them.

Deploying the MemPalace Brain in Docker

Before we can connect our IDE to an AI memory system, we need to build the “brain” and give it a place to live. By hosting MemPalace locally on my own hardware (in my case, I am using an ASUS Chromebox 3 with Ubuntu Server installed), I ensure that my personal notes, code snippets, and deployment secrets never sit on a third-party server.

The Docker Compose Configuration

To get MemPalace running, we are going to deploy it using a docker-compose.yml stack. In Portainer, create a new stack, name it mempalace, and paste the following configuration:

yaml
services:
  mempalace-server:
    image: ghcr.io/mempalace/mempalace:latest
    container_name: mempalace-server
    restart: unless-stopped
    ports:
      - "8888:8888" # Exposing the port for our Cloudflare Tunnel
    # Override the default stdio command to run the SSE HTTP server
    command: ["serve", "--host", "0.0.0.0", "--port", "8888"] 
    volumes:
      # Maps your physical server folder to the container's internal data directory
      - ./mempalace/data:/data
    environment:
      # The embedding model used to "vectorize" your text
      - MODEL_NAME=all-MiniLM-L6-v2
      - LOG_LEVEL=INFO

Breaking Down the Configuration

Let’s look at why we configured it this way:

  • The Official Image: We are using ghcr.io/mempalace/mempalace:latest. This contains everything needed to run the Model Context Protocol (MCP) server without needing a local Python toolchain installed on our host.

  • The Volume Mount (/data): The MemPalace Docker image defaults to storing the palace database, configuration files, and the cached embedding model in the /data directory. By mapping this to /server-config/mempalace/data on my host machine, I ensure my AI’s memory isn’t wiped out if the container restarts or updates.

  • The MODEL_NAME: I am using all-MiniLM-L6-v2. In the world of AI, this is a “Sentence Transformer” model. Its only job is to convert your text notes into a list of numbers (vectors) so the database can perform semantic searches later. It is highly efficient, processing facts in milliseconds on a standard CPU without maxing out your hardware.

Deployment and Verification

Before we deploy our Docker container, let’s create our folders where things will be stored, with the right permissions:

  1. Create the host directory explicitly:
bash
sudo mkdir -p /home/darek/server-config/mempalace/data
  1. Grant ownership to UID 1000 so the container can write to it:
bash
sudo chown -R 1000:1000 /home/darek/server-config/mempalace/data

Of course, you need to adjust your directory path accordingly.

Once we deploy the stack (sudo docker compose up -d), give it a minute to pull the image and start up.

To verify it is working:

  1. Open the container’s logs in Portainer.
  2. We should see a progress bar indicating that onnx.tar.gz (the MiniLM brain) has successfully downloaded.
  3. Finally, we should see a log entry confirming the server is listening on port 8888.

If at any stage you need to update your docker-compose.yml, remember to stop and remove the container first:

bash
sudo docker rm -f mempalace-server

If we did everything correctly, in the logs we should see something like this:

bash
Starting MemPalace remote MCP server
  palace   : /data/.mempalace/palace
  backend  : default
  bind     : 0.0.0.0:8888  (network-exposed)
  tls      : off (plaintext — terminate TLS at a proxy)
  read-only: no
  A new bearer token was generated and stored 0600 at:
    /data/.mempalace/server/ea14d52878fb2dc1c663911a/token
  Store it securely — clients need it to connect:
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Connect a client:
  claude mcp add --transport http mempalace http://YOUR_SERVER_HOST:8888/mcp --header "Authorization: Bearer WsG63kI_joz1eozHomwzrnxeTmej3qlg1ER6zkrnfjU"
  curl http://YOUR_SERVER_HOST:8888/healthz   # liveness (no auth)
MemPalace MCP HTTP server starting...
MemPalace MCP HTTP server bound to non-loopback host 0.0.0.0; /mcp requires the configured bearer token.
MemPalace MCP HTTP server listening on http://0.0.0.0:8888/mcp

At this stage, record your generated bearer token and save it for later.

MemPalace strictly uses “lazy loading” for its models. The model download only triggers on the very first command.

To trigger that download now so our IDE doesn’t encounter a timeout error later, we just need to run a few commands.

Initialize the Palace

First, tell MemPalace to create its internal database structure inside your mapped /data folder.

bash
sudo docker exec -it mempalace-server mempalace init /data

This command creates the necessary files and ensures the configuration directory exists.

When asked Mine this directory now? [Y/n], confirm with Y.

Trigger the Model Download

Now that the database exists, you can run the dummy search. Because it now has a Palace to search inside, it will hit the embedding requirement and immediately start downloading the 80MB all-MiniLM-L6-v2 model:

bash
sudo docker exec -it mempalace-server mempalace search "wake up brain"

A perfectly fine output will be:

bash
/data/.cache/chroma/onnx_models/all-MiniLM-L6-v2/onnx.tar.gz: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 79.3M/79.3M [00:03<00:00, 21.2MiB/s]
No results found for: "wake up brain"

At this stage, our local AI memory database is officially ready and the relevant model downloaded.

Checkpoint – Verifying Local Connectivity

Before we go any further, let’s see if our MemPalace works locally.

The 5-Second Ping Test (Terminal)

Open the terminal on your local computer and run a quick health check against your server’s local IP address:

bash
curl http://192.168.1.239:8888/healthz

If the container is running and port 8888 is open, it will instantly return a simple OK or a status JSON.

In the Portainer logs, you will also see the communication:

text
HTTP 192.168.1.242 - "GET /healthz HTTP/1.1" 200 -
The Local IDE Test (Antigravity)

Now let’s connect our IDE locally. This proves the MCP protocol and the Bearer token are functioning correctly.

In Antigravity IDE, go to the chat panel, select MCP Servers from the three dots at the top, and, ignoring the loaded list, click Manage MCP Servers. If you do not have anything configured there (“No MCP servers installed”), just click View raw config and replace:

json
{
"mcpServers": {}
}

With:

json
{
	"mcpServers": {
		"mempalace-local": {
		"serverUrl": "http://192.168.1.239:8888/mcp",
			"headers": {
			"Authorization": "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
			}
		}
	}
}

Make sure to use your actual server IP and the token you saved from the Docker logs.

The “Hello World” Memory Test

Fully close your Antigravity IDE and reload it again.

In the Portainer logs, you will see Antigravity IDE communicating with our local MemPalace through the MCP protocol:

text
HTTP 192.168.1.242 - "POST /mcp HTTP/1.1" 202 -
HTTP 192.168.1.242 - "POST /mcp HTTP/1.1" 200 -

Open the Antigravity IDE chat section and type the prompt below:

markdown
Using the `#mempalace-local` tools, save this note: 'Local network MCP connection is fully operational' in the room 'infrastructure' under the wing 'test_wing'.

Upon a successful response, you will see:

markdown
Used MCP tool: mempalace-local/mempalace_add_drawer

The note has been successfully saved to Mempalace:

* **Content:** `'Local network MCP connection is fully operational'`
* **Wing:** `test_wing`
* **Room:** `infrastructure`
* **Drawer ID:** `drawer_test_wing_infrastructure_39715aca9c5c52e3384f6bb7`

In the Portainer logs for our Docker container, we will see:

text
Embedding function initialized (model=minilm device=cpu providers=['CPUExecutionProvider'])
Filed drawer: drawer_test_wing_infrastructure_39715aca9c5c52e3384f6bb7 → test_wing/infrastructure
HTTP 192.168.1.242 - "POST /mcp HTTP/1.1" 200 -

Now we are ready for the next step.

If you are happy with just local access to your MemPalace, you may want to skip some of the points below and just do the Instruction Protocols and The “Dump” Command for your existing chats.

Secure Remote Access with Cloudflare Zero Trust

Once our MemPalace is working locally, it’s time to let it be accessed from the internet… securely.

Cloudflare introduced features to manage enterprise environments with dozens of AI agents and MCP servers through its MCP Server Portals under Zero Trust > Access controls.

However, for a personal homelab running a single MemPalace instance, using the dedicated Zero Trust Application + Service Token approach is actually the most robust and universally compatible method. It gives direct, unmediated control over the headers in our IDE. In this article, it is best to teach this fundamental method because it explains how Machine-to-Machine (M2M) authentication actually works.

Assumption: You already have cloudflared running on your network, and it is visible and healthy under Networks > Tunnels & Mesh. You also have your domain’s DNS managed through Cloudflare.

Creating the Tunnel (The Pipe)

  1. Go to Networks > Tunnels & Mesh and click on your tunnel name.
  2. Go to Published application routes from the top menu.
OverviewCIDR routesHostname routesPublished application routesLive logs
  1. Click the blue button + Add a published application route.
  2. Configure the routing – as in the example below:
  • Subdomain: mempalace
  • Domain: (select preferred domain from the list of your domains)
  • Service
    • Type: HTTP
    • URL: (our local server address, like: 192.168.0.1:8888)

Our server on our local network is accessible over the unencrypted HTTP protocol, yet our tunnel will add HTTPS to it along the way.

Click Save for now. Cloudflare will automatically create the DNS record for you.

At this point, our MemPalace is on the internet, but it is completely unprotected. Anyone who guesses mempalace.yourdomain.com can access it. Let’s lock it down.

Forging the Service Token (The Machine Key)

Because your IDE (like Antigravity) operates in the background, it cannot open a web browser to click a “Login” button. It needs programmatic access. We achieve this using Service Tokens. We must create this before we build our security shield.

  1. Go to Access controls > Service credentials.
  2. Click the + Create service token button:
  • Name: MemPalace
  • Service Token Duration: Non-expiring
  1. Click the Generate token button.

You will be presented with Service token details. You must copy the Header and client secret and store them in a safe place, as these will be displayed only once.

Copy your CF-Access-Client-Id as well, as you will need it later:

text
CF-Access-Client-Id: your-client-id-here.access
CF-Access-Client-Secret: your-client-secret-here
  1. Confirm by clicking the Done button.

The Zero Trust Application (The Shield)

We need to put a “bouncer” in front of our subdomain.

  1. In the Zero Trust dashboard, navigate to Access controls > Applications.
  2. Click + Create new application and choose Self-hosted and private.
  • From the options, select Public DNS and click Continue with self-hosted and private.
Private destinationsWorkersPublic DNSService auth
  1. Let’s fill in the configuration:
  • Destinations
    • Subdomain: mempalace
    • Domain: (as selected previously)
  • Access policies – click the Create new policy button.
    • Policy rules
      • Selector is: Service token
      • Below, select your MemPalace token created earlier.
  • Policy details
    • Policy Name: MemPalace Service Token Auth
    • Action: Service Auth
    • Policy session duration: Same as application session duration
  1. Confirm by clicking the Save policy button.
  2. In the Preview section, confirm that all is as below:
  • Sources: Services
  • Policies: MemPalace Service Token Auth
  • Destination: mempalace.example.com (your domain selected earlier)
  1. In Details, fill in:
  • Name: MemPalace Server
  • Session Duration: 24 hours
  1. Confirm by clicking the Save button.

Enforce Access JSON Web Token (JWT) validation

  1. Go back to Networks > Tunnels & Mesh and click on your tunnel.
  2. Go to Published application routes, click on the route created earlier, and follow with the Edit button.
  3. Scroll to the bottom and open the section called Origin request and connection settings.
  4. Open the Access section and enable Enforce Access JSON Web Token (JWT) validation.
  5. From the dropdown box, select your MemPalace Server and click Save.

This addition adds additional security that binds our Tunnel directly to our Access application, ensuring that nobody can bypass our “bouncer” by discovering your tunnel’s internal routing.

Checkpoint – Verifying Remote Connectivity

Before we wire this up to our IDE, let’s prove that our Cloudflare “bouncer” is doing its job, and that our Service Token is the VIP pass that gets us through.

Test the Bouncer (The Failure Test)

First, try to access your remote server without any credentials. Run this in your terminal:

bash
curl -I https://mempalace.yourdomain.com/healthz

(Note: The -I flag tells curl to fetch only the HTTP headers).

Expected Result: You should see an HTTP/2 302 redirect or an HTTP/2 403 Forbidden pointing to a Cloudflare Access login page. This proves your server is no longer exposed to the public internet!

Test the VIP Pass (The Success Test)

Now, let’s present our Service Token headers to bypass the bouncer. You will need the Client ID (with .access) and Client Secret you saved during Phase 2.

Run this command, replacing the placeholders with your actual domain and Cloudflare credentials:

bash
curl -i https://mempalace.yourdomain.com/healthz \
  -H "CF-Access-Client-Id: your-client-id-here.access" \
  -H "CF-Access-Client-Secret: your-client-secret-here"

Expected Result: If everything is configured correctly, Cloudflare will read those headers, validate the JWT, let the request through the tunnel, and MemPalace will respond with: HTTP/2 200 OK

If you get that 200 OK, our remote architecture is flawless! You have successfully tunneled into your home network securely.

You will also see in the Docker logs a response coming directly from your router (as the request goes through the internet).

IDE & MCP Integration (Connecting the Brain)

At this stage, we have built a dual-layer security model for our MemPalace and IDE communication:

  • The Cloudflare Headers (CF-Access-Client-*): The ID card to get past the “bouncer” at the front door of your network.
  • The Bearer Token (Authorization): The key to open the actual safe (MemPalace) once you are inside.

MemPalace itself has no idea that Cloudflare exists. If Cloudflare lets the traffic through, MemPalace will still reject it with a 401 Unauthorized status if that Bearer token isn’t attached to the request.


Now that our MemPalace server is securely exposed to the internet, we need to teach our IDE how to talk to it. Just a reminder that in this guide, we are using Antigravity IDE, which has native, first-class support for the Model Context Protocol (MCP). Standard VS Code with GitHub Copilot integration can also utilise MCP and MemPalace—I tried it, but you need a paid plan to use it effectively. On the Copilot Free plan, you will quickly exhaust your token allowance before MemPalace is actively used.

The Dual-Layer Security Concept

To connect successfully, we have to pass two different layers of security simultaneously:

  1. The Perimeter Shield: Cloudflare needs our Client ID and Client Secret to let the traffic into our home network.
  2. The Application Lock: MemPalace needs the Bearer Token (generated at the beginning of setting up MemPalace in Docker) to grant access to the database.

Antigravity IDE allows us to pass all of these “keys” natively using standard HTTP headers.

Configuring Antigravity IDE

Once again, in Antigravity IDE, go to the chat panel, select MCP Servers from the three dots at the top, and, ignoring the loaded list, click Manage MCP Servers. If you do not have anything configured there (“No MCP servers installed”), just click View raw config and paste the following:

json
{
  "mcpServers": {
    "mempalace-remote": {
      "serverUrl": "https://mempalace.yourdomain.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_MEMPALACE_BEARER_TOKEN",
        "CF-Access-Client-Id": "YOUR_CLOUDFLARE_CLIENT_ID.access",
        "CF-Access-Client-Secret": "YOUR_CLOUDFLARE_CLIENT_SECRET"
      }
    }
  }
}

Replace your domain in serverUrl and fill in your Bearer and CF-Access values. Save the file and fully close Antigravity IDE.

Reopen Antigravity and look at the chat panel. If you do not see any MCP error messages, everything has most likely gone well. To verify, check your Docker logs when you launch Antigravity IDE. The logs should show something like this:

text
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 200 -
HTTP 192.168.1.1 - code 404, message Not Found
HTTP 192.168.1.1 - "GET /mcp HTTP/1.1" 404 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 202 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 200 -
HTTP 192.168.1.1 - code 501, message Unsupported method ('DELETE')
HTTP 192.168.1.1 - "DELETE /mcp HTTP/1.1" 501 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 200 -
HTTP 192.168.1.1 - code 404, message Not Found
HTTP 192.168.1.1 - "GET /mcp HTTP/1.1" 404 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 200 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 202 -
HTTP 192.168.1.1 - code 404, message Not Found
HTTP 192.168.1.1 - "GET /mcp HTTP/1.1" 404 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 202 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 200 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 200 -
HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 202 -

This confirms communication with MemPalace through the Cloudflare infrastructure. The IP address 192.168.1.1 is your router’s local IP, showing that the request originated from the internet and that communication with your MemPalace instance was initiated by the router itself.

Instruction Protocols & Taxonomy (Organising the Brain)

Now that our IDE is securely connected to our MemPalace database, we need to teach the AI how to use it. If we don’t set ground rules, the AI will just dump everything into a giant, disorganised pile.

To prevent chaos, MemPalace uses a specific 3-tier organisational structure. We need to explain this structure to our AI agent and give it rules on how to navigate it dynamically.

The Core Taxonomy Hierarchy

Think of MemPalace exactly as the name implies—a physical building. We organise knowledge into three levels:

  • Wings (Projects / Repositories): A Wing represents an isolated project workspace (e.g., my-website, home-server-config). Keeping projects in separate Wings ensures the AI doesn’t mix up the deployment steps for your blog with the routing rules for your home network.
  • Rooms (Topics / Categories): Rooms represent standard subject areas inside a Wing. Common rooms include infrastructure, deployment, debugging, or architecture.
  • Drawers (Individual Notes): Drawers are the actual, atomic pieces of knowledge saved inside a specific Room.

Dynamic Wing Auto-Detection

If you work across dozens of projects, you don’t want to manually tell the AI which Wing you are in every time you open a chat. Instead, we use a smart detection system:

  • The Primary Method: Inside the root folder of any project, create a file named mempalace_wing.txt containing the name of the project. The AI will read this file to identify its current Wing.

  • The Failsafe: If you forget to create this file, the AI will act intelligently: it will automatically check the name of the folder currently open in your IDE and use that as the Wing name. This guarantees your memories are always filed away cleanly.

AI-Driven Room Categorisation & Cross-Wing Tunnels

You should not have to memorise your Room names or tell the AI where to put things. Humans forget; AI does not. We are going to instruct the AI to act as an automated librarian. Based on the context of your conversation, the AI will automatically determine which standard “Room” your note belongs in.

Why do we want standard rooms? Because of Cross-Wing Topic Tunnels.

If you solve a CSS issue in the my-website project and later ask the AI for CSS help while working in friend-website, the AI can search the infrastructure room globally (leaving the Wing parameter empty). This acts as a tunnel, allowing the AI to pull your past solutions from entirely different projects.

Agent Rules & Protocols (The Instructions)

Before moving forward, let’s break down the Antigravity IDE configuration:

  • Global Rules (~/.gemini/GEMINI.md): This is the agent’s global “brain”. Anything written here applies to every single project you ever open. If you want MemPalace to be your universal memory system across all repos, this is where it goes.
  • Workspace Rules (.agents/rules/ directory): This is the modern replacement for .geminirules. These rules apply only to the specific repository you currently have open.
  • Skills (~/.gemini/config/skills/): Skills are on-demand, specialised scripts or templates that the AI loads only when triggered. Because our MemPalace instructions dictate behaviour and taxonomy (how to categorise things and when to search), they belong in a Rule, not a Skill.

For MemPalace, since we are building Cross-Wing Tunnels that span multiple projects, the best place to put this is in the Global Rules.


To make all of this automatic, we need to give Antigravity IDE its marching orders. Because we want MemPalace to act as our universal brain across all our projects, we are going to add these instructions as a Global Rule.

A Global Rule acts as the AI’s permanent subconscious—it will automatically evaluate your conversations and save or search MemPalace in the background without you ever having to ask.

Because Antigravity applies Global Rules across every project you open, we simply need to edit the master configuration file on your computer.

  1. In Antigravity IDE, press Cmd+P (Mac) or Ctrl+P (Windows) to open the file finder.
  2. Type ~/.gemini/GEMINI.md and press Enter to open your global rules file. (If it doesn’t exist, simply open your terminal, run touch ~/.gemini/GEMINI.md, and then open it in the IDE).
  3. Add the following YAML frontmatter and rules to the file:
markdown
# MemPalace Integration Rules

You are connected to a long-term memory system called MemPalace. You must use it to recall past decisions and store new, important context automatically.

## Wing & Room Taxonomy
- **Wing Auto-Detection:** Always determine your current "Wing" before saving or searching. Look for a `mempalace_wing.txt` file in the current active folder. Its contents represent the Wing name. 
- **The Failsafe:** If no `mempalace_wing.txt` is found, do NOT leave the Wing empty. Fall back to using the exact name of the current root workspace folder (or active subfolder) as the Wing name.
- **Multi-Repo Workspaces:** If operating in a parent folder with multiple projects (e.g., a GitHub directory), use the user's active chat context to determine which specific subfolder we are working in, and apply the Wing detection/failsafe rules to that specific subfolder.
- **Room Auto-Categorization:** Do NOT rely on the user to specify a Room name. Act as an automated librarian. Based on the context of the chat, automatically categorize the memory into one of these standard predefined rooms: `infrastructure`, `deployment`, `architecture`, `debugging`, `database`, or `general`.

## Autonomous Operating Protocols (No User Prompting Required)
1. **Search Before Acting:** Before making architectural decisions, writing deployment scripts, or answering complex questions, automatically use the MemPalace search tool to check for existing patterns in the current Wing and Room. 
2. **Cross-Wing Tunnels:** If you cannot find the answer in the current project's Wing, perform a global search by leaving the `wing` parameter EMPTY. This creates a Cross-Wing Topic Tunnel, allowing you to draw on standardized Rooms (like `infrastructure`) from my other projects.
3. **Save Outcomes Proactively:** Do not wait for the user to say "save this." When an architectural decision is finalized, a complex bug is solved, or a new pattern is established, automatically summarize the technical decision and save it to the correct Wing and inferred Room.

If you already have global rules set up for other tasks, do not delete them! Because Antigravity treats this entire file as its global system prompt, you can simply scroll to the very bottom of your existing text and paste the MemPalace rules directly underneath.


That’s it. You are done.

Antigravity IDE will load this into its system prompt for every project you ever open. You never have to type any command, you never have to specify a room, and you never have to explicitly say “save this to MemPalace”. The AI will simply act as your silent librarian in the background.

However…

Not everybody likes having Global Rules applied all the time; some prefer to use MemPalace only when they decide to.

The Manual Opt-In Workflow

If the idea of an AI silently saving your code in the background feels a bit too intrusive, you can opt for a manual approach instead.

By creating a Workflow rather than a Global Rule, the AI will only act as your MemPalace librarian when you explicitly ask it to. This gives you 100% control over when memories are saved or searched.

Here is how to set up the manual workflow:

  1. Open Antigravity IDE and navigate to your Agent Chat panel.
  2. Click the three dots (...) at the top of the chat panel.
  3. Select Customisations and open the Workflows tab.
  4. Click the + Global button.
  5. When prompted for a name, type mempalace-integration-rules and press Enter.

Antigravity will open a new file.

Delete everything inside it and replace it entirely with the following code:

markdown
---
description: Manually invoke MemPalace memory rules, taxonomy auto-categorization, and cross-wing search protocols.
---
# MemPalace Integration Rules

You are connected to a long-term memory system called MemPalace. For the duration of this request, act as an automated librarian.

## Wing & Room Taxonomy
- **Wing Auto-Detection:** Look for a `mempalace_wing.txt` file in the current active folder. Its contents represent the Wing name. 
- **The Failsafe:** If no `mempalace_wing.txt` is found, do NOT leave the Wing empty. Fall back to using the exact name of the current root workspace folder (or active subfolder).
- **Room Auto-Categorization:** Do NOT ask the user for a Room name. Based on the context of our chat today, automatically categorize the memory into one of these standard predefined rooms: `infrastructure`, `deployment`, `architecture`, `debugging`, `database`, or `general`.

## Operating Protocols
1. **Search First:** If I ask you a technical question, use the MemPalace search tool to check for existing patterns in the current Wing and Room before answering.
2. **Cross-Wing Tunnels:** If you cannot find the answer locally, perform a global search by leaving the `wing` parameter EMPTY to pull from my other projects.
3. **Save Outcomes:** Summarize the technical decisions, code patterns, and solutions from our current conversation concisely, and save them to the correct Wing and inferred Room.

How to use it: Because this is a workflow, it sits quietly in the background until you need it:

  • When you finish a complex debugging session and want to document the fix, simply open the chat and type: /mempalace-integration-rules Please save the solution we just figured out.
  • Or, if you want the AI to search your past projects before answering a new question, start your prompt with: /mempalace-integration-rules How did I configure CSS last time?

You have the choice of how you want to integrate it: either the “Set it and forget it” Global Rule or the “Call it when I need it” Workflow.

Testing Your Automated Librarian

We have built the database, secured the tunnel, and programmed the AI’s subconscious. Let’s prove it works.

The Live Test

  1. Create a test folder, create a file named mempalace_wing.txt inside it, and type a test name inside (e.g., test-project).

  2. Open a brand new chat in Antigravity IDE.

  3. Type something like this:

    “I’ve decided we are going to use PostgreSQL for our database, and we’ll connect to it using Prisma ORM. Let’s move forward.”

Watch what happens. You didn’t ask it to save anything. You didn’t tell it a Wing. You didn’t specify a Room. But because of your Global Rules, the AI should automatically pause, trigger the mempalace_add_drawer tool, and save a summary.

Check the tool output.

Antigravity should do this completely on its own, without you asking:

  1. Read the room: Autonomously triggered Listed directory and Viewed mempalace_wing.txt to figure out where it was. It successfully read test-project.
  2. Used the tools: Autonomously called mempalace_add_drawer to store your architectural decision. (It also looks like your MemPalace MCP server has a diary_write tool, and the AI was so eager it decided to log its thoughts there too!)
  3. The Shield worked: My Docker logs show HTTP 192.168.1.1 - "POST /mcp HTTP/1.1" 200 -. The 200 status code means the traffic successfully passed through the Cloudflare Zero Trust authentication, hit your tunnel, and wrote directly to your local database.
  4. Kept working: After saving the memory to the test-project wing in the background, it still came back and answered your prompt by drafting the Prisma implementation plan.

This proves our Zero-Friction Automation is working flawlessly. We have just built a personalised, cross-project, long-term memory system that operates entirely in the background.

After a successful test, to clean up our MemPalace database from the test project, we can issue this command:

markdown
Please find all memories and diary entries in the test-project wing and delete them.

Bonus: “The Dump Command” (Archiving Past Chats)

What about all the brilliant problem-solving you did before you installed MemPalace?

You likely have several old chats filled with valuable configurations and decisions. You don’t want to lose them, but copy-pasting them manually would take hours.

You can use the Dump Command to have the AI retroactively read an old chat and file it away.

The Wing Concern: How does the AI know which Wing to use for an old chat? Because our global rules are always active, the AI will still try to read the folder you currently have open. However, old chats are heavily context-loaded. To prevent the AI from getting confused, the best practice is to explicitly state the Wing in your Dump Command just to be safe.

Open an old, valuable chat in your IDE and send this exact prompt:

The Dump Command: “Review this entire chat history. Extract all the final, working architectural decisions, configuration files, and solved bugs. Summarise them concisely and save them to MemPalace. Follow our standard Room taxonomy. For safety, force the Wing name to be: [Insert Wing Name Here].”

The AI will scan the entire history of that conversation, break it down into logical topics, and automatically sort them into the correct Rooms (like infrastructure or debugging) inside your specified Wing. It acts as an automated archivist, turning weeks of messy chat logs into organised, permanent knowledge!


Now, go to your projects and create mempalace_wing.txt files with your wing names, especially in the ones you have already worked on in Antigravity.

Congratulations – you have just cured your AI’s amnesia. By combining a locally hosted MemPalace, impenetrable Cloudflare Zero Trust tunnels, and Antigravity’s global rules, you haven’t just configured an IDE. You have built a completely private, globally accessible second brain that learns every time you code, never forgets a bug fix, and travels with you anywhere in the world.

The AI landscape moves at breakneck speed, and viral projects will come and go. But by building this yourself, you aren’t just installing a tool – you are mastering the Model Context Protocol, securing local Docker deployments with Cloudflare Zero Trust, and taking complete ownership of your AI infrastructure. No matter what memory tool comes next, your homelab is ready for it.

Post Scriptum: The Reality of Working with LLMs

After implementing all of the above and using this setup for a while, you might notice something: when you send a new prompt, you can clearly se (in Docker logs) the AI communicating with MemPalace to search for context before replying. But sometimes, at the end of a long coding session or after finally solving a complex issue, you might not see it automatically save the outcome to memory.

Why does this happen, and is the automation actually working?

First, this is actually by design. In our Global Rules, we instructed the AI to save when an architectural decision is “finalized” or a bug is “solved.” If the AI saved every single step of your brainstorming or every broken iteration of your code, your vector database would quickly fill up with useless noise. It purposefully waits for a definitive conclusion.

However, at the end of the day, an LLM is still just an LLM.

During a long, complex chat, the agent can get “tunnel vision.” It becomes so hyper-focused on solving the problem and delivering the final working code to you that it simply “forgets” to trigger the mempalace_add_drawer tool in that same turn.

If you notice the AI hasn’t automatically archived a brilliant solution you just reached, you don’t need to write a complex command or manually specify your Wing and Room again. You just need to give it a gentle nudge to signal that the task is complete.

Simple, natural conversational phrases work perfectly:

  • “That’s all for now, send our approach/solution to MemPalace.”
  • “Great, this works perfectly. Document it.”
  • “Good job, let’s save these finalized findings to memory.”

This light push immediately reminds the agent of its “Save Outcomes Proactively” rule. Because it already has the entire context of the conversation and knows its Wing from your background rules, it will seamlessly trigger the save tool and categorize it correctly.

Zero-friction automation is incredible, but sometimes, as the lead developer, you just have to remind your automated librarian that the meeting is over and it’s time to file the notes!

Share on Threads
Share on Bluesky
Share on Linkedin
Share via WhatsApp
Share via Email
Share on Mastodon

Comments & Reactions

Categories