forget-me-not-mcp 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -8
- package/dist/db.js +18 -0
- package/dist/embedder.js +59 -0
- package/dist/index.js +19 -1
- package/dist/semantic.js +200 -0
- package/dist/server.js +27 -9
- package/dist/store.js +24 -4
- package/package.json +9 -3
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# forget-me-not-mcp
|
|
2
2
|
|
|
3
|
-
A local MCP server that gives Claude Code a memory across sessions. Claude can save decisions, non-obvious error fixes, project facts and your preferences, then find them again in later sessions with
|
|
3
|
+
A local MCP server that gives Claude Code a memory across sessions. Claude can save decisions, non-obvious error fixes, project facts and your preferences, then find them again in later sessions. Search combines keywords (exact error codes, names) with meaning, so "where is the backend hosted" finds "We deploy the API to Azure Container Apps".
|
|
4
4
|
|
|
5
|
-
Everything is kept in one SQLite file on your machine.
|
|
5
|
+
Everything is kept in one SQLite file on your machine. The embedding model runs inside the server, so there's no Ollama, no API key and no cloud service, and your memories never leave your computer.
|
|
6
6
|
|
|
7
7
|
## Requirements
|
|
8
8
|
|
|
@@ -77,7 +77,7 @@ When the server is on only in some projects, put the usage rules in each of thos
|
|
|
77
77
|
| Tool | Purpose |
|
|
78
78
|
| --- | --- |
|
|
79
79
|
| `remember` | Save a memory (`content`, `type`, optional `project`, `tags`, `pinned`) |
|
|
80
|
-
| `search` |
|
|
80
|
+
| `search` | Hybrid keyword + semantic search over active memories, best match first. Filters: `project`, `type`, `include_global`, `limit` |
|
|
81
81
|
| `get_context` | Pinned and most recent memories for a project (plus global ones), for the start of a session |
|
|
82
82
|
| `update_memory` | Edit content, tags, type or pinning in place |
|
|
83
83
|
| `supersede` | Replace a memory with a new one. The old one is hidden from search but kept |
|
|
@@ -85,9 +85,32 @@ When the server is on only in some projects, put the usage rules in each of thos
|
|
|
85
85
|
| `history` | Show the earlier versions a memory replaced |
|
|
86
86
|
| `link` / `related` | Record relations between named things (`api` uses `postgres`) and list them |
|
|
87
87
|
| `export` | Write all active memories to a Markdown file and return its path |
|
|
88
|
+
| `status` | Server version, memory counts, and whether semantic search is ready |
|
|
88
89
|
|
|
89
90
|
Memory types are `decision`, `fact`, `error_fix`, `preference` and `note`. A memory saved without a project is global and shows up in every project's search and context.
|
|
90
91
|
|
|
92
|
+
## Semantic search
|
|
93
|
+
|
|
94
|
+
Each memory is turned into a 768-number vector by [nomic-embed-text-v1.5](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5), run in-process by [Transformers.js](https://huggingface.co/docs/transformers.js) on ONNX Runtime. The vectors are stored in the same SQLite file.
|
|
95
|
+
|
|
96
|
+
A search runs two retrievers and merges their rankings (reciprocal rank fusion):
|
|
97
|
+
|
|
98
|
+
- **Keyword** (SQLite FTS5, BM25) is best for exact terms: `SQLITE_BUSY`, file names, library names.
|
|
99
|
+
- **Semantic** (cosine similarity) is best for reworded questions: "how are bills created" finds "Customer invoices are generated nightly".
|
|
100
|
+
|
|
101
|
+
Each result has a `match` field (`keyword`, `semantic` or `both`) and, for semantic matches, a `similarity` score. Semantic matches below 0.45 similarity are dropped, so an unrelated question returns nothing rather than the nearest unrelated memory.
|
|
102
|
+
|
|
103
|
+
**What to expect:**
|
|
104
|
+
|
|
105
|
+
- **First run:** the model (about 130 MB) is downloaded from Hugging Face into `~/.claude/memory/models`. After that it works offline. The server answers immediately during the download; search is keyword-only until the model is ready.
|
|
106
|
+
- **Speed:** loading from cache takes under a second, and a search takes about 10 ms.
|
|
107
|
+
- **Memory use:** about 400 MB of RAM per running server with the model loaded, against about 70 MB keyword-only. Each open Claude Code session runs its own server.
|
|
108
|
+
- **Install size:** Transformers.js and ONNX Runtime add roughly 450 MB to the install, because they include binaries for every platform. They are optional dependencies: if they fail to install, the server still runs keyword-only.
|
|
109
|
+
- **Existing memories** are embedded automatically in the background. Edited memories are re-embedded.
|
|
110
|
+
- **No model available** (offline first run, or an unsupported platform): search falls back to keyword-only and `status` shows the reason. It retries every 5 minutes.
|
|
111
|
+
|
|
112
|
+
To turn semantic search off, set `MEMORY_EMBEDDINGS=off`.
|
|
113
|
+
|
|
91
114
|
## Where data is kept
|
|
92
115
|
|
|
93
116
|
By default everything is in `~/.claude/memory/` (`%USERPROFILE%\.claude\memory\` on Windows):
|
|
@@ -98,6 +121,7 @@ By default everything is in `~/.claude/memory/` (`%USERPROFILE%\.claude\memory\`
|
|
|
98
121
|
| `backups/memory-YYYYMMDD.db` | One backup per day, taken when the server starts. The newest 7 are kept |
|
|
99
122
|
| `exports/*.md` | Files written by the `export` tool |
|
|
100
123
|
| `memory-mcp.log` | Log file, rotated at 5 MB |
|
|
124
|
+
| `models/` | The cached embedding model, shared by all databases on the machine |
|
|
101
125
|
|
|
102
126
|
Settings, passed with `-e NAME=value` on `claude mcp add` or in `env` in `.mcp.json`:
|
|
103
127
|
|
|
@@ -107,6 +131,10 @@ Settings, passed with `-e NAME=value` on `claude mcp add` or in `env` in `.mcp.j
|
|
|
107
131
|
| `MEMORY_EXPORT_DIR` | `exports` next to the database |
|
|
108
132
|
| `MEMORY_LOG_PATH` | `memory-mcp.log` next to the database |
|
|
109
133
|
| `MEMORY_BACKUP` | Set to `off` to turn off the daily backup |
|
|
134
|
+
| `MEMORY_EMBEDDINGS` | Set to `off` for keyword-only search (no model download) |
|
|
135
|
+
| `MEMORY_MODEL_DIR` | `~/.claude/memory/models` |
|
|
136
|
+
| `MEMORY_EMBED_DTYPE` | `q8` (quantised, ~130 MB). `fp32` is slightly more accurate and about 4 times larger |
|
|
137
|
+
| `MEMORY_MIN_SIMILARITY` | `0.45`. Semantic matches below this are dropped |
|
|
110
138
|
|
|
111
139
|
To keep a project's memories in a separate file, give that project its own `MEMORY_DB_PATH`.
|
|
112
140
|
|
|
@@ -128,17 +156,15 @@ The code is in `src/`:
|
|
|
128
156
|
| --- | --- |
|
|
129
157
|
| `index.ts` | Entry point: settings, logging, backup, stdio transport |
|
|
130
158
|
| `server.ts` | MCP tool definitions |
|
|
131
|
-
| `store.ts` | All queries: remember, search, supersede, export |
|
|
159
|
+
| `store.ts` | All queries: remember, keyword search, supersede, export |
|
|
160
|
+
| `semantic.ts` | Background embedding, vector search, and fusion with keyword results |
|
|
161
|
+
| `embedder.ts` | The nomic-embed-text model, behind an interface so it can be swapped |
|
|
132
162
|
| `db.ts` | Database connection and schema migrations |
|
|
133
163
|
| `backup.ts` | Daily backup |
|
|
134
164
|
| `logger.ts` | File logger. stdout is reserved for the MCP protocol, so nothing is printed there |
|
|
135
165
|
|
|
136
166
|
To change the schema, add a new SQL string to `MIGRATIONS` in `src/db.ts`. Never edit one that has already shipped.
|
|
137
167
|
|
|
138
|
-
## Roadmap
|
|
139
|
-
|
|
140
|
-
- Meaning-based search (embeddings with `sqlite-vec`), so a reworded query still finds the right memory.
|
|
141
|
-
|
|
142
168
|
## License
|
|
143
169
|
|
|
144
170
|
MIT
|
package/dist/db.js
CHANGED
|
@@ -52,6 +52,24 @@ const MIGRATIONS = [
|
|
|
52
52
|
created_at TEXT NOT NULL,
|
|
53
53
|
UNIQUE (from_id, to_id, label)
|
|
54
54
|
);
|
|
55
|
+
`,
|
|
56
|
+
// v2 — semantic search. One vector per memory, stored as a little-endian
|
|
57
|
+
// Float32 BLOB. `model` records which model produced it, so switching models
|
|
58
|
+
// makes old vectors stale (they are skipped and re-embedded).
|
|
59
|
+
`
|
|
60
|
+
CREATE TABLE memory_embeddings (
|
|
61
|
+
memory_id INTEGER PRIMARY KEY REFERENCES memories(id) ON DELETE CASCADE,
|
|
62
|
+
model TEXT NOT NULL,
|
|
63
|
+
dim INTEGER NOT NULL,
|
|
64
|
+
embedding BLOB NOT NULL,
|
|
65
|
+
created_at TEXT NOT NULL
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
-- Editing content invalidates the vector; the background indexer re-embeds it.
|
|
69
|
+
CREATE TRIGGER memories_embedding_stale AFTER UPDATE OF content ON memories
|
|
70
|
+
WHEN old.content IS NOT new.content BEGIN
|
|
71
|
+
DELETE FROM memory_embeddings WHERE memory_id = old.id;
|
|
72
|
+
END;
|
|
55
73
|
`,
|
|
56
74
|
];
|
|
57
75
|
export function openDb(dbPath) {
|
package/dist/embedder.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* nomic-embed-text-v1.5 run in-process with Transformers.js (ONNX Runtime).
|
|
3
|
+
* No Ollama or Python: the model is downloaded from Hugging Face on first use
|
|
4
|
+
* and cached under `cacheDir`; after that it works offline.
|
|
5
|
+
*
|
|
6
|
+
* Nomic models are trained with task prefixes: documents must be embedded as
|
|
7
|
+
* "search_document: ..." and queries as "search_query: ...". Leaving them out
|
|
8
|
+
* noticeably hurts retrieval quality.
|
|
9
|
+
*/
|
|
10
|
+
export class NomicEmbedder {
|
|
11
|
+
opts;
|
|
12
|
+
static MODEL_ID = "nomic-ai/nomic-embed-text-v1.5";
|
|
13
|
+
dim = 768;
|
|
14
|
+
model;
|
|
15
|
+
extractor = null;
|
|
16
|
+
loading = null;
|
|
17
|
+
constructor(opts) {
|
|
18
|
+
this.opts = opts;
|
|
19
|
+
this.model = `${NomicEmbedder.MODEL_ID}:${opts.dtype ?? "q8"}`;
|
|
20
|
+
}
|
|
21
|
+
init() {
|
|
22
|
+
this.loading ??= (async () => {
|
|
23
|
+
// Dynamic import: the package is an optional dependency, and loading
|
|
24
|
+
// ONNX Runtime costs startup time we don't want on the MCP handshake.
|
|
25
|
+
const { pipeline, env } = await import("@huggingface/transformers");
|
|
26
|
+
env.cacheDir = this.opts.cacheDir;
|
|
27
|
+
const pipe = await pipeline("feature-extraction", NomicEmbedder.MODEL_ID, {
|
|
28
|
+
dtype: (this.opts.dtype ?? "q8"),
|
|
29
|
+
});
|
|
30
|
+
this.extractor = pipe;
|
|
31
|
+
})().catch((err) => {
|
|
32
|
+
this.loading = null; // allow a later retry
|
|
33
|
+
throw err;
|
|
34
|
+
});
|
|
35
|
+
return this.loading;
|
|
36
|
+
}
|
|
37
|
+
async embed(texts, kind) {
|
|
38
|
+
await this.init();
|
|
39
|
+
const prefix = kind === "document" ? "search_document: " : "search_query: ";
|
|
40
|
+
const out = await this.extractor(texts.map((t) => prefix + t), { pooling: "mean", normalize: true });
|
|
41
|
+
return out.tolist().map((v) => Float32Array.from(v));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Float32Array <-> SQLite BLOB. */
|
|
45
|
+
export function toBlob(v) {
|
|
46
|
+
return Buffer.from(v.buffer, v.byteOffset, v.byteLength);
|
|
47
|
+
}
|
|
48
|
+
export function fromBlob(b) {
|
|
49
|
+
// Copy: a Buffer slice may not be 4-byte aligned, which Float32Array requires.
|
|
50
|
+
const copy = new Uint8Array(b.byteLength);
|
|
51
|
+
copy.set(b);
|
|
52
|
+
return new Float32Array(copy.buffer);
|
|
53
|
+
}
|
|
54
|
+
export function dot(a, b) {
|
|
55
|
+
let s = 0;
|
|
56
|
+
for (let i = 0; i < a.length; i++)
|
|
57
|
+
s += a[i] * b[i];
|
|
58
|
+
return s;
|
|
59
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,8 @@ import { MemoryStore } from "./store.js";
|
|
|
8
8
|
import { createServer } from "./server.js";
|
|
9
9
|
import { initLogger, log } from "./logger.js";
|
|
10
10
|
import { dailyBackup } from "./backup.js";
|
|
11
|
+
import { NomicEmbedder } from "./embedder.js";
|
|
12
|
+
import { SemanticIndex } from "./semantic.js";
|
|
11
13
|
// Read the version from package.json (one level above dist/) so it can't drift.
|
|
12
14
|
const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
13
15
|
const dbPath = process.env.MEMORY_DB_PATH || path.join(os.homedir(), ".claude", "memory", "memory.db");
|
|
@@ -17,7 +19,20 @@ async function main() {
|
|
|
17
19
|
const db = openDb(dbPath);
|
|
18
20
|
log("info", `forget-me-not-mcp ${VERSION} started`, { dbPath, pid: process.pid });
|
|
19
21
|
const store = new MemoryStore(db);
|
|
20
|
-
|
|
22
|
+
// Semantic search: on unless MEMORY_EMBEDDINGS=off. The model cache is shared
|
|
23
|
+
// by all databases on the machine, so separate per-project DBs don't each
|
|
24
|
+
// download their own copy.
|
|
25
|
+
const embedder = process.env.MEMORY_EMBEDDINGS === "off"
|
|
26
|
+
? null
|
|
27
|
+
: new NomicEmbedder({
|
|
28
|
+
cacheDir: process.env.MEMORY_MODEL_DIR || path.join(os.homedir(), ".claude", "memory", "models"),
|
|
29
|
+
dtype: process.env.MEMORY_EMBED_DTYPE || "q8",
|
|
30
|
+
});
|
|
31
|
+
const minSimilarity = Number(process.env.MEMORY_MIN_SIMILARITY);
|
|
32
|
+
const semantic = new SemanticIndex(db, store, embedder, {
|
|
33
|
+
minSimilarity: Number.isFinite(minSimilarity) && process.env.MEMORY_MIN_SIMILARITY ? minSimilarity : undefined,
|
|
34
|
+
});
|
|
35
|
+
const server = createServer(store, semantic, {
|
|
21
36
|
version: VERSION,
|
|
22
37
|
exportDir: process.env.MEMORY_EXPORT_DIR || path.join(dataDir, "exports"),
|
|
23
38
|
});
|
|
@@ -37,6 +52,9 @@ async function main() {
|
|
|
37
52
|
process.on("SIGTERM", shutdown);
|
|
38
53
|
process.stdin.on("close", shutdown); // Claude Code closes stdin when the session ends
|
|
39
54
|
await server.connect(new StdioServerTransport());
|
|
55
|
+
// Load the model only after the handshake, so Claude Code never waits on it.
|
|
56
|
+
// Failures are logged and search stays keyword-only.
|
|
57
|
+
semantic.start().catch(() => { });
|
|
40
58
|
}
|
|
41
59
|
main().catch((err) => {
|
|
42
60
|
log("error", "fatal", err);
|
package/dist/semantic.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { dot, fromBlob, toBlob } from "./embedder.js";
|
|
2
|
+
import { log } from "./logger.js";
|
|
3
|
+
/** Standard RRF constant; dampens the advantage of rank 1 over rank 2. */
|
|
4
|
+
const RRF_K = 60;
|
|
5
|
+
/** Candidates taken from each retriever before fusion. */
|
|
6
|
+
const CANDIDATES = 50;
|
|
7
|
+
const toMemory = (r) => ({ ...r, pinned: r.pinned === 1 });
|
|
8
|
+
/**
|
|
9
|
+
* Hybrid retrieval over the memory store.
|
|
10
|
+
*
|
|
11
|
+
* - Keyword (FTS5/BM25) and semantic (embedding cosine) results are merged with
|
|
12
|
+
* reciprocal rank fusion, so neither score scale has to be calibrated.
|
|
13
|
+
* - The model loads in the background. Until it's ready, search quietly falls
|
|
14
|
+
* back to keyword-only, so the MCP server is usable from the first second.
|
|
15
|
+
* - Vectors are compared by brute force in JS. At personal-memory scale
|
|
16
|
+
* (thousands of rows) that takes a few milliseconds and needs no extension.
|
|
17
|
+
*/
|
|
18
|
+
export class SemanticIndex {
|
|
19
|
+
db;
|
|
20
|
+
store;
|
|
21
|
+
embedder;
|
|
22
|
+
status;
|
|
23
|
+
ready = null;
|
|
24
|
+
lastError = null;
|
|
25
|
+
failedAt = 0;
|
|
26
|
+
indexing = null;
|
|
27
|
+
rerun = false;
|
|
28
|
+
opts;
|
|
29
|
+
constructor(db, store, embedder, opts = {}) {
|
|
30
|
+
this.db = db;
|
|
31
|
+
this.store = store;
|
|
32
|
+
this.embedder = embedder;
|
|
33
|
+
this.status = embedder ? "loading" : "off";
|
|
34
|
+
this.opts = {
|
|
35
|
+
minSimilarity: opts.minSimilarity ?? 0.45,
|
|
36
|
+
readyWaitMs: opts.readyWaitMs ?? 5000,
|
|
37
|
+
batchSize: opts.batchSize ?? 32,
|
|
38
|
+
retryAfterMs: opts.retryAfterMs ?? 5 * 60 * 1000,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
info() {
|
|
42
|
+
const counts = this.embedder
|
|
43
|
+
? this.db
|
|
44
|
+
.prepare(`SELECT COUNT(*) AS active,
|
|
45
|
+
SUM(CASE WHEN e.model = @model THEN 1 ELSE 0 END) AS embedded
|
|
46
|
+
FROM memories m LEFT JOIN memory_embeddings e ON e.memory_id = m.id
|
|
47
|
+
WHERE m.status = 'active'`)
|
|
48
|
+
.get({ model: this.embedder.model })
|
|
49
|
+
: null;
|
|
50
|
+
return {
|
|
51
|
+
status: this.status,
|
|
52
|
+
model: this.embedder?.model ?? null,
|
|
53
|
+
...(counts ? { active: counts.active, embedded: counts.embedded ?? 0 } : {}),
|
|
54
|
+
...(this.lastError ? { error: this.lastError } : {}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Start loading the model (no-op if loading, loaded, or recently failed). Then backfill. */
|
|
58
|
+
start() {
|
|
59
|
+
if (!this.embedder)
|
|
60
|
+
return Promise.resolve();
|
|
61
|
+
if (this.ready)
|
|
62
|
+
return this.ready;
|
|
63
|
+
if (this.status === "error" && Date.now() - this.failedAt < this.opts.retryAfterMs) {
|
|
64
|
+
return Promise.reject(new Error(this.lastError ?? "embedder unavailable"));
|
|
65
|
+
}
|
|
66
|
+
this.status = "loading";
|
|
67
|
+
const started = Date.now();
|
|
68
|
+
this.ready = this.embedder.init().then(() => {
|
|
69
|
+
this.status = "ready";
|
|
70
|
+
this.lastError = null;
|
|
71
|
+
log("info", `embedder ${this.embedder.model} ready in ${Date.now() - started} ms`);
|
|
72
|
+
this.schedule();
|
|
73
|
+
}, (err) => {
|
|
74
|
+
this.status = "error";
|
|
75
|
+
this.failedAt = Date.now();
|
|
76
|
+
this.lastError = err instanceof Error ? err.message : String(err);
|
|
77
|
+
this.ready = null;
|
|
78
|
+
log("warn", "embedder failed to load; search is keyword-only", err);
|
|
79
|
+
throw err;
|
|
80
|
+
});
|
|
81
|
+
return this.ready;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Embed every active memory that has no vector for the current model.
|
|
85
|
+
* Call after any write; repeated calls while running coalesce into one more pass.
|
|
86
|
+
*/
|
|
87
|
+
schedule() {
|
|
88
|
+
if (!this.embedder || this.status !== "ready")
|
|
89
|
+
return Promise.resolve();
|
|
90
|
+
if (this.indexing) {
|
|
91
|
+
this.rerun = true;
|
|
92
|
+
return this.indexing;
|
|
93
|
+
}
|
|
94
|
+
this.indexing = (async () => {
|
|
95
|
+
do {
|
|
96
|
+
this.rerun = false;
|
|
97
|
+
await this.indexPending();
|
|
98
|
+
} while (this.rerun);
|
|
99
|
+
})()
|
|
100
|
+
.catch((err) => log("error", "embedding backfill failed", err))
|
|
101
|
+
.finally(() => {
|
|
102
|
+
this.indexing = null;
|
|
103
|
+
});
|
|
104
|
+
return this.indexing;
|
|
105
|
+
}
|
|
106
|
+
async indexPending() {
|
|
107
|
+
const embedder = this.embedder;
|
|
108
|
+
const pending = this.db.prepare(`SELECT m.id, m.content FROM memories m
|
|
109
|
+
LEFT JOIN memory_embeddings e ON e.memory_id = m.id AND e.model = @model
|
|
110
|
+
WHERE m.status = 'active' AND e.memory_id IS NULL AND m.id > @after
|
|
111
|
+
ORDER BY m.id LIMIT @limit`);
|
|
112
|
+
// Only store the vector if the content is still what we embedded; an edit
|
|
113
|
+
// during the (async) embed call must not leave a stale vector behind.
|
|
114
|
+
const upsert = this.db.prepare(`INSERT OR REPLACE INTO memory_embeddings (memory_id, model, dim, embedding, created_at)
|
|
115
|
+
SELECT @id, @model, @dim, @embedding, @now
|
|
116
|
+
WHERE EXISTS (SELECT 1 FROM memories WHERE id = @id AND content = @content)`);
|
|
117
|
+
let total = 0;
|
|
118
|
+
// Walk forward by id so a row whose insert was skipped (edited mid-embed)
|
|
119
|
+
// can't stall the loop; the write that edited it schedules another pass.
|
|
120
|
+
let after = 0;
|
|
121
|
+
for (;;) {
|
|
122
|
+
const rows = pending.all({ model: embedder.model, limit: this.opts.batchSize, after });
|
|
123
|
+
if (!rows.length)
|
|
124
|
+
break;
|
|
125
|
+
const vectors = await embedder.embed(rows.map((r) => r.content), "document");
|
|
126
|
+
const now = new Date().toISOString();
|
|
127
|
+
this.db.transaction(() => {
|
|
128
|
+
rows.forEach((r, i) => {
|
|
129
|
+
upsert.run({ id: r.id, model: embedder.model, dim: vectors[i].length, embedding: toBlob(vectors[i]), content: r.content, now });
|
|
130
|
+
});
|
|
131
|
+
})();
|
|
132
|
+
after = rows[rows.length - 1].id;
|
|
133
|
+
total += rows.length;
|
|
134
|
+
}
|
|
135
|
+
if (total)
|
|
136
|
+
log("info", `embedded ${total} memories`);
|
|
137
|
+
}
|
|
138
|
+
/** Cosine top-k over active memories that match the filters. */
|
|
139
|
+
vectorSearch(query, input, k) {
|
|
140
|
+
const { where, params } = this.store.filterClauses(input);
|
|
141
|
+
const rows = this.db
|
|
142
|
+
.prepare(`SELECT m.*, e.embedding AS _embedding FROM memories m
|
|
143
|
+
JOIN memory_embeddings e ON e.memory_id = m.id AND e.model = @model
|
|
144
|
+
WHERE ${where.join(" AND ")}`)
|
|
145
|
+
.all({ ...params, model: this.embedder.model });
|
|
146
|
+
return rows
|
|
147
|
+
.map(({ _embedding, ...r }) => ({ memory: toMemory(r), similarity: dot(query, fromBlob(_embedding)) }))
|
|
148
|
+
.filter((h) => h.similarity >= this.opts.minSimilarity)
|
|
149
|
+
.sort((a, b) => b.similarity - a.similarity)
|
|
150
|
+
.slice(0, k);
|
|
151
|
+
}
|
|
152
|
+
/** Wait for the model if it's loading, but never longer than readyWaitMs. */
|
|
153
|
+
async waitReady() {
|
|
154
|
+
if (this.status === "ready")
|
|
155
|
+
return true;
|
|
156
|
+
if (!this.embedder)
|
|
157
|
+
return false;
|
|
158
|
+
const ready = this.start().then(() => true, () => false);
|
|
159
|
+
const timeout = new Promise((r) => setTimeout(r, this.opts.readyWaitMs, false).unref());
|
|
160
|
+
return Promise.race([ready, timeout]);
|
|
161
|
+
}
|
|
162
|
+
async search(input) {
|
|
163
|
+
const limit = Math.min(Math.max(input.limit ?? 10, 1), 50);
|
|
164
|
+
const keyword = this.store.search({ ...input, limit: CANDIDATES });
|
|
165
|
+
let semantic = [];
|
|
166
|
+
if (await this.waitReady()) {
|
|
167
|
+
try {
|
|
168
|
+
const [q] = await this.embedder.embed([input.query], "query");
|
|
169
|
+
semantic = this.vectorSearch(q, input, CANDIDATES);
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
log("warn", "query embedding failed; keyword-only result", err);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Reciprocal rank fusion: score = Σ 1 / (k + rank) over the lists an item appears in.
|
|
176
|
+
const fused = new Map();
|
|
177
|
+
keyword.forEach((m, rank) => {
|
|
178
|
+
const { score: _bm25, ...memory } = m;
|
|
179
|
+
fused.set(m.id, { ...memory, score: 1 / (RRF_K + rank + 1), match: "keyword" });
|
|
180
|
+
});
|
|
181
|
+
semantic.forEach(({ memory, similarity }, rank) => {
|
|
182
|
+
const add = 1 / (RRF_K + rank + 1);
|
|
183
|
+
const hit = fused.get(memory.id);
|
|
184
|
+
const sim = Math.round(similarity * 1000) / 1000;
|
|
185
|
+
if (hit) {
|
|
186
|
+
hit.score += add;
|
|
187
|
+
hit.match = "both";
|
|
188
|
+
hit.similarity = sim;
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
fused.set(memory.id, { ...memory, score: add, match: "semantic", similarity: sim });
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
const results = [...fused.values()]
|
|
195
|
+
.sort((a, b) => b.score - a.score || b.updated_at.localeCompare(a.updated_at))
|
|
196
|
+
.slice(0, limit)
|
|
197
|
+
.map((r) => ({ ...r, score: Math.round(r.score * 10000) / 10000 }));
|
|
198
|
+
return { semantic: this.status, results };
|
|
199
|
+
}
|
|
200
|
+
}
|
package/dist/server.js
CHANGED
|
@@ -24,6 +24,8 @@ function brief(m) {
|
|
|
24
24
|
...(m.supersedes_id ? { supersedes_id: m.supersedes_id } : {}),
|
|
25
25
|
updated: m.updated_at.slice(0, 10),
|
|
26
26
|
...(m.score !== undefined ? { score: m.score } : {}),
|
|
27
|
+
...(m.match ? { match: m.match } : {}),
|
|
28
|
+
...(m.similarity !== undefined ? { similarity: m.similarity } : {}),
|
|
27
29
|
};
|
|
28
30
|
}
|
|
29
31
|
const ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
|
|
@@ -41,7 +43,12 @@ function handle(name, fn) {
|
|
|
41
43
|
}
|
|
42
44
|
};
|
|
43
45
|
}
|
|
44
|
-
export function createServer(store, opts) {
|
|
46
|
+
export function createServer(store, semantic, opts) {
|
|
47
|
+
/** Fire-and-forget: embed new or edited memories in the background. */
|
|
48
|
+
const reindex = (result) => {
|
|
49
|
+
void semantic.schedule();
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
45
52
|
const server = new McpServer({ name: "forget-me-not", version: opts.version }, {
|
|
46
53
|
instructions: "Persistent memory across Claude Code sessions. Call get_context at the start of a task, search before " +
|
|
47
54
|
"re-investigating something, remember lasting decisions/fixes/facts, and use supersede (not remember) " +
|
|
@@ -59,11 +66,13 @@ export function createServer(store, opts) {
|
|
|
59
66
|
tags: tagsSchema.optional(),
|
|
60
67
|
pinned: z.boolean().optional().describe("Pinned memories are always returned by get_context"),
|
|
61
68
|
},
|
|
62
|
-
}, handle("remember", (a) => brief(store.remember(a))));
|
|
69
|
+
}, handle("remember", (a) => reindex(brief(store.remember(a)))));
|
|
63
70
|
server.registerTool("search", {
|
|
64
71
|
title: "Search memories",
|
|
65
|
-
description: "
|
|
66
|
-
"
|
|
72
|
+
description: "Hybrid search over active memories: keyword (exact terms, error codes, names) plus semantic (meaning), " +
|
|
73
|
+
"merged by rank. Natural-language questions work; include distinctive terms when you have them. Each result " +
|
|
74
|
+
"says whether it matched by keyword, semantic or both. When project is given, global memories are included " +
|
|
75
|
+
"unless include_global is false.",
|
|
67
76
|
inputSchema: {
|
|
68
77
|
query: z.string().min(1),
|
|
69
78
|
project: projectSchema.optional(),
|
|
@@ -71,9 +80,9 @@ export function createServer(store, opts) {
|
|
|
71
80
|
include_global: z.boolean().optional(),
|
|
72
81
|
limit: z.number().int().min(1).max(50).optional(),
|
|
73
82
|
},
|
|
74
|
-
}, handle("search", (a) => {
|
|
75
|
-
const results =
|
|
76
|
-
return { count: results.length, results: results.map(brief) };
|
|
83
|
+
}, handle("search", async (a) => {
|
|
84
|
+
const { semantic: status, results } = await semantic.search({ ...a, includeGlobal: a.include_global });
|
|
85
|
+
return { count: results.length, semantic: status, results: results.map(brief) };
|
|
77
86
|
}));
|
|
78
87
|
server.registerTool("get_context", {
|
|
79
88
|
title: "Get project context",
|
|
@@ -96,7 +105,7 @@ export function createServer(store, opts) {
|
|
|
96
105
|
type: typeSchema.optional(),
|
|
97
106
|
pinned: z.boolean().optional(),
|
|
98
107
|
},
|
|
99
|
-
}, handle("update_memory", ({ id, ...changes }) => brief(store.update(id, changes))));
|
|
108
|
+
}, handle("update_memory", ({ id, ...changes }) => reindex(brief(store.update(id, changes)))));
|
|
100
109
|
server.registerTool("supersede", {
|
|
101
110
|
title: "Supersede memory",
|
|
102
111
|
description: "Replace an outdated memory with a new one. The old one is marked superseded and disappears from search; " +
|
|
@@ -110,7 +119,7 @@ export function createServer(store, opts) {
|
|
|
110
119
|
},
|
|
111
120
|
}, handle("supersede", ({ old_id, ...input }) => {
|
|
112
121
|
const r = store.supersede(old_id, input);
|
|
113
|
-
return { superseded: brief(r.old), new: brief(r.new) };
|
|
122
|
+
return reindex({ superseded: brief(r.old), new: brief(r.new) });
|
|
114
123
|
}));
|
|
115
124
|
server.registerTool("forget", {
|
|
116
125
|
title: "Forget memory",
|
|
@@ -142,6 +151,15 @@ export function createServer(store, opts) {
|
|
|
142
151
|
description: "List all relations that touch an entity, in either direction.",
|
|
143
152
|
inputSchema: { name: z.string().min(1) },
|
|
144
153
|
}, handle("related", ({ name }) => store.related(name)));
|
|
154
|
+
server.registerTool("status", {
|
|
155
|
+
title: "Memory status",
|
|
156
|
+
description: "Server version, memory counts by status, and whether semantic search is ready (model, how many memories are embedded).",
|
|
157
|
+
inputSchema: {},
|
|
158
|
+
}, handle("status", () => ({
|
|
159
|
+
version: opts.version,
|
|
160
|
+
memories: Object.fromEntries(store.stats().map((s) => [s.status, s.n])),
|
|
161
|
+
semantic: semantic.info(),
|
|
162
|
+
})));
|
|
145
163
|
server.registerTool("export", {
|
|
146
164
|
title: "Export to Markdown",
|
|
147
165
|
description: "Write all active memories (optionally one project) to a Markdown file for review. Returns the file path.",
|
package/dist/store.js
CHANGED
|
@@ -27,14 +27,24 @@ export function normaliseProject(project) {
|
|
|
27
27
|
* FTS5 query syntax. Returns null if nothing searchable remains.
|
|
28
28
|
*/
|
|
29
29
|
export function buildFtsQuery(text, op) {
|
|
30
|
-
|
|
30
|
+
let tokens = text
|
|
31
31
|
.split(/\s+/)
|
|
32
32
|
.map((t) => t.replace(/"/g, "").trim())
|
|
33
33
|
.filter((t) => /[\p{L}\p{N}]/u.test(t));
|
|
34
|
+
// In OR mode a single filler word ("the", "is") would match almost every
|
|
35
|
+
// memory, so drop them — unless that leaves nothing to search for.
|
|
36
|
+
if (op === "OR") {
|
|
37
|
+
const meaningful = tokens.filter((t) => !STOPWORDS.has(t.toLowerCase()));
|
|
38
|
+
if (meaningful.length)
|
|
39
|
+
tokens = meaningful;
|
|
40
|
+
}
|
|
34
41
|
if (!tokens.length)
|
|
35
42
|
return null;
|
|
36
43
|
return tokens.map((t) => `"${t}"`).join(` ${op} `);
|
|
37
44
|
}
|
|
45
|
+
const STOPWORDS = new Set(("a an and are as at be but by can do does for from get got has have how i if in into is it its me my no not of on or " +
|
|
46
|
+
"our should so that the their them there these this to too was we were what when where which who why will with would you your")
|
|
47
|
+
.split(" "));
|
|
38
48
|
function checkContent(content) {
|
|
39
49
|
const c = content.trim();
|
|
40
50
|
if (!c)
|
|
@@ -80,15 +90,25 @@ export class MemoryStore {
|
|
|
80
90
|
* Tries an AND of all terms first (precise); if that finds nothing, retries
|
|
81
91
|
* with OR so a partially matching query still recalls something.
|
|
82
92
|
*/
|
|
83
|
-
|
|
84
|
-
|
|
93
|
+
/**
|
|
94
|
+
* WHERE clauses (against alias `m`) and parameters for the search filters.
|
|
95
|
+
* Shared by keyword and semantic search so both honour the same scope.
|
|
96
|
+
*/
|
|
97
|
+
filterClauses(input) {
|
|
85
98
|
const project = normaliseProject(input.project);
|
|
86
99
|
const includeGlobal = input.includeGlobal ?? true;
|
|
87
|
-
const where = ["m.status = 'active'"
|
|
100
|
+
const where = ["m.status = 'active'"];
|
|
88
101
|
if (project)
|
|
89
102
|
where.push(includeGlobal ? "(m.project = @project OR m.project IS NULL)" : "m.project = @project");
|
|
90
103
|
if (input.type)
|
|
91
104
|
where.push("m.type = @type");
|
|
105
|
+
return { where, params: { project, type: input.type ?? null } };
|
|
106
|
+
}
|
|
107
|
+
search(input) {
|
|
108
|
+
const limit = Math.min(Math.max(input.limit ?? 10, 1), 50);
|
|
109
|
+
const { where: filters, params } = this.filterClauses(input);
|
|
110
|
+
const project = params.project;
|
|
111
|
+
const where = [...filters, "memories_fts MATCH @q"];
|
|
92
112
|
// bm25() is lower-is-better; weight content 1.0 and tags 0.5. A small boost
|
|
93
113
|
// for the requested project so its rows beat equally relevant global ones.
|
|
94
114
|
const sql = `
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "forget-me-not-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Local memory MCP server for Claude Code: decisions, fixes and project facts that persist across sessions, stored in SQLite with
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Local memory MCP server for Claude Code: decisions, fixes and project facts that persist across sessions, stored in SQLite with hybrid keyword + semantic search.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
7
7
|
"model-context-protocol",
|
|
@@ -10,7 +10,10 @@
|
|
|
10
10
|
"memory",
|
|
11
11
|
"sqlite",
|
|
12
12
|
"fts5",
|
|
13
|
-
"ai-agent"
|
|
13
|
+
"ai-agent",
|
|
14
|
+
"embeddings",
|
|
15
|
+
"semantic-search",
|
|
16
|
+
"nomic-embed-text"
|
|
14
17
|
],
|
|
15
18
|
"author": "Ranga Surendra",
|
|
16
19
|
"license": "MIT",
|
|
@@ -44,5 +47,8 @@
|
|
|
44
47
|
"@types/node": "^26.6.6",
|
|
45
48
|
"typescript": "^7.0.2",
|
|
46
49
|
"vitest": "^5.1.0"
|
|
50
|
+
},
|
|
51
|
+
"optionalDependencies": {
|
|
52
|
+
"@huggingface/transformers": "^4.3.2"
|
|
47
53
|
}
|
|
48
54
|
}
|