openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

[codex] Add MCP write audit log

Open Felyx-Fu opened this issue 6 months ago • 5 comments

Summary

  • add a persistent mcp_writes table to the memory-tree SQLite schema
  • record successful and failed MCP write tool calls from memory.store, memory.note, and tree.tag
  • add internal-only openhuman.mcp_audit_list RPC with limit, offset, since, client, tool, and success filters
  • thread McpSession::source_type() into MCP write dispatch so audit rows and write provenance use the connected client label

Closes #2536.

Validation

  • cargo test mcp_audit --lib
  • cargo test summarize_write_args --lib
  • cargo test extract_document_id --lib
  • cargo test schema_for_rpc_method_finds_internal_mcp_audit_list --lib
  • cargo test rpc_method_from_parts_does_not_expose_internal_mcp_audit_list --lib
  • pnpm format:check
  • pnpm rust:check
  • pnpm typecheck
  • pnpm lint (passes with existing warnings)
  • pnpm --dir app run lint:commands-tokens
  • git diff --check

Summary by CodeRabbit

  • New Features
    • Audit logging for write operations (memory updates, notes, tags) with a queryable history.
    • Queryable filters: client, tool name, timestamp range, pagination, and success status.
    • View which client performed each write and any associated error messages.
    • Summaries redact sensitive write payloads while preserving relevant metadata.
    • Tool behavior now respects session/source context and configured write policies, surfacing denials as client-visible errors.

Review Change Stack

Felyx-Fu avatar May 24 '26 13:05 Felyx-Fu

