Skip to content

Audit Trail

Chris edited this page Dec 1, 2026 · 10 revisions

Audit Trail

memory-journal-mcp includes a high-throughput, symlink-hardened JSONL audit logging subsystem (src/audit/) that records mutating tool invocations, team operations, sensitive resource reads, identity context, timing, and token estimates. Mutating and privileged scopes (write, admin, team, audit) are always logged when enabled, while general read tools are opt-in via --audit-reads.


⚑ Overview & Quick Start

Enable audit logging via CLI flags, environment variables, or the startup configuration file (memory-journal.config.{json,yaml}).

CLI Flags

# Enable JSONL audit logging to a rotating file
memory-journal-mcp --audit-log ./logs/mcp-audit.jsonl

# Also log read-scoped tools and allow up to 20 MB per log file
memory-journal-mcp --audit-log ./logs/mcp-audit.jsonl --audit-reads --audit-log-max-size 20971520

# Disable argument redaction (include tool input parameters in entries)
memory-journal-mcp --audit-log ./logs/mcp-audit.jsonl --no-audit-redact

Environment Variables & Config Keys

CLI Flag Environment Variable Config Key (JSON/YAML) Default Description
--audit-log <path> AUDIT_LOG_PATH auditLog disabled Absolute/relative JSONL file path, or stderr for container streaming
--audit-redact / --no-audit-redact AUDIT_REDACT auditRedact true (redacted) Omit tool input args from written entries by default
--audit-reads AUDIT_READS auditReads false Also log read-scoped tool invocations
--audit-log-max-size <bytes> AUDIT_LOG_MAX_SIZE auditLogMaxSize 10485760 (10 MB) Max file size before rotation (min: 1024 bytes via CLI/env; 0 disables rotation programmatically only)

Note

auditLog, auditRedact, auditReads, and auditLogMaxSize in memory-journal.config.{json,yaml} are startup-only settings (not hot-reloaded on file change). Both the server and the offline CLI subcommand memory-journal-mcp admin audit read AUDIT_LOG_PATH with MEMORY_JOURNAL_AUDIT_LOG as a fallback.

Docker & Container Mode (--audit-log stderr)

For Docker, Kubernetes, and container orchestrators where platform drivers capture standard error, pass --audit-log stderr (AUDIT_LOG_PATH=stderr):

docker run --rm -p 3000:3000 \
  -e AUDIT_LOG_PATH=stderr \
  -e ALLOWED_IO_ROOTS=/app/data \
  -e MCP_AUTH_TOKEN="<strong-random-secret>" \
  -v ./data:/app/data \
  writenotenow/memory-journal-mcp:latest \
  --transport http --port 3000 --server-host 0.0.0.0 \
  --database /app/data/memory_journal.db

Alternatively, bind-mount a log directory (-v ./logs:/var/log/memory-journal) with --audit-log /var/log/memory-journal/mcp-audit.jsonl when shipping logs with Grafana Alloy or Datadog Agent (see examples/observability/).


πŸ“‹ Log Entry Schema

Each line written to the audit log is a self-contained JSON object (AuditEntry, src/audit/types.ts):

{
  "timestamp": "2026-05-30T14:22:10.412Z",
  "requestId": "aud-m2x9k1p-9f4a21c8",
  "sessionId": "b7c4e910-3a2d-4e9b-9c21-1f8e7d6c5b4a",
  "tool": "create_entry",
  "category": "write",
  "scope": "write",
  "user": "alice@example.com",
  "scopes": ["read", "write", "audit"],
  "durationMs": 4,
  "success": true,
  "tokenEstimate": 185,
  "workspaceId": "my-repo",
  "projectNumber": 1
}

Field Reference (15 Fields)

