openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(mcp): add memory.store and memory.note write tools

Open Liohtml opened this issue 6 months ago • 17 comments

Summary

  • Add memory.store MCP tool: creates memory documents from content with configurable namespace and tags, routing to the existing doc_put RPC
  • Add memory.note MCP tool: creates annotation documents linked to existing chunks via metadata.annotates_chunk_id, also routing through doc_put
  • Add enforce_write_policy() for write-specific security gating (distinct from read/act for audit clarity)
  • Add dispatch_write_tool() with structured tracing::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 --lib passes
  • [x] cargo test -p openhuman --lib mcp_server::tools — all 40 tests pass (29 existing + 11 new)
  • [x] cargo fmt --all applied
  • [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

Review Change Stack

Liohtml avatar May 20 '26 08:05 Liohtml

[!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_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to 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 proposes mcp:<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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 20 '26 08:05 coderabbitai[bot]

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 avatar May 20 '26 08:05 Liohtml

@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_put RPC, 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) — separating enforce_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 new mcp_writes table. 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:

  1. tree.tag — the third tool the RFC proposed. Want me to spin it up as a follow-up PR using your enforce_write_policy + dispatch_write_tool scaffolding once this one lands, so it merges cleanly on top?
  2. client_info propagation — RFC Q2 also suggested capturing the calling MCP client name (e.g. "mcp:Claude Desktop" from the initialize payload) 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 avatar May 20 '26 08:05 justinhsu1477

@justinhsu1477 Great mapping — you're reading the implementation exactly right on all four questions.

Re your follow-ups:

  1. tree.tag — yes, please! The enforce_write_policy + dispatch_write_tool scaffolding is designed to be additive, so a follow-up PR on top should be clean. Happy to review it.
  2. client_info propagation — agreed this should be a separate issue. The initialize payload's clientInfo is the right source; the current source_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 avatar May 20 '26 08:05 Liohtml

@Liohtml — green light on tree.tag ack'd, both follow-ups are now up:

  • #2316 — tree.tag PR layered on top of this branch. Reuses enforce_write_policy + dispatch_write_tool unchanged; +242 LoC net (the new dispatch arm, the tree_tag_schema, the build_rpc_params branch, a small required_non_empty_string_array helper next to optional_string_array, and 8 unit tests covering each failure path). Marked Depends on #2306 and will rebase cleanly when this lands.
  • #2317 — client_info propagation filed as a separate issue. Includes the proposed mcp:<normalized-name> shape on source_type plus the back-compat "mcp" fallback when clientInfo.name is 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.

justinhsu1477 avatar May 20 '26 08:05 justinhsu1477

@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),麻烦再看一下。

YOMXXX avatar May 20 '26 10:05 YOMXXX

@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, &params)?;
            return dispatch_write_tool(spec.name, &params).await;
            //                                    ↑ &params, 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_mcp asserts the built params have namespace == "mcp", source_type == "mcp", and a mcp-store-<slug> key.
  • memory_note_builds_annotation_document asserts the built params include the metadata.annotates_chunk_id linkage.

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:

  1. Mix a short content/timestamp hash into the key (mcp-note-{chunk_id}-{hash8(note_text)}) so the tool is genuinely append-style.
  2. 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).

justinhsu1477 avatar May 21 '26 01:05 justinhsu1477

@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, &params) }. 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.

Liohtml avatar May 21 '26 12:05 Liohtml

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

  1. Content size limit on memory.store — build_rpc_params validates that content is a non-empty string, but there's no max-length cap at the MCP layer. A misbehaving MCP client could store arbitrarily large documents. The doc_put storage layer doesn't enforce one either. A reasonable cap (e.g. 32KB or 64KB) in build_rpc_params would be cheap insurance — matches the existing pattern of explicit rejection over silent clamping.

Recommended follow-ups (not blocking)

  1. ToolOperation::Write as a distinct security gate — enforce_write_policy() currently delegates to ToolOperation::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.

  2. 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.

  3. Write-specific rate limiting — The Act policy's max_actions_per_hour applies, 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.

  4. Multi-process write path (Q1 from #2269) — The PR routes through doc_put which 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 and event_bus emissions 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 avatar May 21 '26 18:05 graycyrus

@graycyrus Thanks for the thorough security review — really appreciate the depth.

Fixed before merge (cdd58180):

  • Added 64KB content size limit on both memory.store and memory.note in build_rpc_params. Rejects with a clear error message including actual vs limit sizes. Test added.

Acknowledged as follow-ups (not blocking):

  • ToolOperation::Write as 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.

Liohtml avatar May 21 '26 20:05 Liohtml

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.

YOMXXX avatar May 22 '26 00:05 YOMXXX

@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.

YOMXXX avatar May 22 '26 01:05 YOMXXX

@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.

justinhsu1477 avatar May 22 '26 01:05 justinhsu1477

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 failed
  • pnpm i18n:check -> passed, including de missing keys = 0
  • pre-push with GGML_NATIVE=OFF completed: format check, lint (0 errors / existing warnings), TypeScript compile, Tauri rust: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

YOMXXX avatar May 22 '26 04:05 YOMXXX

@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.

Liohtml avatar May 23 '26 07:05 Liohtml

hey @Liohtml same thing as the last pr. just resolve the tests failing in the CI and then all good to go

senamakel avatar May 23 '26 07:05 senamakel

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=true and the prior inline threads are now outdated/resolved.
  • The remaining blocker appears to be the stale CHANGES_REQUESTED review 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.

YOMXXX avatar May 23 '26 14:05 YOMXXX