[!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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c0e0f58e-8043-4bc1-b39a-47ad5859ce36

📥 Commits

Reviewing files that changed from the base of the PR and between 52dfff43011a77ddecd4c023a2ebce46d87461b8 and fda912ae263b939789dafc7e20c2af4253d3e4c3.

📒 Files selected for processing (1)
  • src/openhuman/mcp_audit/schemas.rs

📝 Walkthrough

Walkthrough

Adds persistent MCP write audit logging: new record types, SQLite storage and query API, an internal-only RPC mcp_audit.list, module wiring, and tool-dispatch changes to thread client provenance and record write outcomes.

Changes

MCP Audit Logging System

Layer / File(s) Summary
Audit Record Data Schema
src/openhuman/mcp_audit/types.rs
Defines NewMcpWriteRecord, McpWriteRecord, and McpWriteListQuery types with fields for timestamp, client/tool metadata, redacted arguments, outcome, and optional filters.
Audit Persistence Layer
src/openhuman/mcp_audit/store.rs
Implements record_write to insert audit rows into SQLite mcp_writes table and list_writes to query with optional filters for client, tool, timestamp, and success status; includes normalization helpers, UTF‑8-safe truncation, and unit tests.
RPC Handler & Query Endpoint
src/openhuman/mcp_audit/schemas.rs
Defines the internal-only mcp_audit.list controller schema with pagination/filter inputs, implements handle_list to deserialize params and call store::list_writes, and includes unit/integration tests for registration and response content.
Module Organization & Controller Registration
src/openhuman/mcp_audit/mod.rs, src/openhuman/mod.rs, src/core/all.rs, src/core/all_tests.rs
Adds the mcp_audit module with re-exports of store/types and schema lists, exposes the module in the crate index, registers internal controllers in the internal-only registry, and adds tests ensuring the controller is internal-only.
Tool Dispatch Integration & Audit Recording
src/openhuman/mcp_server/protocol.rs, src/openhuman/mcp_server/tools.rs
Threads session.source_type()/client_info into call_tool, updates call_tool/dispatch_write_tool to load config, enforce write policy, validate/inject params, extract document ids, and record success/failure NewMcpWriteRecord entries with redacted/summarized args; includes tests for redaction, denial auditing, and client provenance.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Protocol as MCP Protocol
  participant CallTool as call_tool()
  participant DispatchWrite as dispatch_write_tool()
  participant MemPut as openhuman.memory_doc_put
  participant AuditStore as Audit Store

  Client->>Protocol: tools/call (write tool)
  Protocol->>CallTool: call_tool(name, args, client_info)
  CallTool->>CallTool: load_write_config()
  CallTool->>CallTool: enforce_write_policy_for_config()
  CallTool->>CallTool: inject source_type = client_info
  CallTool->>DispatchWrite: dispatch_write_tool(audit_args, client_info, config)
  DispatchWrite->>MemPut: invoke mapped RPC (e.g., memory_doc_put)
  MemPut-->>DispatchWrite: response (success/failure)
  DispatchWrite->>DispatchWrite: extract_document_id()
  DispatchWrite->>AuditStore: record_write(NewMcpWriteRecord)
  AuditStore-->>DispatchWrite: row id
  DispatchWrite-->>CallTool: result
  CallTool-->>Protocol: JSON response
  Protocol-->>Client: tools/call result

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • tinyhumansai/openhuman#2306: Modifies src/openhuman/mcp_server/tools.rs in the write-tool dispatch path—related to the audit dispatch wiring in this PR.
  • tinyhumansai/openhuman#2332: Threads session provenance into tools::call/call_tool, which this PR consumes for audit provenance.
  • tinyhumansai/openhuman#2316: Also modifies mcp_server/tools.rs around call_tool/dispatch write behavior and is code-adjacent to these changes.

Suggested reviewers

  • senamakel

Poem

🐰 I nibble bytes and store the tale,

timestamps, client, and tool set sail.
Quiet rows in SQLite keep,
Who wrote what while others sleep.
A tiny audit hop—then back to the dale.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 49.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '[codex] Add MCP write audit log' clearly and concisely summarizes the main change: introduction of an MCP audit logging feature.
Linked Issues check ✅ Passed The pull request implements all primary coding objectives from #2536: persistent mcp_writes table schema [#2536], record insertion for write tools with args_summary [#2536], read-only RPC openhuman.mcp_audit_list with filters [#2536], client_info threading via source_type [#2536], and unit tests for insertion/filtering/ordering [#2536].
Out of Scope Changes check ✅ Passed All changes are directly related to MCP write audit logging. The modifications to protocol.rs and tools.rs thread session source_type into dispatch, store.rs/types.rs/schemas.rs implement the audit infrastructure, and core/all.rs wires the internal RPC—all in scope per #2536.

✏️ 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 24 '26 13:05 coderabbitai[bot]

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan? Reviews resume once this user has a paid seat and their Git account is linked in Qodo. Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? These require an Enterprise plan - Contact us Contact us →

qodo-code-review[bot] avatar May 24 '26 13:05 qodo-code-review[bot]

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan? Reviews resume once this user has a paid seat and their Git account is linked in Qodo. Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? These require an Enterprise plan - Contact us Contact us →

qodo-code-review[bot] avatar May 24 '26 14:05 qodo-code-review[bot]

Review/CI triage note: this red run is a real compile failure, not the earlier checkout/GHCR infra class. The current first blocker is in src/openhuman/mcp_server/tools.rs: load_write_config(...) -> Result<Config, ToolCallError> matches Ok(config) => config, but that arm needs to return Ok(config). That single E0308 failure is enough to fan out into Rust Quality, core tests, Tauri build, and E2E failures.\n\nAlso flagging reviewer context: this overlaps with draft #2553 for #2536. If this PR stays canonical, I would first fix the compile error and then ask the #2553 author/reviewer to either close the draft or explicitly keep it as an alternative design thread so reviewers do not review two divergent audit-log implementations in parallel.

YOMXXX avatar May 24 '26 15:05 YOMXXX

Author of #2553 (the parallel draft for #2536) here — flagging coordination context, not pushing for territory.

RFC design context (from the lazy-consensus comment on #2536):

  • Q1 = A — colocated in the existing memory-tree SQLite, additive CREATE TABLE IF NOT EXISTS (no separate migration step). ✅ both PRs picked this.
  • Q2 = A — best-effort audit; insert failures are logged but never propagate to the underlying write. ✅ both PRs picked this.
  • Q3 = A — no auto-prune in v1; revisit once we see usage volume.
  • Q4 = A (internal RPC only, deferred in #2553) — the openhuman.mcp_audit_list surface you've shipped in this PR.

So we're aligned on Q1–Q3. The split is Q4: my draft deliberately deferred the query RPC pending ratification (kept a recent() helper as #[cfg(test)] only); yours commits to A (internal-only RPC, no MCP-client-side exposure) in v1. That's a reasonable read of the lazy consensus.

One safety detail worth checking that bit me in #2553: error_message truncation needs to land on a UTF-8 char boundary, not a raw byte offset. A 4-byte char like 🦀 sliced mid-codepoint produces invalid UTF-8 and SQLite happily stores garbage. The pattern I used:

let mut end = ERROR_MESSAGE_MAX_BYTES;
while end > 0 && !msg.is_char_boundary(end) {
    end -= 1;
}
record.error_message = Some(msg[..end].to_string());

Plus a regression test (record_handles_multibyte_truncation_safely) that repeats 🦀 past the cap and asserts is_char_boundary(stored.len()). Worth checking your store doesn't have the same naive-slice risk.

On the "writes vs write attempts" question @YOMXXX raised: I'd argue both should be recorded. Failure rows are the abuse-detection signal — a misbehaving MCP client repeatedly bouncing off the policy gate or doc_put validation will show up as a burst of success = false rows that pure "successful write history" framing would miss. Both PRs already do this; just worth ratifying explicitly so the RPC docs match.

Happy to close #2553 once @senamakel picks the canonical path. Either outcome works — flagging this so the design context from the RFC thread doesn't get lost in the handoff.

justinhsu1477 avatar May 24 '26 22:05 justinhsu1477

@justinhsu1477 Agreed on both points, thanks for carrying the #2553/RFC context over here.

I tightened this up in the latest commits:

  • error_message is now capped at 1 KiB in mcp_audit::store::record_write, and truncation walks back to a UTF-8 char boundary before slicing. I added record_handles_multibyte_error_truncation_safely with a repeated \u{1F980} payload to lock that down.
  • The mcp_audit.list controller schema now explicitly describes the rows as write attempts, including successful writes plus rejected/failed attempts, and clarifies that success_only filters for succeeded attempts.

I also fixed the load_write_config Ok(config) compile regression and updated the audit store to use the current memory_store::chunks::store connection path after the main-branch memory refactor.

Validation on this branch:

  • cargo fmt --manifest-path Cargo.toml --check
  • git diff --check
  • cargo check --manifest-path Cargo.toml -p openhuman --lib
  • cargo test --manifest-path Cargo.toml -p openhuman --lib record_handles_multibyte_error_truncation_safely -- --nocapture

Felyx-Fu avatar May 25 '26 05:05 Felyx-Fu