Field Type Description
timestamp string ISO 8601 UTC timestamp of the invocation
requestId string Unique correlation ID (aud-<timestamp-base36>-<8-hex>, or denied-<timestamp-ms> for denied-access records)
sessionId string? HTTP/SSE transport session ID when present
tool string MCP tool name or resource/prompt audit target identifier
category 'read' | 'write' | 'admin' | 'team' | 'audit' Operation category mapped from required OAuth scope
scope string Required OAuth scope (read, write, admin, team, audit)
user string | null OAuth sub claim when authenticated, or null when auth is not enabled
scopes string[] Granted OAuth scopes on the caller's token ([] when unauthenticated)
durationMs number Execution duration in milliseconds
success boolean true if execution succeeded; false on exception or { success: false }
error string? Sanitized error message (present only when success === false)
args object? Scrubbed tool input arguments (omitted when AUDIT_REDACT=true, default)
tokenEstimate number? Estimated response token count (~2.8–4.0 bytes/token by content type)
workspaceId string? Resolved multi-tenant workspace ID associated with the call
projectNumber number? Resolved project number associated with the call

🎯 Scope Logging Matrix

AuditInterceptor (src/audit/interceptor.ts) classifies every operation by its required scope and sensitive-resource sensitivity:

Operation / Scope Examples Logged? Notes
write create_entry, link_entries, import_markdown βœ… Always Recorded with identity, timing, token estimate, and workspace/project scope
admin update_entry, run_auto_prune, merge_tags, team_merge_tags, backup_journal, restore_backup, update_configuration, admin prompts βœ… Always Always captured including failures
team team_create_entry, team_link_entries, memory://team/*, team prompts βœ… Always Both team mutations and sensitive memory://team/* / memory://insights/team-collaboration reads
audit search_audit_log, memory://audit, memory://metrics/users βœ… Always Auditing and sensitive user/log reads are always recorded
read (standard) search_entries, get_recent_entries, get_entry_by_id, standard resources ⚑ Opt-in (--audit-reads) Disabled by default to keep audit logs compact and low-noise

Argument Redaction & Sensitive Field Scrubbing

  • Default Redacted (AUDIT_REDACT=true): Tool input args are omitted from audit entries by default so entry bodies, search queries, and credentials never leak into log streams.
  • Unredacted Opt-In (--no-audit-redact / AUDIT_REDACT=false): Includes scrubbed args (capped at 2048 chars per value after a 4096-char pre-scrub slice, with sensitive secret keys stripped by scrubAuditArgs()).

πŸ”Ž Inspecting Audit Logs

1. memory://audit MCP Resource

When audit logging is active, agents with the audit scope (in authenticated deployments) can read memory://audit (text/plain YAML) over stdio or HTTP. It streams backward from EOF in 64 KB chunks (O(1) chunk buffer) until up to 50 most recent entries are collected (or start-of-file is reached) and returns the session_summary alongside them:

audit_log: ./logs/mcp-audit.jsonl
entries_shown: 2
as_of: 2026-05-30T14:22:15.000Z
session_summary:
  total_tokens: 412
  total_duration_ms: 19
  error_count: 0
  dropped_count: 0
  redact_mode: true

- timestamp: 2026-05-30T14:22:10.412Z
  tool: "create_entry"
  scope: write
  category: write
  duration_ms: 4
  success: true
  token_estimate: 185

You can also scope the resource query with URI parameters:

  • memory://audit?workspace_id=my-repo
  • memory://audit?project_number=1
  • memory://audit?workspace_id=my-repo&project_number=1

2. search_audit_log Tool & CLI admin audit

When the admin tool group is active (requires audit, admin, or full scope under OAuth), query historical recordsβ€”including rotated .1–.5 archivesβ€”via search_audit_log:

Parameter Type Default Description
tool_name string β€” Filter by exact MCP tool name
user string β€” Filter by OAuth sub user identifier
date_range { start?: string, end?: string } β€” Filter by ISO 8601 start/end timestamps
status boolean β€” true for successful calls, false for failures (success alias accepted)
category 'read' | 'write' | 'admin' | 'team' | 'audit' β€” Filter by operation category
limit integer (1–1000) 100 Maximum matching entries to return (newest first)
workspace_id string β€” Filter by workspace (* disables workspace filtering)
project_number integer β€” Filter by project number

From the command line without starting an MCP session, inspect logs via:

MEMORY_JOURNAL_AUDIT_LOG=./logs/mcp-audit.jsonl memory-journal-mcp admin audit --limit 25

πŸ’Ύ Storage, Rotation & Security Hardening

