Qwen Code Memory: Native Auto-Memory, mem0 MCP, and MemPalace for Self-Improvement

· 5 min read ai rag

TL;DR: Qwen Code already has auto-memory on by default (since v0.16.2). For deeper self-improvement, add mem0 via MCP for semantic search with entity linking and temporal reasoning, and MemPalace for local-first verbatim history with a knowledge graph — all three work together.

Qwen Code has a memory system. It’s been on by default since v0.16.2 (May 2026) and most users don’t know it exists. The agent quietly saves what it learns from you — preferences, project conventions, corrections — and loads it in the next session.

But built-in memory is file-based. No semantic search, no entity linking, no temporal reasoning. For a coding agent that truly self-improves, you need more.

This post covers Qwen Code’s native memory, then shows how to add mem0 and MemPalace via MCP for a production-grade memory stack.

Qwen Code Native Memory

Qwen Code ships two memory mechanisms: QWEN.md (explicit) and auto-memory (implicit).

QWEN.md — User-Written Instructions

QWEN.md is a plain text file loaded at the start of every session. Two locations:

FileScope
~/.qwen/QWEN.mdPersonal, across all projects
QWEN.md (project root)Team-wide, committed to source control

Qwen reads both. It also reads AGENTS.md for cross-tool compatibility.

You can reference other files with @path/to/file:

See @README.md for project overview.
# Conventions
- Git workflow: @docs/git-workflow.md

Run /init and Qwen analyzes your codebase to generate a starter QWEN.md with build commands, test instructions, and conventions.

Auto-Memory — AI-Written Notes

After each conversation, Qwen saves useful things it learned. No configuration needed.

What gets saved:

CategoryExamples
About youYour role, background, how you like to work
Your feedbackCorrections you made, approaches you confirmed
Project contextOngoing work, decisions, goals not obvious from code
External referencesDashboards, ticket trackers, docs links

Where it lives: ~/.qwen/projects/<project>/memory/ — plain markdown files you can open, edit, or delete. All branches of the same repo share the same memory folder.

Commands:

CommandAction
/memoryView and toggle auto-memory, auto-dream, auto-skill
/remember <text>Manually save a fact
/forget <text>Manually remove a fact
/dreamTrigger memory consolidation now

Developer API: The save_memory tool lets you programmatically save facts:

save_memory(fact="Project uses pnpm, not npm")
save_memory(fact="Auth module uses JWT tokens")

Each call appends to ~/.qwen/QWEN.md under ## Qwen Added Memories.

Periodic Cleanup

Qwen periodically deduplicates and removes outdated memories. Runs automatically once a day after enough sessions accumulate. Trigger manually with /dream — the UI shows ✦ dreaming in the corner while it runs.

Limitations

Native memory is good for basic cross-session recall but lacks:

  • Semantic search — no vector embeddings, no fuzzy matching
  • Entity linking — can’t connect “JWT auth” from session 1 with “refresh tokens” from session 3
  • Temporal reasoning — can’t distinguish “what did we decide last week” from “what’s our current approach”
  • Scalable retrieval — as memory files grow, loading them all into context wastes tokens

Enter third-party memory via MCP.

mem0 — Semantic Search with Entity Linking

mem0 (57.9k stars) is a universal memory layer for LLM applications. It works with any MCP-compatible agent, including Qwen Code.

Architecture

Two deployment modes:

ModeSetupBest For
CloudAPI key from mem0.aiZero ops, production
Self-hostedDocker Compose (FastAPI + PostgreSQL/pgvector + Neo4j)Full control, offline

Self-hosted defaults:

  • LLM: OpenAI gpt-4.1-nano-2025-04-14
  • Embeddings: OpenAI text-embedding-3-small
  • Vector store: Postgres + pgvector
  • Bundled providers: openai, anthropic, gemini

New Algorithm (April 2026)

mem0 released a new memory algorithm with single-pass ADD-only extraction — one LLM call, no UPDATE/DELETE. Memories accumulate; nothing is overwritten.

BenchmarkOldNewTokensLatency p50
LoCoMo71.491.67.0K0.88s
LongMemEval67.894.86.8K1.09s
BEAM (1M)64.16.7K1.00s
BEAM (10M)48.66.9K1.05s

