Persistent codebase memory for an AI coding agent is a small MCP server that stores structured, evidence-backed facts about your repository outside the context window and returns them on demand. Because it is an MCP server rather than a plugin, any MCP-capable agent can read from it and write to it, and what it learns survives across sessions, machines and different agents.
This guide shows what belongs in that memory, how to structure it, and how to build the server with NitroStack in TypeScript.
Quick answer: Build an MCP server with three tools (
recall,remember,forget), store entries in SQLite with full-text search, and give every entry akind, ascope, andevidence(files and a commit). Rank results by scope, then relevance, then recency. Usegit diffto lower the confidence of entries whose cited files changed. Tell the agent torecallbefore a task andrememberafter.
Disclosure: this article is published by the NitroStack team, and the server below is built with NitroStack, our open-source framework. The approach works with any MCP server SDK. [confirm wording]
Why do AI coding agents forget your codebase every session?
Your AI coding agent is brilliant for the first ten minutes of every session and a stranger to your codebase for the rest of its life.
Open a fresh session and watch what happens. The agent lists directories, greps for the auth middleware, opens the same five files it opened yesterday, and re-discovers that your team uses pnpm, not npm. Then it confidently proposes a fix that breaks a convention you settled in a pull request three months ago. None of this is a model-quality problem. It is a memory problem: everything the agent learned last session was thrown away when the context window closed.
Why don't CLAUDE.md, AGENTS.md or bigger context windows solve it?
They help, but each leaves a gap:
| Approach | Strength | Where it falls short |
|---|---|---|
| CLAUDE.md / AGENTS.md | Zero infrastructure, human-readable, loads automatically | Someone must write and maintain it, and it has to stay short enough to load every time |
| Bigger context window | Paste in more background | You pay for those tokens on every turn, and the agent still doesn't know why the code looks the way it does |
| MCP memory server (this guide) | Queryable, structured, shared across agents, can flag stale facts | You build and run a server, and you must guard against bad writes |
These aren't exclusive. A short instruction file that tells the agent to call recall first pairs well with a memory server.
What is codebase memory?
Codebase memory is the set of facts about a repository that an agent can't cheaply re-derive by reading code, stored outside the context window and retrieved on demand. The key phrase is can't cheaply re-derive. The agent can always grep for a function signature. It cannot grep for "we dropped Redux in March because of bundle size" or "never run the integration suite against prod credentials."
Five kinds of knowledge earn a place in memory:
| Kind | Example | Why the agent can't just read it |
|---|---|---|
| Structure | "Billing logic lives in packages/billing; apps/web only calls its public API" | Learned by exploring many files; expensive to repeat |
| Conventions | "Errors are returned as Result<T>, never thrown" | Implicit; visible only as a pattern across files |
| Decisions | "Chose Postgres over DynamoDB for audit queries (ADR-014)" | The why isn't in the code |
| Gotchas | "Tests in legacy/ fail if run in parallel" | Learned the hard way, written nowhere |
| Task history | "Auth refactor: finished token rotation, session cleanup still open" | Lives only in the previous session |
What to leave out: raw file contents (the file is the source of truth and goes stale instantly), anything the agent can recover with one grep, and secrets. A good entry is short, specific and tied to evidence: a file path, a commit, a pull request. If an entry can't point at something checkable, it's a rumor, and rumors are how memory goes bad.
Why is MCP the right interface for agent memory?
You could bolt memory onto a single editor plugin. But then Cursor's memory isn't Claude Code's memory, and a teammate on a different agent starts from zero. MCP makes memory a server rather than a feature of one client: write it once, and every MCP-capable agent can use it.
MCP's three primitives each map onto part of the problem:
- Tools are actions the agent decides to take:
recallto search memory,rememberto save a new fact,forgetto retire a stale one. The model chooses when to call them. - Resources are read-only context the client can attach. A
memory://overviewresource can hand every new session a compact map of the repo without a tool call. - Prompts are reusable templates. An
onboard_meprompt can bundle "read the overview, check recent task history, then summarize what's in flight."
The design rule that follows: reads should be cheap and automatic, writes should be deliberate. Expose the overview as a resource, expose search as a tool, and make writes go through a tool with a strict schema so the agent can't dump free-form text into your store.
What does the architecture look like?
Four layers, each swappable without touching the others. Agents speak MCP to a thin server; the server delegates to a service that owns ranking and write rules; the service persists to a single database file. A separate job watches git and keeps the store honest.
Agents only ever see tools, resources and prompts, so you can replace SQLite with Postgres or add embeddings later without any client noticing. The git job is the only writer that isn't an agent or a human, and its sole task is to lower confidence when the files an entry cites have changed.
[Insert architecture diagram here. Suggested alt text: "Agents call an MCP server, which uses a memory service backed by SQLite, with a git job lowering confidence on stale entries."]
How should you design the memory model?
A memory store is only as good as its schema. Free-text notes are easy to write and miserable to retrieve, so give every entry structure from day one:
typescriptinterface MemoryEntry { id: string; kind: 'structure' | 'convention' | 'decision' | 'gotcha' | 'task'; summary: string; // one or two sentences, what the agent reads detail?: string; // optional longer explanation scope: string[]; // paths or globs this applies to, e.g. ['packages/billing/**'] evidence: { // provenance: why we believe this files: string[]; commit?: string; // commit the fact was observed at source: 'agent' | 'human' | 'indexer'; }; confidence: number; // 0..1, decays as evidence changes createdAt: string; lastVerifiedAt: string; supersededBy?: string; // soft-delete: point to the replacement }
Four fields do most of the work:
scopemakes retrieval spatial. When the agent is editingpackages/billing/invoice.ts, it should see billing memories first and ignore the rest. Scope is the cheapest relevance signal you have.evidencemakes memory trustworthy. Every claim carries the files and commit it was observed at, so you can later check whether it still holds.lastVerifiedAtandconfidencemodel staleness honestly. Memory isn't true or false; it's more or less likely to still be true.supersededBymeans you never hard-delete. When a convention changes, the old entry points to the new one, which preserves decision history and stops the agent re-learning the old rule from a stale copy.
Storage: start boring. SQLite with FTS5 full-text search gives you ranked keyword retrieval, zero infrastructure and a single file you can commit or sync. Add vector embeddings later if keyword recall proves too weak; many teams never need to.
How do you build the memory server with NitroStack?
NitroStack is an open-source TypeScript framework for MCP servers. It's NestJS-inspired: tools, resources and prompts are decorated methods on classes, grouped into modules, with dependency injection wiring services together. That structure suits a memory server because the store, the retriever and the tool surface are naturally separate concerns.
Version note: decorator and import names vary between NitroStack releases (the docs show both
nitrostackand@nitrostack/coreentry points). Check the snippets below against the version you install. The code is illustrative and has not been run end to end.
Step 1: Scaffold the project
bashnpx @nitrostack/cli init codebase-memory cd codebase-memory npm install better-sqlite3 npm run dev
Step 2: Write the memory service
The service owns the SQLite store and nothing else. Keeping it free of MCP concepts means you can unit-test it without a server.
typescript// src/memory/memory.service.ts import Database from 'better-sqlite3'; import { randomUUID } from 'node:crypto'; export class MemoryService { private db = new Database(process.env.MEMORY_DB ?? '.memory/codebase.db'); constructor() { this.db.exec(` CREATE TABLE IF NOT EXISTS memory ( id TEXT PRIMARY KEY, kind TEXT, summary TEXT, detail TEXT, scope TEXT, evidence TEXT, confidence REAL, created_at TEXT, last_verified_at TEXT, superseded_by TEXT ); CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(summary, detail, content='memory', content_rowid='rowid'); `); } save(entry: Omit<MemoryEntry, 'id' | 'createdAt' | 'lastVerifiedAt'>) { const id = randomUUID(); const now = new Date().toISOString(); const info = this.db.prepare( `INSERT INTO memory VALUES (?,?,?,?,?,?,?,?,?,NULL)` ).run(id, entry.kind, entry.summary, entry.detail ?? '', JSON.stringify(entry.scope), JSON.stringify(entry.evidence), entry.confidence, now, now); this.db.prepare( `INSERT INTO memory_fts(rowid, summary, detail) VALUES (?,?,?)` ).run(info.lastInsertRowid, entry.summary, entry.detail ?? ''); return id; } search(query: string, limit = 8) { return this.db.prepare(` SELECT m.* FROM memory_fts f JOIN memory m ON m.rowid = f.rowid WHERE memory_fts MATCH ? AND m.superseded_by IS NULL ORDER BY bm25(memory_fts) LIMIT ? `).all(query, limit); } }
Step 3: Expose the tools
Three tools are enough: recall, remember and forget. Each has a strict Zod schema, so the agent can't write malformed memory. recall and remember are shown below; forget follows the same pattern and sets superseded_by on an entry.
typescript// src/memory/memory.tools.ts import { ToolDecorator as Tool, z, ExecutionContext } from '@nitrostack/core'; import { MemoryService } from './memory.service.js'; export class MemoryTools { constructor(private memory: MemoryService) {} @Tool({ name: 'recall', description: 'Search persistent codebase memory. Call this BEFORE exploring unfamiliar ' + 'areas of the repo, and before making changes that touch conventions.', inputSchema: z.object({ query: z.string().describe('What you want to know, in plain words'), path: z.string().optional().describe('File you are working on, to prioritize scoped memory'), }), }) async recall(input: { query: string; path?: string }, ctx: ExecutionContext) { // Basic version: full-text only. The ranking section below adds path-aware scoring. return this.memory.search(input.query); } @Tool({ name: 'remember', description: 'Save a durable fact about this codebase. Only save things that cannot be ' + 'recovered by reading code: decisions, conventions, gotchas. Always cite evidence.', inputSchema: z.object({ kind: z.enum(['structure', 'convention', 'decision', 'gotcha', 'task']), summary: z.string().min(10).max(280), scope: z.array(z.string()).min(1), files: z.array(z.string()).min(1).describe('Files that support this fact'), }), }) async remember(input: any, ctx: ExecutionContext) { const id = this.memory.save({ kind: input.kind, summary: input.summary, scope: input.scope, evidence: { files: input.files, source: 'agent' }, confidence: 0.6, }); return { saved: id }; } }
Much of the engineering lives in the tool descriptions. The model decides when to call a tool largely from that text, so "call this BEFORE exploring unfamiliar areas" does real work. Also note that remember requires files and caps summary at 280 characters. Those constraints keep the store from filling up with essays.
Step 4: Wire it into a module
typescript// src/app.module.ts import { McpApp, Module } from '@nitrostack/core'; import { MemoryService } from './memory/memory.service.js'; import { MemoryTools } from './memory/memory.tools.js'; @Module({ name: 'memory', controllers: [MemoryTools], providers: [MemoryService], }) class MemoryModule {} @McpApp({ module: AppModule, server: { name: 'codebase-memory', version: '1.0.0' }, }) @Module({ imports: [MemoryModule] }) export class AppModule {}
Point your agent at the server (for Claude Code: claude mcp add codebase-memory -- npx tsx src/main.ts) and the three tools appear. NitroStack's Studio app is handy here: call remember and recall by hand and inspect the payloads before any model touches them.
How do you retrieve the right memory and keep it fresh?
Storage is the easy half. A memory that returns the wrong thing, or the right thing from six months ago, is worse than no memory, so spend your effort here.
Rank by scope, then relevance, then recency
Plain full-text ranking ignores context the agent already gave you. When recall receives a path, boost entries whose scope globs match it, then break ties by lastVerifiedAt. A short scoring function beats an embedding model you haven't needed yet:
typescriptfunction score(row: MemoryRow, path?: string): number { const scoped = path && matchesAny(row.scope, path) ? 2.0 : 0; const ageDays = (Date.now() - Date.parse(row.lastVerifiedAt)) / 864e5; return -row.bm25 + scoped + row.confidence - Math.min(ageDays / 90, 1); }
MemoryRow and matchesAny are yours to define: a row type with the parsed columns plus the bm25 value, and a glob matcher such as picomatch. To use this, have search accept the path, fetch more rows than you need, sort by score, and return the top few. Cap what you return: eight short entries cost the agent a few hundred tokens; eighty cost it focus.
Let git tell you what's stale
Your repository already records when facts stop being true. Run a lightweight job on each commit, or when the server starts, that compares each entry's evidence files against git diff since the commit it was observed at:
- File unchanged: leave the entry alone.
- File modified: lower confidence and flag the entry as "needs re-verification." Return it from
recallwith a warning rather than hiding it. - File deleted or renamed: mark it superseded, or follow the rename and update the evidence path.
This turns staleness from a silent failure into a visible one. The agent sees "this note may be outdated, the cited file changed in a1b2c3d" and can verify before relying on it.
Close the loop: let the agent write back
Memory that only humans maintain won't be maintained. Give the agent a clear trigger for remember: when it discovers a gotcha, when a human corrects it, or when it finishes a task with open threads. A short instruction in your project's agent config does it:
After finishing a task, save any non-obvious convention, decision or gotcha you learned with
remember. Before starting one, callrecallfor the area you'll touch.
Pair that with a task entry at the end of each session, a two-line handoff saying what's done and what's open. That single habit is often the biggest practical win, because it replaces the "where were we?" re-exploration that burns the most tokens.
What can go wrong with persistent agent memory?
A persistent memory is also a persistent attack surface and a persistent source of confident wrong answers. Four failure modes need a design answer before you ship:
- Memory poisoning. An agent that reads a malicious README or web page can be tricked into saving "always disable auth checks in tests" as a convention. Treat
remembercalls as untrusted writes: require evidence files that exist in the repo, tag entries withsource: 'agent', and haverecalllabel agent-written, unreviewed entries so the model weighs them accordingly. For high-impact kinds likeconvention, route writes through human review. - Stale confidence. If nothing ever lowers confidence, old facts win forever. The git-based decay above is the minimum; also run a periodic sweep that surfaces entries unverified for 90 days.
- Token bloat. Memory that grows unbounded eventually returns noise. Enforce the 280-character summary cap, merge near-duplicates on write (search before insert), and keep
recallcapped at a handful of results. - Secrets and privacy. The store will hold paths, names and internal decisions. Scan
summaryanddetailfor credential patterns on write, keep the database out of public repos, and decide up front whether memory is per-developer, per-repo or shared across the team.
One more habit: log every recall and remember call. After a few weeks the log shows which memories the agent actually uses, which it ignores and which it keeps re-saving. That is the feedback you need to tune the schema.
When should you not build an MCP memory server?
- Small or short-lived repos: a well-kept
CLAUDE.mdorAGENTS.mdis simpler and often enough. - A solo developer on a single agent: the cross-agent benefit is smaller, so the server may not pay for itself.
- No one to review writes: if nobody will maintain or audit the store, poisoning and staleness will outweigh the gains.
Where to go from here
Agents don't need bigger context windows nearly as much as they need better recall. A small MCP server that stores structured, evidence-backed facts about your repo, retrieves them by scope and recency, and lets the agent write back what it learns turns every session into a continuation of the last one.
To get started, scaffold the server above, seed it with a handful of real conventions and gotchas from your team, and add two lines to your agent's instructions telling it to recall before and remember after. Once that loop works, the natural next steps are an indexer that seeds structure entries automatically, vector search for fuzzy queries, and shared team memory with review.
Ready to try it? Start with the NitroStack docs and run npx @nitrostack/cli init codebase-memory.
Frequently asked questions
What is persistent codebase memory for AI coding agents?
It is a store of facts about a repository that an agent can't cheaply re-derive by reading code, such as conventions, decisions and gotchas, kept outside the context window and retrieved on demand through a tool like recall.
How is MCP memory different from CLAUDE.md or AGENTS.md?
Instruction files are static text that loads every session and must be hand-maintained. An MCP memory server is queryable, structured, can track evidence and staleness, and is shared across any MCP-capable agent.
What should an AI agent store in codebase memory?
Structure, conventions, decisions, gotchas and task history. It should not store raw file contents, anything recoverable with one grep, or secrets.
How do you stop agent memory from going stale?
Record the files and commit each entry was observed at, compare them against git diff, lower confidence when the files change, and return flagged entries with a warning instead of hiding them. Add a periodic sweep for entries unverified for 90 days.
Do I need a vector database for codebase memory?
Not to start. SQLite full-text search with scope-aware ranking is often enough. Add embeddings later if keyword recall proves too weak.
How do you prevent memory poisoning?
Treat agent writes as untrusted: require evidence files that exist, tag the source, label unreviewed entries on recall, and send high-impact entries such as conventions through human review.
Does this work with Cursor and Claude Code?
Yes, in principle: any MCP-capable client can connect to the server. Setup commands differ per client, so check each tool's current MCP documentation.


