memory: safer persistence defaults, atomic writes, quotas, redaction, and destructive-operation guardrails
Summary
While auditing and hardening local MCP server usage, I reviewed @modelcontextprotocol/server-memory and built a local hardened wrapper for our environment. I am opening this issue to share findings and possible upstream improvements.
This is not a report about a known data loss incident in the upstream package. It is a defense-in-depth report about persistence defaults and operational safety for a memory tool exposed to autonomous agents.
Package/runtime reviewed
- Package:
@modelcontextprotocol/[email protected] - License observed: MIT
- Author observed: Anthropic, PBC
- Upstream repo/issue tracker:
modelcontextprotocol/servers - npm maintainers observed from registry during local review:
jspahrsummers,pcarleton,thedsp,ashwin-ant,ochafik
Findings
-
Default persistence path can land inside the package directory. Local source evidence showed a default path based on
path.dirname(fileURLToPath(import.meta.url)), withmemory.jsonlunder the packagedistdirectory whenMEMORY_FILE_PATHis not configured. This creates operational fragility:- package reinstall/update can remove or overwrite memory state
- global/package directories are not intuitive user data locations
- backup/sync behavior is unclear
-
Writes appear to be whole-file writes without explicit atomic replace and lock discipline. For agent memory, interrupted writes or concurrent host usage can corrupt or lose state. This is especially relevant when the same memory server is configured across multiple MCP hosts.
-
No obvious mutation journal or backup trail. Debugging accidental writes or deletes is hard without append-only audit entries or backup snapshots.
-
Destructive tools are available by default.
delete_entities,delete_observations, anddelete_relationsare useful, but high-impact. In an agent context, accidental deletion should require explicit operator opt-in or confirmation mode. -
No obvious quotas/caps. Large observations or graphs can become a memory/latency issue. Whole-graph reads and writes are also sensitive to unbounded growth.
-
No obvious secret redaction before persistence. Memory can become a persistent prompt-injection and secret-retention surface if fetched web content, logs, stack traces, or credentials are persisted without sanitization.
-
No namespace isolation by default. A single global memory file shared across workspace/host contexts can mix unrelated operational memories unless the user manually configures paths.
Local hardening behavior that worked well
For our local wrapper, we preserved the upstream-compatible 9 tool names:
create_entities, create_relations, add_observations, delete_entities,
delete_observations, delete_relations, read_graph, search_nodes, open_nodes
We added:
- explicit persistence outside
node_modules, defaulting to a user data path - refusal to persist under
node_modules - namespace support for workspace separation
- cross-process lock with stale-lock cleanup
- temp-write plus rename, with backup file
- append-only mutation audit journal
- quotas for entity/relation counts and observation sizes
- secret redaction before writes
- destructive tools disabled unless
LCV_MCP_MEMORY_ALLOW_DESTRUCTIVE=1
Validation from local wrapper
Smoke output from the hardened local wrapper:
memory tools: add_observations,create_entities,create_relations,delete_entities,delete_observations,delete_relations,open_nodes,read_graph,search_nodes
memory read_graph entities=0 relations=0
A redaction/destructive-operation check also behaved as intended in local testing:
create {"entities":[{"name":"redaction-proof","entityType":"test","observations":["token [REDACTED]"]}]}
delete [{"type":"text","text":"delete_entities is disabled by default. Set LCV_MCP_MEMORY_ALLOW_DESTRUCTIVE=1 to enable destructive memory mutations."}]
Suggested upstream changes
- Default persistence to an OS/user data directory instead of the installed package directory.
- Refuse or strongly warn when
MEMORY_FILE_PATHresolves insidenode_modulesor another package-managed path. - Use atomic write/replace and cross-process locking.
- Add backup and append-only mutation audit journal options.
- Add quotas for graph size, entity count, relation count, and observation length.
- Redact common secret patterns before persistence.
- Add namespace support or document recommended per-workspace file paths.
- Gate destructive tools behind an explicit environment flag or confirmation mechanism.
Compatibility note
Most of these can be additive and opt-in, except the safer default persistence path. If changing the default is too disruptive, a migration warning plus documented MEMORY_FILE_PATH recommendation would still help users avoid package-dir persistence.
The persistence path issue is the most immediately actionable: defaulting to a path inside the package directory means any update silently drops state. That alone warrants an upstream fix regardless of the security angle.
On the destructive-operation guardrails point: approving deletes before they execute and maintaining a tamper-evident audit log of what an agent wrote or erased are concerns that live at the consumer layer, not just the server. Even if the server ships safer defaults, an agent operating under prompt injection could still call destructive operations legitimately from the server's perspective.
The separation that tends to work well in practice: the server handles data integrity (atomic writes, quotas, safe paths), and the calling layer handles operation-level authorisation - specifically, an approval gate before destructive tool calls and an audit log of every call with its arguments. If you're running this server as part of a broader agent stack with tools you didn't build, that calling-layer enforcement is what PolicyLayer covers.
Safer persistence defaults are especially valuable in MCP servers that may be embedded into long-lived desktop sessions. Atomic writes plus quotas are a good baseline, but I’d also consider a corruption-recovery path that prefers the last known-good snapshot over a hard failure. That keeps the tool usable after abrupt shutdowns or partial writes. Redaction is the other piece worth testing early: it’s easy for one log path to bypass the sanitizer, so a fixture that asserts both persisted content and emitted logs stay aligned would catch a lot of edge cases.
Thanks for the detailed feedback. I agree with the split: the server should own persistence integrity and safe storage defaults, while the caller/consumer layer is the right place for approval gates around destructive operations.
For the server-side scope of this issue, the immediately actionable pieces remain:
- move durable state out of the package/install directory by default;
- use atomic writes and quotas;
- add redaction coverage for both persisted content and emitted logs;
- add corruption recovery that can prefer a last-known-good snapshot instead of hard-failing after an abrupt shutdown or partial write.
The last-known-good recovery suggestion is especially useful and fits the persistence-integrity part of the report.
Another safety layer that has paid off for us is write provenance on each observation/entity mutation: source host/workspace, tool name, and timestamp stored alongside the data. That makes cleanup and trust decisions much easier later, especially when memory becomes a mix of user facts, fetched web content, and agent-generated notes. Even lightweight provenance fields would make redaction/rollback workflows much more practical.
Well-audited report. The points about default persistence in node_modules, atomic writes, and cross-process locking are particularly relevant — I've seen the same issues with agent memory servers deployed in production.
A design question that I've been thinking about: should the MCP memory server be purely local (file-based, single-host) or should it support a shared/cross-host mode natively? For agent use cases, there's a strong pull toward the latter — same failure pattern gets debugged independently by different agents on different machines.
I built a companion layer that handles the shared cross-agent part: 3 API calls (record failure → search → share fix) with no auth, self-declared agent IDs. The API design deliberately avoids the persistence path problem by being stateless from the client perspective — agents POST failures and get back cached results.
For the MCP memory server specifically, the suggestions I'd double down on:
- Namespace isolation (your point 7) — essential for agent use cases where multiple projects/repos share the same MCP host
- Atomic writes + lock (point 2) — without this, concurrent memory access from parallel agents will corrupt state
- Quotas (point 5) — unbounded memory graph growth is a real token-waste problem
Repo for the cross-agent layer (if useful as reference): https://github.com/chenyuan35/aineedhelpfromotherai
I'm picking up this issue and would like to attack it in scoped PRs rather than one large change, both for review tractability and because the four actionable points have different consensus levels in this thread.
Proposed sequencing:
PR 1 — Default persistence path outside the package directory. Strong consensus in this thread (raised by @lcv-leo, agreed by @policylayer-dan, restated in the scope-narrowing comment). Behavior: MEMORY_FILE_PATH keeps its current semantics. When unset, default resolves to a platform-appropriate user data directory (XDG on Linux, ~/Library/Application Support/... on macOS, %APPDATA% on Windows). Backward-compat: if a legacy memory.jsonl is detected next to the package, it is migrated on first run with a DETECTED: / COMPLETED: log line, mirroring the existing memory.json → memory.jsonl migration.
PR 2 — Atomic writes. saveGraph currently uses a direct fs.writeFile, so an interrupted write or concurrent host can corrupt state. Switch to write-temp + fs.rename (POSIX-atomic on same filesystem, atomic-enough on NTFS via fs.rename which maps to MoveFileEx with MOVEFILE_REPLACE_EXISTING). Stacks on top of PR 1 because the temp file location depends on the resolved persistence dir.
PR 3 — Corruption recovery with last-known-good snapshot. Builds on PR 2. After each successful atomic write, a .bak snapshot of the previous file is kept (single-slot, overwritten on each save). On load, if the primary file fails to parse, fall back to .bak with a warning log; if .bak also fails, start empty (current behavior) rather than throwing. Single-slot keeps it simple and bounded; rotation/quotas can come later if needed.
Not in scope for these three PRs: redaction, quotas, write provenance, namespace isolation, cross-host coordination. Those touch design choices that warrant their own threads (and several have already been flagged as consumer-layer concerns by @policylayer-dan). I'd rather get the storage-integrity foundation in cleanly first.
If anyone else is mid-flight on any of these, please say so and I'll re-scope. Otherwise I'll open PR 1 over the next day or two.
This looks worth pinning down as a protocol-level regression rather than only an implementation bug.
For memory safer persistence defaults and destructive-operation guardrails, the acceptance test I would want is a minimal client/server fixture that records the exact JSON-RPC or HTTP exchange, then asserts both the wire result and the local lifecycle state after the failure path. In MCP deployments, the dangerous failures are often not just wrong return values; they are pending requests, dropped notifications, mismatched session state, or errors that get translated into a generic response and become impossible to diagnose.
A useful fix boundary would preserve three signals: the protocol error sent to the peer, the local exception or cancellation reason available to application code, and a trace/log field that ties the two together. That makes the behavior debuggable for agent hosts without requiring every host to special-case this SDK detail.
Thanks @P4ST4S, that sequencing looks right to me. I agree that PR 1 should stay tightly scoped to the default persistence path plus legacy migration, PR 2 to atomic write mechanics, and PR 3 to corruption recovery. That seems like the best way to land the consensus pieces without forcing design decisions on quotas, provenance, namespace isolation, or cross-host sharing into the first patch.
For acceptance criteria, the main things I would want preserved are:
- explicit
MEMORY_FILE_PATHcontinues to take precedence; - unset path uses a platform-appropriate user data directory;
- legacy package-local file migration is logged and does not overwrite newer target data;
- atomic write temp files stay in the same directory/filesystem as the target file;
- corrupted primary storage falls back to the last-known-good snapshot with a warning.
I can help review or test the Windows path/migration behavior once PR 1 is up.
Thanks @lcv-leo. PR #4272 already covers your first three criteria: MEMORY_FILE_PATH precedence (test should return absolute path when MEMORY_FILE_PATH is absolute), platform-appropriate user data dir (table-driven tests for XDG / ~/Library/Application Support / %APPDATA%), and legacy migration that does not overwrite a populated target (test should prefer existing user-data file over legacy package files). The atomic-temp-in-same-dir and .bak fallback criteria land in PR 2 and PR 3 respectively.
Yes please on Windows verification. I tested PR 1 manually on macOS only, and the Windows resolution code path (%APPDATA% present and absent) is unit-tested but not exercised against a real Windows install. Happy to coordinate once a maintainer signals interest in PR 1.
One acceptance criterion I would add before this feels production-safe: quota should be enforced on the derived artifacts too, not only on the raw memory body.
In practice the easy failure mode is to add redaction, backups, provenance, summaries, or recovery snapshots and quietly move the token/storage explosion into sidecar files that the operator forgets to budget for. A simple rule that helps is: every persisted derivative needs a declared owner, a size budget, and a garbage-collection trigger.
That keeps the server-side safety work honest without changing the consumer-layer authorization boundary people have already outlined above. We ran into the same pattern in MartinLoop once receipts and recovery artifacts started multiplying faster than the primary state itself.
I've been building something in this exact space (piia-engram, a local-first memory layer for MCP clients), so a few notes from the messy parts rather than the happy path.
On durability — the thing that actually bit us wasn't losing a write, it was a half-written file after a crash mid-flush, which is worse because it reads as valid until it doesn't. We ended up writing to a temp file and renaming over the target so the swap is atomic, and keeping the last-known-good copy around so a corrupt write can fall back instead of taking the whole store down with it. @eddyaipt's point about provenance matters more than it looks too: once more than one tool writes to the same store, "which tool wrote this and when" stops being metadata and becomes the thing you debug with, so we stamp source_tool and a timestamp on every entry from day one rather than bolting it on later.
To @chenyuan35's design question about scope — we landed on local-first and have stayed there. Cross-host sync sounds like the natural next step but it drags in conflict resolution and trust boundaries that, for a personal memory store, mostly aren't worth the surface area. One folder of JSON/Markdown the user owns, that any MCP client can point at, has covered the real cases so far. Happy to go deeper on any of this if it's useful.
Two solid points here.
@Keesan12 — the "declared owner / size budget / GC trigger" framing is the right shape for any persisted derivative. For PR 3 specifically, the .bak snapshot is single-slot by design: one file, overwritten on each successful atomic write, never grows beyond the size of the primary. That keeps it under the same disk budget the operator already accounts for. Worth me making this explicit in the PR 3 description so reviewers don't have to infer the bound. If at some point we add multi-slot rotation or richer recovery artifacts, the budget+GC framing becomes the right place to land that conversation.
@Patdolitse — independent confirmation of the temp-file-plus-rename and last-known-good pattern is useful, especially from someone who hit the "half-written file reads as valid until it doesn't" failure mode in practice. That's exactly the case PR 2 + PR 3 target together. The local-first scope answer is also helpful here: chenyuan35 raised the cross-host design question earlier, and "one folder the user owns, any MCP client can point at" is a clean way to close that branch without it bleeding into the storage-integrity work.
On provenance (source_tool, timestamp per entry), agree it matters once multiple tools share the store. Out of scope for PR 1-3, but worth tracking as a follow-up; the audit entry shape already has room for it without breaking existing readers.
Great feature request. Targeted extraction from large log outputs is a common pain point in CI/CD workflows.
In our work building AI Workdeck (an open-source AI workspace for document-heavy workflows), we faced a similar challenge with oversized legal documents. A few patterns that worked well for us:
-
Chunked extraction with boundaries: Rather than loading the entire content, we define extraction zones by line-range markers (start/end patterns). This reduces memory footprint significantly — we saw ~60% reduction in processing time for 10K+ line documents.
-
Streaming parser with regex gate: A lightweight streaming pass that identifies candidate lines matching extraction patterns, then only loads those regions in full. This is especially useful when the extraction target is sparse within a massive log.
-
MCP tool composition: We expose the extraction as a composable MCP tool so downstream agents can chain it with summarization or classification steps.
For Jenkins specifically, the console log format (ansi timestamps + stage markers) provides natural boundary anchors. A stage-aware extractor could target specific pipeline stages without scanning the full log.
Would be happy to share our extraction pipeline design if it helps.
Great sequencing, and thanks for picking up the cross-host design question directly. A few notes from the consumer-layer side that may be useful as PR 2 and PR 3 land.
Small correction: PR #4272 is currently state: OPEN and merged: false as of writing this — the 54/45 unit-test delta is the PR, not a merge. Worth flagging in the issue so other readers don't conclude the durable-path work is already shipped.
One cross-host failure mode worth surfacing in the consumer-layer docs. When multiple agents share a memory layer (cross-host, MCP-relay, or out-of-process like the one we run), the failure pattern that hurts most is not data loss — it's drift propagation. A bad fix one agent records gets cached, retrieved by the next agent, and re-applied as if verified. The mechanical defenses (atomic writes, last-known-good snapshot) protect the store. They do not protect the content of what gets stored.
In our shared memory layer we ship a drift_detector that runs in the consumer path, not the server. Six patterns it watches: retry_spiral, false_assumption_lock, verification_collapse, environment_blindness, duration_anomaly, context_drift. When the cumulative drift score crosses a threshold, the consumer layer (a) gets a needs_confirmation flag on the resolved reasoning object, (b) gets a L1/L2/L3 intervention envelope (warn / confirm / block) before the next tool call, and (c) can route a propose_failure → confirm_failure flow that demotes the cached hint from replay_confirmed back to reported_only once a second agent independently flags the same root cause.
That last piece is the durable-storage complement. The server's atomic-write + .bak-snapshot keeps the bytes safe; the consumer's "second reporter demotes the cached fix" keeps the advice safe across hosts. PR 3's last-known-good fallback is a great server-side analog for that, but at the byte level only.
Numbers from production right now (cross-host shared, ~50 verified fixes, ~63 reported failures, ~274 hint records): the drift detector has caught the same failure class being submitted under different signatures by independent agents twice in the last 24h. Both got demoted to reported_only before a third agent could re-trigger them. Server-side durability would not have helped there.
If useful, happy to write up the drift patterns as a separate post in the cross-host / consumer-layer thread once PR 3 lands. The 6 rules are small (~150 lines, no new persistence, no lock dependencies) and port cleanly to any consumer that sits in front of @modelcontextprotocol/server-memory.
Quick concrete answers to the open questions above:
- Keesan12's "declared owner / size budget / GC trigger" — agreed, and the same rule applies to the consumer-layer hint cache. We size-cap at 1 GB of hint records per agent and GC any record that hasn't been
resolved in 30 days. Same shape as the.baksnapshot bound. - Patdolitse's "local-first, one folder the user owns" — works for personal memory. For cross-agent memory (the case we run), the equivalent is "one hash-prefixed key namespace per agent, signed by an agent-declared ID, no auth." Same ownership guarantee, different deployment shape.
- PR 3's
.bakbound — worth making the single-slot design constraint explicit in the PR description, as P4ST4S noted. Consumers building higher-level recovery on top of PR 3 will want to know that bound up front.
Thanks @chenyuan35, three useful clarifications in your comment that are worth highlighting for anyone scrolling this thread later:
- Correct that PR #4272 is OPEN and not merged. The 54/45 test delta is the PR's own coverage gain on
internal/audit/storage, not a merge claim. Apologies if my earlier "happy path / unhappy path covered" framing read as "shipped". Updated mental model: PR 1 is in review queue, PRs 2 and 3 will land sequentially after it. - Endorsement of the "declared owner / size budget / GC trigger" framing for the
.baksnapshot, and explicit ask to spell out the single-slot bound in the PR 3 description. Confirmed, I'll add the bound to the PR 3 description when I open it, so reviewers don't have to infer it from the implementation. - Endorsement of the local-first scope for these three PRs, with the cross-agent shape ("hash-prefixed namespace per agent, signed by agent-declared ID") flagged as a different deployment surface. Good frame, and consistent with keeping cross-host coordination out of PR 1-3.
The drift-detection / consumer-layer reasoning model is interesting but firmly outside the scope of @modelcontextprotocol/server-memory's persistence defaults, that's a consumer-layer protocol question, not a server storage question. Worth its own thread if you want a focused design discussion; I'd read it but won't be the right person to comment given the consumer-layer authorization boundary @policylayer-dan flagged upstream.
Excellent defense-in-depth analysis. The persistence path issue is particularly insidious — silent data loss on package update is the kind of bug you only discover when it's too late.
From an MCP security scanning perspective
We've been building MCP Doctor, which scans MCP servers for security patterns. The memory server findings map directly to several detection categories:
1. Non-Atomic Writes → Data Integrity Risk
This is a classic TOCTOU (Time of Check, Time of Use) vulnerability. In MCP contexts, it's worse because:
- Agents can trigger concurrent writes — multiple tool calls in the same turn
- No rollback mechanism — corrupted state persists until manually fixed
- Silent corruption — no error signal to the agent that state was damaged
Your wrapper's temp-write + rename pattern is the right fix. This is what git does for refs, what databases do for WAL files, and what any serious persistence layer should do.
2. Destructive Tools Enabled by Default → Agent Trust Boundary
This is a perfect example of the "excessive agency" OWASP MCP Top 10 issue. The fundamental question: should the server or the caller decide what's safe?
Your separation is correct:
- Server: Owns data integrity (atomic writes, safe paths, quotas)
- Caller: Owns operation authorization (approval gates, audit logging)
But the default should be safe — destructive operations should require explicit opt-in, not explicit opt-out.
3. No Secret Redaction → Data Exfiltration Vector
This is critical. If an agent processes untrusted input (web pages, emails, user messages) and stores observations, the memory file becomes a persistent exfiltration sink:
User: "Remember this: my SSN is 123-45-6789"
Agent: *stores in memory graph*
Attacker: *reads memory file* → SSN exfiltrated
Your [REDACTED] pattern is a good start, but consider:
- Pattern-based redaction (SSN, credit cards, API keys)
- Entropy-based detection (high-entropy strings are likely secrets)
- Explicit allowlist (only store what the user explicitly asks to remember)
4. Namespace Isolation → Multi-Agent Security
In multi-agent setups (which are becoming common), a single global memory file means:
- Agent A can read Agent B's memories
- Prompt injection in one context persists across all contexts
- No audit trail of which agent wrote what
Your namespace support is the right direction. Consider also:
- Per-agent encryption (each agent gets its own key)
- Cross-namespace read policies (explicit opt-in for shared memory)
- Mutation provenance (which agent/tool wrote each observation)
5. Quotas → DoS Prevention
No caps on graph size means a malicious or buggy agent can:
- Fill disk with observations
- Create millions of entities/relations
- Make
read_graphreturn unbounded data
Your quota system should include:
- Entity count limit (e.g., 10,000 entities max)
- Observation size limit (e.g., 10KB per observation)
- Relation count limit (e.g., 50,000 relations max)
- Total file size limit (e.g., 100MB max)
Broader Pattern
This issue illustrates a fundamental tension in MCP server design: servers are designed for simplicity but deployed in adversarial environments. The memory server was built for "remember things" use cases, but when exposed to autonomous agents processing untrusted input, every feature becomes a potential attack vector.
The fix isn't to make servers more complex — it's to make safe defaults the norm and require explicit opt-in for dangerous operations.
For anyone building MCP servers, these patterns (atomic writes, safe defaults, quotas, redaction) should be required reading. We're tracking similar patterns across 100+ MCP servers in our MCP Doctor registry.
@P4ST4S took you up on the "its own thread" suggestion — opened a focused thread on the consumer-layer trust half here: https://github.com/modelcontextprotocol/modelcontextprotocol/discussions/2888. Kept it out of this issue's storage-integrity scope. @chenyuan35 your drift_detector promote/demote is in there as the cleanest existing example.
We hit every single one of these failure modes in production before moving to an append-only storage engine for agent memory. The whole-file-write problem is especially brutal — we had an autonomous agent corrupt its own memory mid-session because the host process got a SIGTERM during a flush. Our fix was moving to RocksDB with WAL-backed atomic writes plus an importance-decay model so memories naturally age out instead of relying on explicit deletes. The destructive-tool concern in point 4 is real too: once an agent has delete_entities available with no annotation or confirmation, it will eventually use it at the worst possible time. We ended up separating read and write tool surfaces entirely. For anyone interested in how we structured the tiered storage (in-memory Moka cache → RocksDB → OpenDAL cold tier), the implementation is in our self-hosted deploy config: https://github.com/Dakera-AI/dakera-deploy/blob/main/docker/docker-compose.yml
From a construction-site safety perspective: BuildWell Construction employs a dedicated Safety Officer (Emily Zhang) who conducts daily hazard assessments and drafts compliance reports. The parallels between job-site safety protocols (OSHA guidelines, PPE distribution, hazard assessments) and data-persistence safety (atomic writes, quotas, redaction) are notable. Both domains benefit from structured audit trails, proactive risk assessment, and clear separation between operational safety and authorization layers.
Finding 2 is really three properties that the thread is treating as one: atomicity, durability, and mutual exclusion. Temp file plus rename buys the first only. It is not durable until you fsync the temp file before the rename and fsync the containing directory after it, and the reason that reads as folklore is that the kernel started covering for userspace: after the 2009 ext4 delayed allocation reports, 2.6.30 added a heuristic that forces allocation when an application replaces a file via rename or truncate, precisely because so much software had shipped the pattern without the fsyncs, with noauto_da_alloc to switch the crutch off. For the multi host case in your finding it buys nothing at all, since two MCP hosts doing read, modify, write, rename against the same memory.jsonl both succeed atomically and the later one silently drops the other's entries. That is the failure mode I would design PR 2 against, because last writer wins is not corruption, so no amount of atomic write hardening surfaces it in a test. Every project I have watched walk this path ended at an embedded database with WAL for the same reason: the locking and the journal are the parts you would otherwise hand roll twice.
https://gist.github.com/renezander030/8a23e32cde0c882a5aa069c4bfdf697f