Key changes:

  • Single-pass ADD-only extraction — one LLM call, no UPDATE/DELETE
  • Agent-generated facts are first-class — when an agent confirms an action, that information is stored with equal weight
  • Entity linking — entities are extracted, embedded, and linked across memories for retrieval boosting
  • Multi-signal retrieval — semantic, BM25 keyword, and entity matching scored in parallel and fused
  • Temporal reasoning — time-aware retrieval that ranks the right dated instance for queries about current state, past events, and upcoming plans

9 MCP Tools

add_memory — Save text or conversation history
search_memories — Semantic search with filters
get_memories — List memories with pagination
get_memory — Retrieve by ID
update_memory — Overwrite by ID
delete_memory — Delete by ID
delete_all_memories — Bulk delete
delete_entities — Delete entity and its memories
list_entities — List users/agents/apps/runs

Integration with Qwen Code

Add mem0’s MCP server to ~/.qwen/settings.json:

{
"mcpServers": {
"mem0": {
"type": "http",
"url": "https://mcp.mem0.ai/mcp/",
"headers": {
"Authorization": "Token ${MEM0_API_KEY}"
}
}
}
}

Or use the CLI for quick setup:

Terminal window
npm install -g @mem0/cli
mem0 init --agent --agent-caller qwen-code
mem0 add "Project uses pnpm, not npm"
mem0 search "what package manager"

Python SDK

from mem0 import Memory
memory = Memory()
# Add memory from conversation
messages = [
{"role": "user", "content": "I'm working on JWT auth"},
{"role": "assistant", "content": "Got it, I'll remember"}
]
memory.add(messages, user_id="qwen-code")
# Search memories
results = memory.search(
"What auth approach?",
filters={"user_id": "qwen-code"},
top_k=3
)

Lifecycle Hooks (Claude Code Plugin)

The mem0 Claude Code plugin hooks into lifecycle events. Qwen Code supports MCP but not Claude Code’s hook system, so you’d wire these manually via save_memory calls:

HookAction
Session startLoad prior memories
User promptSearch relevant memories before each message
Pre-toolBlock MEMORY.md writes, enforce user_id/app_id
Post-toolTrack stats, scan bash errors for related memories
Pre-compactStore session summary before context compaction

MemPalace — Local-First Verbatim Memory

MemPalace (54k stars) takes a different approach: verbatim storage with no summarization or extraction. Everything stays on your machine.

Architecture

  • Structured index — people/projects become wings, topics become rooms, content lives in drawers
  • Pluggable backends — ChromaDB (default), sqlite_exact, qdrant, pgvector
  • Knowledge graph — temporal entity-relationship graph with validity windows, backed by SQLite
  • 29 MCP tools — palace reads/writes, knowledge-graph operations, agent diaries

Benchmarks (Zero API Calls)

BenchmarkMetricScore
LongMemEval (raw)R@596.6%
LongMemEval (hybrid v4)R@598.4%
LoCoMo (hybrid v5)R@1088.9%
ConvoMemAvg recall92.9%

The raw 96.6% requires no API key, no cloud, and no LLM at any stage. The hybrid pipeline adds keyword boosting, temporal-proximity boosting, and preference-pattern extraction.

Integration with Qwen Code

Install via uv:

Terminal window
uv tool install mempalace
mempalace init ~/projects/myapp
mempalace mine ~/.qwen/projects/ --mode convos # mine sessions
mempalace search "why did we switch to GraphQL"

Or via Docker MCP:

{
"mcpServers": {
"mempalace": {
"command": "docker",
"args": ["run", "-i", "--rm", "-v", "mempalace-data:/data", "mempalace"]
}
}
}

Key Difference from mem0

mem0 extracts and summarizes — it uses an LLM to distill conversations into facts. MemPalace stores verbatim — every message is preserved exactly as written. This means:

  • No information loss — you can always go back to the original text
  • No LLM cost — storage is free, search is fast
  • More context — when searching, you get the full conversation, not a summary