AuditLogger (src/audit/audit-logger.ts, src/audit/audit-file-helpers.ts) is non-blocking and non-throwing so log I/O never stalls MCP tool responses:

  • Async Ring Buffering: Buffers up to 50 entries (BUFFER_HIGH_WATER) or 100ms (FLUSH_INTERVAL_MS), then flushes sequentially and drains cleanly on shutdown.
  • Size-Based Rotation: Automatically rotates when the active log exceeds 10 MB (DEFAULT_AUDIT_LOG_MAX_SIZE_BYTES, configurable via --audit-log-max-size / AUDIT_LOG_MAX_SIZE; CLI/env enforces a minimum of 1024 bytes, while 0 disables rotation programmatically only), retaining 5 archive generations (.1 through .5).
  • Bounded Line Size (256 KB): Serialized entries are hard-capped at 262,144 bytes (MAX_AUDIT_LINE_BYTES)β€”truncating oversized errors/args safely so backward search (1 MB chunk skip ceiling) never skips malformed lines.
  • Symlink & Special-File Protection: Validates paths with lstat() and opens files using O_NOFOLLOW to prevent symlink-following attacks against log paths.
  • Health Visibility: memory://health reports live audit status (ok, degraded, unknown) and droppedCount if disk flushes ever fail.

πŸ›‘οΈ Backup & Recovery Parity

Unlike relational DDL MCP servers (such as mysql-mcp) that create per-DDL schema snapshots (.snapshot.json.gz), memory-journal-mcp provides database-level SQLite backups for point-in-time recovery across destructive journal operations:

  • backup_journal β€” Create a consistent snapshot of the SQLite journal database
  • list_backups β€” Inspect available backup files, timestamps, and sizes
  • restore_backup β€” Restore from a backup (automatically creates a pre-restore safety backup before overwriting)
  • cleanup_backups β€” Enforce retention limits on old backups
  • Pre-Prune Protection β€” Live run_auto_prune executions create a safety backup automatically before modifying or deleting entries

See Maintenance & Optimization and Tools Reference for usage details.


πŸš€ Log Shipping & Audit Identity

Log Shipping Integrations (--audit-log <file> & stderr)

Platform Collection Method Notes
Grafana Loki Grafana Alloy (examples/observability/alloy-config.alloy) Tail mcp-audit.jsonl with tail_from_end = true + file_watch on WSL2 9p; Loki mem_limit: 512m + GOMEMLIMIT=400MiB
Datadog File tailing (conf.d) or container labels (com.datadoghq.ad.logs) Promote success, tool, category, and scope attributes; avoid duplicate autodiscovery
Elastic / ELK Filebeat filestream JSON parser Parse timestamp and structured fields natively
Splunk Universal Forwarder or HTTP Event Collector (JSON) Route --audit-log stderr or bind-mounted JSONL directly
CloudWatch Logs Docker awslogs log driver (--audit-log stderr) Native JSONL line indexing in AWS CloudWatch Logs Insights
Fluentd / Fluent Bit tail input + json parser Works seamlessly for both file mounts and container stderr

OAuth 2.1 & Bearer Identity Attribution

When OAuth 2.1 (--oauth-enabled) or Bearer authentication is active, every audit entry records:

  • user: Authenticated claims.sub identifier (or null when unauthenticated)
  • scopes: Array of granted scopes from the token
  • sessionId, workspaceId, and projectNumber: Transport and multi-tenant scope correlation across multi-agent deployments

πŸ”— Related Pages

  • Observability β€” Prometheus /metrics, Grafana, Loki, Datadog, and memory://metrics/* resources
  • Configuration β€” CLI flags, environment variables, and startup config options
  • HTTP Transport β€” OAuth 2.1, Bearer auth, /metrics, and rate limiting
  • Resources β€” memory://audit, memory://health, and memory://metrics/* details
  • Maintenance & Optimization β€” SQLite backups, run_auto_prune, and database health
  • Team Collaboration β€” Team database RBAC and team audit coverage
  • Deployment β€” Production container and Docker Compose patterns

Memory Journal MCP

Tip

Value Proposition: Persistent project memory for AI agents, so decisions and history stay available across sessions.

🏠 Home


πŸš€ Getting Started


πŸ› οΈ Core Features


🧠 Knowledge Graph


πŸ™ GitHub Integration


πŸ€– AI Integration


πŸ” Enterprise & Architecture


πŸ”— External Links

Clone this wiki locally