feat(mcp): add memory.store and memory.note write tools
Summary
- Add
memory.storeMCP tool: creates memory documents from content with configurable namespace and tags, routing to the existingdoc_putRPC - Add
memory.noteMCP tool: creates annotation documents linked to existing chunks viametadata.annotates_chunk_id, also routing throughdoc_put - Add
enforce_write_policy()for write-specific security gating (distinct from read/act for audit clarity) - Add
dispatch_write_tool()with structuredtracing::info!audit logging (tool, chunk_id, client fields) - Both tools set
source_type = "mcp"for provenance tracking - 11 new unit tests covering param validation, defaults, slug generation, and error cases
Closes #2269
Test plan
- [x]
cargo check -p openhuman --libpasses - [x]
cargo test -p openhuman --lib mcp_server::tools— all 40 tests pass (29 existing + 11 new) - [x]
cargo fmt --allapplied - [x] CI checks pass on PR
🤖 Generated with Claude Code
Summary by CodeRabbit
-
New Features
- Added memory.store to save memories (title + content) with automatic namespace, deterministic key generation and tagging support
- Added memory.note to attach notes to specific memory chunks with automatic key generation and linked metadata and content structure
-
Tests
- Expanded unit tests covering the new memory tools, argument validation (required fields and unknown-field rejection), defaults, and metadata/content construction
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
📝 Walkthrough
Walkthrough
Adds two MCP write tools—memory.store and memory.note—registered to openhuman.memory_doc_put. Both enforce a write gate, validate inputs against JSON schemas, build RPC parameters with deterministic keys/slugs, dispatch via a dedicated write path with audit logs, and include unit tests.
Changes
Memory Write Tools
| Layer / File(s) | Summary |
|---|---|
Tool declarations and schemas src/openhuman/mcp_server/tools.rs |
Defines allowed-argument keys and registers memory.store / memory.note in the base tool catalog mapped to openhuman.memory_doc_put; adds JSON schemas that require specific fields and disallow extra properties. |
Tool dispatch routing src/openhuman/mcp_server/tools.rs |
call_tool now recognizes the new tools, enforces write-policy (Act), validates controller params, and routes to a dedicated write dispatch helper. |
RPC parameter construction src/openhuman/mcp_server/tools.rs |
build_rpc_params adds branches for both tools: required-field validation, namespace defaulting for memory.store, deterministic key generation, tags forwarding, note document composition, and metadata.annotates_chunk_id for notes. |
Write enforcement and dispatch src/openhuman/mcp_server/tools.rs |
Adds enforce_write_policy to gate write operations and dispatch_write_tool to invoke openhuman.memory_doc_put, map outcomes, and emit structured audit logs. |
Slug generation helper src/openhuman/mcp_server/tools.rs |
slug_from normalizes titles into deterministic, URL-safe slugs with lowercasing, non-alphanumeric→hyphen conversion, hyphen collapsing, truncation, and hash-based fallback for non-ASCII/empty inputs. |
Tests / protocol expectations src/openhuman/mcp_server/protocol.rs, src/openhuman/mcp_server/tools.rs |
Updates tools/list expectation to include the new tools; adds tests for RPC-param construction/validation, namespace/tag handling, unknown-argument rejection, constructed document fields, and slug_from behavior. |
Sequence Diagram(s)
sequenceDiagram
participant Client
participant MCP_Server
participant WritePolicy
participant RPC_Builder
participant MemoryService
Client->>MCP_Server: tools.call(memory.store | memory.note, args)
MCP_Server->>WritePolicy: enforce_write_policy(controller, ToolOperation::Write)
WritePolicy-->>MCP_Server: allow/deny
MCP_Server->>RPC_Builder: build_rpc_params(tool, args)
RPC_Builder-->>MCP_Server: rpc_params
MCP_Server->>MemoryService: openhuman.memory_doc_put(rpc_params)
MemoryService-->>MCP_Server: success/error
MCP_Server-->>Client: result (including audit/log entry)
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related issues
- tinyhumansai/openhuman#2317: This PR sets
source_type = "mcp"while the issue proposesmcp:<client>provenance, so the change is closely related to threading clientInfo into write-tool RPC construction.
Possibly related PRs
- tinyhumansai/openhuman#1760: Extends the same MCP stdio tool-discovery/call plumbing and is a likely predecessor to these write-tool changes.
Suggested reviewers
- senamakel
Poem
A rabbit hops through code and logs,
Two tools to store and note the thoughts.
Slugs march tidy, hashes keep the pace,
Memory finds a stable place. 🐇✨
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The PR title clearly and specifically summarizes the main change: adding two new MCP write tools (memory.store and memory.note) to the codebase. |
| Linked Issues check | ✅ Passed | The PR implements the primary objectives from issue #2269 Phase 1: adds memory.store and memory.note write tools with provenance (source_type=mcp), security gating (enforce_write_policy), and audit logging (dispatch_write_tool). Defers tree.tag and destructive operations as planned. |
| Out of Scope Changes check | ✅ Passed | All changes are directly scoped to the linked issue objectives: memory.store and memory.note tools, write-path scaffolding, slug generation, parameter validation, and unit tests. No unrelated modifications detected. |
| Docstring Coverage | ✅ Passed | Docstring coverage is 90.00% which is sufficient. The required threshold is 80.00%. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Credit to @justinhsu1477 for the thorough RFC-style issue (#2269) — the architecture questions, proposed tool surface, and phased rollout plan made scoping this first wave (memory.store + memory.note) much cleaner. The provenance and audit logging patterns follow directly from the issue's Q2/Q4 proposals.
@Liohtml — thanks for picking this up so fast, and for the explicit RFC credit.
Quick mapping of your implementation against the four open questions in #2269, mostly so I can verify I'm reading the diff right and so anyone landing here later sees the trade-off space:
- Q1 (multi-process write path) — you route through the existing
doc_putRPC, which is effectively Option A from the RFC (daemon is the sole writer). Cleanest path for v1 and side-steps Option C's WAL-coordination work. - Q2 (provenance) —
metadata.source_type = "mcp"on each chunk. Schema-light, no migration. - Q3 (
SecurityPolicy) — separatingenforce_write_policy()from the read enforcer is a nicer split than tunnelling both through the same gate; matches what the RFC was hoping for under "default-allow + audit". - Q4 (audit log) — structured
tracing::info!instead of a newmcp_writestable. Reasonable for v1; if maintainers later want queryable history this is the easiest place to swap a SQLite-backed sink in.
Two follow-ups I'd happily own so the RFC closes out cleanly:
tree.tag— the third tool the RFC proposed. Want me to spin it up as a follow-up PR using yourenforce_write_policy+dispatch_write_toolscaffolding once this one lands, so it merges cleanly on top?client_infopropagation — RFC Q2 also suggested capturing the calling MCP client name (e.g."mcp:Claude Desktop"from theinitializepayload) on each chunk, so a write from Claude Desktop reads differently from one written by Cursor. Doesn't need to block this PR — happy to file as a separate issue once this lands if maintainers want it.
Happy to do a deeper line-level review if it's useful.
@justinhsu1477 Great mapping — you're reading the implementation exactly right on all four questions.
Re your follow-ups:
tree.tag— yes, please! Theenforce_write_policy+dispatch_write_toolscaffolding is designed to be additive, so a follow-up PR on top should be clean. Happy to review it.client_infopropagation — agreed this should be a separate issue. Theinitializepayload'sclientInfois the right source; the currentsource_type = "mcp"is a placeholder that your follow-up would refine to"mcp:Claude Desktop"etc.
A deeper line-level review would absolutely be useful if you have the time — especially around the dispatch_write_tool → doc_put RPC parameter assembly, since you know the memory schema better than anyone.
@Liohtml — green light on tree.tag ack'd, both follow-ups are now up:
- #2316 —
tree.tagPR layered on top of this branch. Reusesenforce_write_policy+dispatch_write_toolunchanged; +242 LoC net (the new dispatch arm, thetree_tag_schema, thebuild_rpc_paramsbranch, a smallrequired_non_empty_string_arrayhelper next tooptional_string_array, and 8 unit tests covering each failure path). MarkedDepends on #2306and will rebase cleanly when this lands. - #2317 —
client_infopropagation filed as a separate issue. Includes the proposedmcp:<normalized-name>shape onsource_typeplus the back-compat"mcp"fallback whenclientInfo.nameis absent / empty, so any client predating this stays on the current behaviour.
For the deeper line-level look at dispatch_write_tool → doc_put parameter assembly: I'd rather sit with the second CodeRabbit round here first so the review lands against the version heading for merge, instead of churning on in-flight code. Will circle back after that.
@senamakel #2306 当前 checks 24 success / 2 skipped / 0 pending / 0 failure,CodeRabbit approved,review threads 0 unresolved。这个是 MCP write tools 的 Phase 1(memory.store / memory.note),麻烦再看一下。
@graycyrus — quick technical note on the [critical] flag against dispatch_write_tool:
I think the read may have skipped the line right above the match arm. build_rpc_params runs before the match in call_tool, not inside any of the arms:
// src/openhuman/mcp_server/tools.rs (current PR HEAD)
pub async fn call_tool(name: &str, arguments: Value) -> Result<Value, ToolCallError> {
let spec = ...;
let params = build_rpc_params(spec.name, arguments)?; // ← runs first
match spec.name {
...
"memory.store" | "memory.note" => {
enforce_write_policy(spec.name).await?;
validate_controller_params(&spec, ¶ms)?;
return dispatch_write_tool(spec.name, ¶ms).await;
// ↑ ¶ms, not raw `arguments`
}
...
}
}
So by the time dispatch_write_tool is reached, params already carries the slug-based key, source_type = "mcp", the default namespace = "mcp", and (for memory.note) the metadata.annotates_chunk_id linkage. Those transformations aren't dead code — they're exactly what memory_doc_put ends up receiving via the params.clone() inside dispatch_write_tool.
The existing tests in this PR pin that behaviour:
memory_store_defaults_namespace_to_mcpasserts the built params havenamespace == "mcp",source_type == "mcp", and amcp-store-<slug>key.memory_note_builds_annotation_documentasserts the built params include themetadata.annotates_chunk_idlinkage.
Both pass at the current head. If the dispatch were sending raw client args, neither would.
—
That said, the [major] memory.note upsert-vs-append note (line 680) is correct and worth addressing before merge: keying solely on chunk_id does mean re-annotating the same chunk silently overwrites the prior note. Two clean ways through:
- Mix a short content/timestamp hash into the key (
mcp-note-{chunk_id}-{hash8(note_text)}) so the tool is genuinely append-style. - Update the description from "Append a note" to "Set a note" if single-note-per-chunk is the intent.
Either resolves the contract — happy to take a hint on the preferred direction so the fix lands consistently across memory.note (here) and tree.tag (#2316).
@graycyrus Thanks for the thorough review — addressed both findings:
[critical] build_rpc_params bypassed — as @justinhsu1477 noted, build_rpc_params runs at line 435 before the match at line 437, so params already contain the slug key, namespace default, and source_type = "mcp" by the time dispatch_write_tool receives them. The code flow is: build_rpc_params(name, raw_args) → match { "memory.store" | "memory.note" => dispatch_write_tool(name, ¶ms) }. No dead code.
[major] note key collision — valid catch! Fixed in c40cbae2: memory.note key is now mcp-note-{chunk_id}-{content_hash} (8 hex chars from SHA-256 of the note text). Multiple notes on the same chunk get distinct keys. Test updated to verify.
Minor: logging inconsistency — also fixed: dispatch_write_tool now uses tracing exclusively (was mixing log::warn/log::error with tracing::info).
Minor: enforce_write_policy — agreed it's currently identical to enforce_act_policy. Keeping it as a named function for now so a future ToolOperation::Write variant can be introduced without touching call sites. Happy to merge them if maintainer prefers.
Security & Robustness Review — Final Verdict
Really solid work on this PR, @Liohtml (and @justinhsu1477 for the thorough back-and-forth in review). The multi-layer validation pattern (MCP allowlist → RPC schema → doc_put storage layer), the secret detection inherited from the memory domain, parameterized SQL, and the 11 unit tests covering edge cases — all of this is well-considered. The slug_from helper with Unicode fallback hashing and the content-hash fix for memory.note key collisions show good attention to detail. The iterating on CodeRabbit and maintainer feedback has been clean.
Overall: this is in good shape to merge. The foundation is sound.
That said, after a deeper security-focused read, here are a few hardening items worth addressing — either in this PR or as fast follow-ups:
Should fix before merge
- Content size limit on
memory.store—build_rpc_paramsvalidates thatcontentis a non-empty string, but there's no max-length cap at the MCP layer. A misbehaving MCP client could store arbitrarily large documents. Thedoc_putstorage layer doesn't enforce one either. A reasonable cap (e.g. 32KB or 64KB) inbuild_rpc_paramswould be cheap insurance — matches the existing pattern of explicit rejection over silent clamping.
Recommended follow-ups (not blocking)
-
ToolOperation::Writeas a distinct security gate —enforce_write_policy()currently delegates toToolOperation::Act, which means users can't independently control "allow MCP writes but block subagent runs" (or vice versa). Fine for now since the autonomy + rate-limit gate covers it, but worth filing as a follow-up so the permission model can grow with the surface area. -
No per-write user notification — MCP spec doesn't have a confirm primitive, so an LLM connected via MCP can silently write/overwrite memories without the user seeing anything. The
tracing::info!audit log exists but only shows in logs. A UI-side notification (even a lightweight snackbar like "Claude Desktop stored a memory") would give users visibility. This is a UX concern more than a code concern — separate issue territory. -
Write-specific rate limiting — The
Actpolicy'smax_actions_per_hourapplies, but there's no write-specific throttle. A misbehaving client could fill the memory tree with noise up to the shared limit. Consider whether writes deserve a tighter or separate budget. -
Multi-process write path (Q1 from #2269) — The PR routes through
doc_putwhich uses SQLite WAL, so data integrity is fine. But if the desktop daemon and a stdio MCP subprocess both write, the daemon's in-memory caches andevent_busemissions could go stale. Worth documenting explicitly — even if the answer is "SQLite WAL handles persistence; cache staleness is acceptable until next read."
None of these are "stop the merge" level — they're "harden in the next iteration" level. The real residual risk isn't injection or corruption (that's well-covered), it's a rogue LLM silently filling memory with noise and the user not knowing. The content size limit is the one I'd squeeze in before merge; the rest can be follow-up issues.
Nice work overall — the scaffolding here (enforce_write_policy, dispatch_write_tool, the validation helpers) sets up a clean foundation for tree.tag in #2316 and future write tools. 👍
@graycyrus Thanks for the thorough security review — really appreciate the depth.
Fixed before merge (cdd58180):
- Added 64KB content size limit on both
memory.storeandmemory.noteinbuild_rpc_params. Rejects with a clear error message including actual vs limit sizes. Test added.
Acknowledged as follow-ups (not blocking):
ToolOperation::Writeas distinct gate — agreed, will file when the surface grows beyond store/note- Per-write user notification — UX concern, separate issue territory
- Write-specific rate limiting — good idea for a tighter budget
- Multi-process write path documentation — SQLite WAL handles persistence; cache staleness is acceptable and documented in #2269's Q1 resolution
All 48 MCP tool tests pass.
Status update: the current red frontend/i18n checks on this PR are from a main-side German locale parity gap, not from this PR's MCP Rust changes. I reproduced the failure on latest upstream/main: German was missing 20 English keys, which caused pnpm i18n:check, I18nContext.test.tsx, and coverage.test.ts to fail.\n\nOpened #2470 to fix the German locale gap. Once #2470 lands, rerun #2306 checks. The remaining non-CI blocker is the stale CHANGES_REQUESTED review decision from earlier reviews; all review threads are resolved, so after checks are green this should just need a fresh review/dismissal from the reviewer.
@graycyrus Heads up: #2470 is now green and ready for review/merge. Once it lands on main, #2306 should just need a CI rerun plus a fresh review/dismissal of the stale CHANGES_REQUESTED state. I am not rerunning #2306 yet because the German i18n fix is not on main, so the same frontend/i18n checks would likely fail again.
@Liohtml — nice job on the content-size cap (cdd58180). And kudos for the patience with this review cycle — landing the foundation here makes #2316 a trivial rebase on top.
Looking forward to merge once @YOMXXX's #2470 clears the German-locale CI noise.
I prepared and validated a sync branch for this PR, but cannot push directly to Liohtml:feat/mcp-write-tools from the current YOMXXX credentials (Permission to Liohtml/openhuman.git denied).
Branch available for fast-forward / cherry-pick:
YOMXXX:fix/2306-review-sync- Head commit:
196ca6dc - Includes: merge from current
upstream/main(7fe3dd06) plus a small German i18n fix for missing MCP settings strings.
Validation run locally on that branch:
GGML_NATIVE=OFF cargo test --manifest-path Cargo.toml mcp_server::tools -- --nocapture-> 48 passed, 0 failedpnpm i18n:check-> passed, includingdemissing keys = 0- pre-push with
GGML_NATIVE=OFFcompleted: format check, lint (0 errors / existing warnings), TypeScript compile, Taurirust:check, and command-token lint passed
The previous reviewer findings for the MCP write-tool logic appear resolved by the current branch history. Once Liohtml:feat/mcp-write-tools is advanced to this branch, this PR should be ready for CI rerun and final reviewer approval. cc @graycyrus
@graycyrus All your review findings are resolved (confirmed in your own comments above). Could you dismiss your CHANGES_REQUESTED review so the PR can move forward? Thanks for the thorough security review — it made the code significantly better.
hey @Liohtml same thing as the last pr. just resolve the tests failing in the CI and then all good to go
Status refresh after today's PR babysit pass:
- Latest head:
ce2f3056. - CI is green: all required checks are
SUCCESS; only platform E2E skips remain skipped as expected. - Review threads check via GraphQL shows every code review thread is
isResolved=trueand the prior inline threads are now outdated/resolved. - The remaining blocker appears to be the stale
CHANGES_REQUESTEDreview state from the earlier graycyrus review, after graycyrus later confirmed the findings were resolved/false alarm.
@graycyrus could you dismiss or update the stale changes-requested review when you have a moment? @senamakel the CI issue you flagged appears resolved now.