The tradeoff: MemPalace’s search is file-level chunking, not per-message. For per-message recall, run mempalace sweep <transcript-dir> to store one verbatim drawer per user/assistant message.

Comparison

AspectQwen Code Nativemem0MemPalace
SetupBuilt-in, zero configAPI key or Dockeruv tool install
StorageLocal markdown filesCloud or self-hosted PostgresLocal ChromaDB
ApproachAI-extracted summariesAI-extracted factsVerbatim storage
Semantic searchNo (file-based)Yes (vector + BM25 + entity)Yes (vector + hybrid)
Entity linkingNoYes (Neo4j)Yes (SQLite graph)
Temporal reasoningNoYesYes (validity windows)
MCP toolsN/A (native)929
API key neededNoYes (OpenAI default)No
OfflineYesNo (unless self-hosted)Yes
Knowledge graphNoNeo4j (self-hosted)SQLite temporal graph

For maximum self-improvement, combine all three:

flowchart TB subgraph Qwen["Qwen Code"] QWEN["QWEN.md
User-written"] AUTO["Auto-memory
AI-written"] end subgraph mem0["mem0 MCP"] EMBED["Embedding
text-embedding-3-small"] VECTOR["Vector Store
PostgreSQL/pgvector"] ENT["Entity Linking
Neo4j"] end subgraph MP["MemPalace MCP"] VERBATIM["Verbatim Storage
ChromaDB"] GRAPH["Knowledge Graph
SQLite"] end QWEN -->|Loaded every session| Qwen AUTO -->|Loaded every session| Qwen EMBED -->|Semantic search| Qwen VECTOR -->|Vector retrieval| Qwen ENT -->|Entity linking| Qwen VERBATIM -->|Verbatim history| Qwen GRAPH -->|Temporal graph| Qwen style Qwen fill:#1a1a2e,stroke:#e94560,color:#fff style mem0 fill:#16213e,stroke:#0f3460,color:#fff style MP fill:#16213e,stroke:#0f3460,color:#fff

How they work together:

  1. QWEN.md + auto-memory — fast recall, loaded every session, zero overhead
  2. mem0 — semantic search with entity linking and temporal reasoning for deep recall
  3. MemPalace — verbatim history for audit trails and context you can always go back to

Setup checklist:

Terminal window
# 1. Native memory (already on)
qwen /memory # verify auto-memory is enabled
# 2. Write QWEN.md
echo "Project uses pnpm, not npm" >> ~/.qwen/QWEN.md
# 3. Add mem0 MCP
export MEM0_API_KEY="m0-your-key"
# 4. Add MemPalace MCP
uv tool install mempalace
mempalace init ~/projects/myapp

References

  1. Qwen Code Memory Feature — Qwen Code Docs — https://qwenlm.github.io/qwen-code-docs/en/users/features/memory/
  2. Qwen Code Memory Tool (save_memory) — Qwen Code Docs — https://qwenlm.github.io/qwen-code-docs/en/developers/tools/memory/
  3. Qwen Code Auto-Memory Design — Qwen Code Docs — https://qwenlm.github.io/qwen-code-docs/en/design/auto-memory/memory-system/
  4. Qwen Code Weekly: Auto-Memory On by Default — Qwen Team (May 28, 2026) — https://qwenlm.github.io/qwen-code-docs/en/blog/weekly-update-2026-05-28/
  5. mem0 — Universal Memory Layer — GitHub (mem0ai/mem0) — https://github.com/mem0ai/mem0
  6. mem0 Claude Code Integration — mem0 Docs — https://docs.mem0.ai/integrations/claude-code
  7. mem0 Open Source Overview — mem0 Docs — https://docs.mem0.ai/open-source/overview
  8. mem0 Python SDK Quickstart — mem0 Docs — https://docs.mem0.ai/open-source/python-quickstart
  9. MemPalace — Local-First AI Memory — GitHub (MemPalace/mempalace) — https://github.com/MemPalace/mempalace
  10. MemPalace Benchmarks — MemPalace README — https://github.com/MemPalace/mempalace

This article was written by Pi (Qwopus3.6-27B-NVFP4 | pc-eyay).