Repository navigation
Observability
memory-journal-mcp includes a built-in, zero-dependency observability subsystem (src/observability/) designed for real-time monitoring, AI token cost accounting, tail-latency profiling, and capacity planning. It combines an in-memory streaming accumulator (MetricsAccumulator), optional atomic disk persistence, Prometheus 0.0.4 /metrics exposition across both HTTP and stdio modes, and seven inspectable MCP resources (memory://metrics/* and memory://health).
┌───────────────────────────┐
│ AI Agent / IDE │
└─────────────┬─────────────┘
│ Tool Calls / Resource Reads
▼
┌────────────────────────────────────────────────────────────────────────────┐
│ memory-journal-mcp Server │
│ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ MetricsAccumulator (In-Memory Streaming Aggregator) │ │
│ │ • Counters: tool calls, errors, duration, input/output tokens, │ │
│ │ normalized resource reads (1,000-key cap), per-user counts │ │
│ │ • LatencyTracker: 1,000-sample sliding window (P50 / P95 / P99) │ │
│ │ • TokenEstimator: content-type heuristic (prose / json / code) │ │
│ └──────────▲───────────────────────────────────┬───────────────────────┘ │
│ │ Optional Snapshot Reload/Save │ Format-time Exposition │
│ ▼ (--persist-metrics) ▼ (--metrics-export │
│ ┌──────────────────────────────┐ ┌───────────────────────────────────┐ │
│ │ Disk JSON State │ │ Prometheus 0.0.4 /metrics │ │
│ │ (Atomic temp + rename via │ │ • HTTP GET /metrics (port 3000) │ │
│ │ --metrics-path) │ │ • Standalone Listener │ │
│ └──────────────────────────────┘ │ (127.0.0.1:9465 default) │ │
│ └───────────────────┬───────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │ │
│ │ MCP Observability Resources │ │ │
│ │ • memory://metrics/{summary,tokens,resources, │ │ │
│ │ system,users,latency} │ │ │
│ │ • memory://health │ │ │
│ └──────────────────────────┬───────────────────────┘ │ │
└─────────────────────────────┼───────────────────────────┼──────────────────┘
│ │
▼ ▼
MCP Client / Agent Prometheus / Grafana /
(stdio & HTTP modes) Datadog / OTel Collector
The observability pipeline consists of four core components:
-
MetricsAccumulator(src/observability/metrics.ts): Tracks per-tool execution counts, error totals, cumulative durations, estimated input/output tokens, normalized resource reads (?queryand#fragmentstripped), per-user call counts, and bounded latency percentiles ($p50$ ,$p95$ ,$p99$ ) using a 1,000-sample sliding window per tool. Unknown dynamic keys beyondMAX_METRIC_KEYS(1,000tools or resources;10,000users) fold cleanly into an'other'bucket to prevent unbounded cardinality growth. -
Prometheus Formatter & Standalone Metrics Server (
src/observability/prometheus-formatter.ts,src/observability/metrics-server.ts): Passing--metrics-export prometheus(METRICS_EXPORT=prometheus) renders standards-compliant Prometheus0.0.4text (text/plain; version=0.0.4; charset=utf-8) on the main HTTP server (GET /metrics, port3000default) and spawns a hardened standalone HTTP listener (127.0.0.1:9465default, customizable via--metrics-port/MJ_METRICS_PORTandMJ_METRICS_HOST) for stdio and HTTP deployments. -
Optional JSON State Persistence: Enabling
--persist-metrics(PERSIST_METRICS=true) saves accumulated metrics atomically (temp + renameat--metrics-path/METRICS_PATH) and reloads/merges historical totals across server restarts, automatically re-normalizing legacy resource URIs. -
MCP Observability Resources: Seven built-in
memory://metrics/*andmemory://healthresources expose real-time telemetry directly inside any MCP session without requiring HTTP scraping.
| Collection Mode | Endpoint / Target | Auth & Bind Behavior | Best For |
|---|---|---|---|
HTTP Transport GET /metrics |
http://<host>:3000/metrics |
Bearer mode requires --auth-token; OAuth 2.1 requires a valid token with audit scope (requireScope('audit')) |
Production HTTP/SSE & OAuth 2.1 deployments |
Stdio + Standalone /metrics |
http://127.0.0.1:9465/metrics (MJ_METRICS_HOST / --metrics-port) |
Loopback by default; non-loopback MJ_METRICS_HOST refuses to start without a non-placeholder --auth-token / MCP_AUTH_TOKEN; enforces Host header validation (403) |
Desktop IDEs (stdio) & sidecar Prometheus scrapes |
| OAuth 2.1 Mode (Fail-Closed Standalone) |
http://<host>:3000/metrics only |
Standalone :9465 is skipped fail-closed when --oauth-enabled is set without a static MCP_AUTH_TOKEN
|
Keycloak / OIDC identity deployments |
| MCP Resources (Any Transport) |
memory://metrics/*, memory://health
|
Works natively over stdio or http (memory://metrics/users requires audit scope when auth is active) |
Direct AI agent diagnostics |
When --transport http is paired with --metrics-export prometheus, GET /metrics is mounted directly on the primary Express application alongside /health and /mcp:
memory-journal-mcp --transport http --port 3000 --server-host 0.0.0.0 \
--allowed-io-roots /path/to/allowed/dir \
--metrics-export prometheus --persist-metrics --metrics-path /data/metrics.json \
--auth-token "$(openssl rand -hex 32)" \
--audit-log /var/log/memory-journal/mcp-audit.jsonlIn stdio mode (used by Antigravity, Claude Desktop, Cursor, and VS Code), passing --metrics-export prometheus spawns the standalone /metrics-only listener on 127.0.0.1:9465 (requestTimeout = 30s, keepAliveTimeout = 65s, headersTimeout = 66s), alongside /health (200 { "status": "ok" }). Both /metrics and /health on the standalone listener enforce GET/HEAD-only requests, returning 405 Method Not Allowed with Allow: GET, HEAD for any other HTTP method:
memory-journal-mcp --transport stdio \
--metrics-export prometheus --metrics-port 9465 \
--persist-metrics --metrics-path ./metrics.json \
--audit-log ./logs/mcp-audit.jsonlAll 17 metric families exported by formatPrometheusMetrics() (src/observability/prometheus-formatter.ts).
Note
Zero Empty Metric Families: Per-tool, per-resource, per-user, and latency metric families (the 9 conditional metrics below) are omitted until matching traffic occurs so Prometheus and Datadog OpenMetrics v2 scrapers never ingest empty # TYPE headers.
| Metric | Type | Labels | Description |
|---|---|---|---|
mcp_server_info |
gauge |
version, platform
|
Constant 1 identifying the Node.js runtime version and OS platform |
mcp_tool_calls_total |
counter | — | Total number of MCP tool invocations across all tools |
mcp_tool_errors_total |
counter | — | Total number of tool invocations resulting in an error or { success: false }
|
mcp_tool_duration_seconds_total |
counter | — | Cumulative wall-clock duration of all tool invocations in seconds |
mcp_tool_input_tokens_total |
counter | — | Total estimated input tokens across all tool invocations |
mcp_tool_output_tokens_total |
counter | — | Total estimated output tokens across all tool invocations |
mcp_process_memory_bytes |
gauge | — | Node.js process Resident Set Size (RSS) in bytes |
mcp_process_uptime_seconds |
gauge | — | Server process uptime in seconds |
| Metric | Type | Labels | Description |
|---|---|---|---|
mcp_resource_reads_total |
counter | resource |
Total MCP resource reads by canonical URI (query strings ? and fragments # stripped) |
mcp_tool_calls_by_name_total |
counter | tool |
Total tool invocations partitioned by tool name |
mcp_tool_tokens_by_name_total |
counter |
tool, type
|
Estimated tokens per tool partitioned by type="input" or type="output"
|
mcp_tool_errors_by_name_total |
counter | tool |
Total errors partitioned by tool name (only tools with errorCount > 0) |
mcp_tool_tokens_per_call |
gauge | tool |
Average total tokens ((input + output) / calls) per tool call |
mcp_user_calls_total |
counter | user |
Total tool calls per authenticated identity (emitted only when audit scope is granted) |
mcp_tool_latency_ms_p50 |
gauge | tool |
Median (P50) execution latency in milliseconds (1,000-sample sliding window) |
mcp_tool_latency_ms_p95 |
gauge | tool |
95th percentile (P95) execution latency in milliseconds |
mcp_tool_latency_ms_p99 |
gauge | tool |
99th percentile (P99) execution latency in milliseconds |
memory-journal-mcp calculates token estimates without external tokenizer dependencies (src/observability/token-estimator.ts) using empirically calibrated UTF-8 byte ratios:
| Content Type | Ratio | Usage |
|---|---|---|
prose |
~4.0 bytes/token | Natural-language strings and Markdown content |
json |
~2.8 bytes/token | Structured JSON tool arguments and _meta.tokenEstimate responses |
code |
~3.2 bytes/token | Code Mode snippets and mixed braces/identifiers |
Input and output token totals flow into mcp_tool_input_tokens_total, mcp_tool_output_tokens_total, mcp_tool_tokens_by_name_total{tool,type}, mcp_tool_tokens_per_call{tool}, and every JSONL entry in Audit Trail.
When --persist-metrics (PERSIST_METRICS=true) is enabled with --metrics-path <path> (METRICS_PATH), MetricsAccumulator saves JSON snapshots atomically (temporary file + rename) and merges prior counts on startup. During reload, legacy resource keys with query strings or fragments are normalized and merged so metric cardinality stays clean across upgrades.
Unlike database servers that wire @opentelemetry/api Meter SDK hooks in-process, memory-journal-mcp uses zero-dependency Prometheus 0.0.4 exposition directly. To ingest memory-journal-mcp metrics into an OpenTelemetry pipeline (or APM backends such as Honeycomb, Grafana Cloud, Dynatrace, or New Relic), configure the OpenTelemetry Collector prometheus receiver to scrape /metrics on :9465 or :3000.
All telemetry is directly inspectable by AI agents over any transport (stdio or http) via native MCP resources (see Resources):
| Resource URI | Access Control | Contents |
|---|---|---|
memory://metrics/summary |
Public / Standard read | Aggregate tool calls, errors, duration, total input/output tokens, distinct tools called and resources read counts |
memory://metrics/tokens |
Public / Standard read | Per-tool token usage sorted by output tokens descending |
memory://metrics/resources |
Public / Standard read | Normalized resource URI read counts and error counts (with snapshot as_of timestamp) |
memory://metrics/system |
Public / Standard read | Server upSince, uptime seconds, RSS memory MB, Node.js version, platform |
memory://metrics/users |
Requires audit scope (when auth enabled) |
Per-user invocation counts sourced from Bearer/OAuth identity context |
memory://metrics/latency |
Public / Standard read | Per-tool P50, P95, P99, min/max latency, and sample counts sorted by P99 descending |
memory://health |
Public / Standard read | Database path/size, vector index readiness, backup count, audit logger health (droppedCount), and metrics summary |
Example memory://metrics/summary inspection payload (text/plain YAML):
metrics_summary:
up_since: 2026-05-30T10:00:00.000Z
as_of: 2026-05-30T10:15:00.000Z
total_calls: 142
total_errors: 2
error_rate_pct: 1.4
total_duration_ms: 1840
avg_duration_ms: 13
total_input_tokens: 12450
total_output_tokens: 48900
total_resource_reads: 38
tools_called: 12
resources_read: 6Turnkey, portable Docker Compose, Prometheus, Grafana, Loki, Grafana Alloy, and Datadog templates live under examples/observability/ in the repository. See also examples/oauth-keycloak/ for OAuth 2.1 + Keycloak integration.
Configure prometheus.yml (examples/observability/prometheus.yml) with a 15-second scrape interval. When MJ_METRICS_HOST=0.0.0.0 is used inside Docker, supply the Bearer token file (MCP_AUTH_TOKEN):
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'memory-journal-mcp'
metrics_path: '/metrics'
authorization:
type: Bearer
credentials_file: '/etc/prometheus/metrics.token'
static_configs:
- targets: ['memory-journal-mcp:9465'] # Or ['host.docker.internal:9465'] when host uses MJ_METRICS_HOST=0.0.0.0 + MCP_AUTH_TOKENexamples/observability/docker-compose.monitoring.yml launches Grafana (grafana/grafana:13.3.2, mem_limit: 512m) on http://localhost:3001 with Prometheus (v3.16.0 on :9090) and Loki (3.7.11 on :3100; distroless image with healthcheck: disable: true and external readiness probe at http://localhost:3100/ready) datasources and three auto-provisioned dashboards:
-
Memory-Journal-MCP Token & Tool Metrics (
grafana-dashboard.json) -
Memory-Journal-MCP AI Efficiency (
grafana-ai-dashboard.json) -
Memory-Journal-MCP Logs (Loki) (
grafana-logs.json)
Tip
After upgrading Grafana container versions, perform a hard browser refresh (Ctrl+Shift+R) if cached frontend SPA panel chunks report "Error loading: stat".
examples/observability/alloy-config.alloy ships mcp-audit.jsonl entries to Loki while promoting tool, category, scope, and success labels. Apply these hardening settings when running under Docker on WSL2 /mnt/c (9p) bind mounts:
-
Grafana Alloy: Set
sync_period = "10s",tail_from_end = true, and explicitfile_watch { min_poll_frequency = "1s" max_poll_frequency = "5s" }so file-rotation checks do not re-read historical log archives across9p(withdepends_on: loki: condition: service_started). -
Loki Container Limits & Distroless Healthcheck: Constrain Loki with
mem_limit: 512mandGOMEMLIMIT=400MiB. Becausegrafana/loki:3.7+is a distroless image withoutwget/curl,docker-compose.monitoring.ymlsetshealthcheck: disable: true; probehttp://localhost:3100/readyexternally for readiness checks.
Use examples/observability/datadog-labels.yml to enable single-source Docker Autodiscovery v2 OpenMetrics scraping and import the two JSON dashboards (datadog-dashboard.json and datadog-ai-dashboard.json):
labels:
tags.datadoghq.com/env: production
tags.datadoghq.com/service: memory_journal_mcp
com.datadoghq.ad.check_names: '["openmetrics"]'
com.datadoghq.ad.init_configs: '[{}]'
com.datadoghq.ad.instances: |-
[{
"reported_hostname": "${DD_REPORTED_HOSTNAME:-memory-journal-mcp-host}",
"openmetrics_endpoint": "http://memory-journal-mcp:9465/metrics",
"namespace": "memory_journal_mcp",
"metrics": [".*"],
"max_returned_metrics": 10000,
"send_monotonic_counter": true,
"timeout": 10,
"min_collection_interval": 15,
"headers": {
"Authorization": "Bearer ${MCP_AUTH_TOKEN}"
},
"tags": ["service:memory_journal_mcp", "env:production"]
}]
com.datadoghq.ad.logs: |-
[{
"source": "memory_journal_mcp",
"service": "memory_journal_mcp"
}]Datadog Hardening Best Practices:
-
Single Scrape Source: Never combine Docker Autodiscovery v2 labels (
com.datadoghq.ad.*) with a duplicate staticopenmetrics.d/conf.yamltargeting the same container. -
Agent Limits & Host Isolation: Set
DD_EXTRA_PERFORMANCE_METRICS: false,pid: host,cgroup: host(notcgroupns_mode: host), andmem_limit: 1536mon the Datadog Agent container. -
Metric Normalization: Datadog automatically translates Prometheus
_totalcounter suffixes into.countmetrics (e.g.,mcp_tool_calls_totalbecomesmemory_journal_mcp.mcp_tool_calls.count).
Scrape memory-journal-mcp directly via the OpenTelemetry Collector prometheus receiver:
receivers:
prometheus:
config:
scrape_configs:
- job_name: 'memory-journal-mcp'
scrape_interval: 15s
metrics_path: '/metrics'
static_configs:
- targets: ['127.0.0.1:9465']| CLI Flag | Environment Variable | Config Key (JSON/YAML) | Default | Description |
|---|---|---|---|---|
--metrics-export <format> |
METRICS_EXPORT |
metricsExport |
disabled | Set to prometheus to enable /metrics exposition |
--metrics-port <port> |
MJ_METRICS_PORT |
metricsPort |
9465 |
Standalone /metrics HTTP server port |
| — | MJ_METRICS_HOST |
— | 127.0.0.1 |
Bind host for standalone /metrics server (non-loopback requires MCP_AUTH_TOKEN) |
--persist-metrics |
PERSIST_METRICS |
persistMetrics |
false |
Persist metric counters/breakdowns to disk across restarts |
--metrics-path <path> |
METRICS_PATH |
metricsPath |
— | File path for persisted metrics JSON state |
--auth-token <token> |
MCP_AUTH_TOKEN |
authToken (prefer MCP_AUTH_TOKEN / env secrets over plaintext config files) |
— | Static Bearer token protecting /metrics (required for non-loopback MJ_METRICS_HOST) |
--auth-scopes <scopes> |
MCP_AUTH_SCOPES |
authScopes |
read |
Include audit scope to expose mcp_user_calls_total and memory://metrics/users
|
--audit-log <path> |
AUDIT_LOG_PATH |
auditLog |
disabled | JSONL audit log path or stderr (see Audit Trail) |
For all server flags, OAuth 2.1 options, and configuration file precedence, see Configuration.
When --oauth-enabled is enabled without a static --auth-token / MCP_AUTH_TOKEN, memory-journal-mcp skips the standalone :9465 listener fail-closed so metrics are never exposed unauthenticated. Configure Prometheus or Datadog to scrape OAuth-protected GET /metrics on the HTTP transport (--port, default 3000) using an access token granted the audit scope.
Setting MJ_METRICS_HOST=0.0.0.0 (or another non-loopback address) without a non-placeholder --auth-token / MCP_AUTH_TOKEN throws a fatal startup error (fail-closed security guard). In Docker deployments (examples/observability/), generate a random 32-byte token (openssl rand -hex 32) for MCP_AUTH_TOKEN.
The standalone metrics listener validates the HTTP Host header: loopback binds only accept localhost, 127.0.0.1, or ::1, and non-wildcard bound hosts require the Host header to match the bound address. Use MJ_METRICS_HOST=0.0.0.0 (paired with MCP_AUTH_TOKEN) when scraping by Docker service name (memory-journal-mcp:9465) or from a container via http://host.docker.internal:9465 (loopback 127.0.0.1 rejects Host: host.docker.internal:9465 unless a loopback relay rewrites Host: localhost:9465).
formatPrometheusMetrics() intentionally omits conditional per-tool, per-resource, per-user, and latency metric blocks until at least one corresponding call or resource read has been recorded, avoiding empty # TYPE families.
Per-user call attribution requires both an authenticated identity context (user) and the audit scope (MCP_AUTH_SCOPES=full / audit or OAuth token with audit scope). Without audit scope, includeUserBreakdown is false to protect user privacy.
-
Audit Trail — JSONL audit logging,
memory://audit,search_audit_log, and log shipping - Configuration — Full CLI flags, environment variables, and YAML/JSON config reference
-
HTTP Transport —
/metricsOAuth scopes, Bearer auth, rate limiting, and Slowloris timeouts -
Resources — All
memory://metrics/*,memory://health, andmemory://auditURIs - Performance — SQLite optimizations, token estimation, and caching internals
- Capacity Planning — Memory sizing, cardinality bounds, and storage budgets
- Deployment — Production Docker and Compose deployment workflows
Tip
Value Proposition: Persistent project memory for AI agents, so decisions and history stay available across sessions.
- Quick Start
- Installation
- Configuration
- CLI Reference
- HTTP Transport
- Tool Filtering
- Code Mode
- Tools Reference
- Performance
- Capacity Planning
- Architecture
- Observability
- Audit Trail
- Maintenance & Optimization
- Deployment
- Schema
- Team Collaboration