Repository navigation
mcp-test v1.2.0 — Audit Inspection / Debugging Utility
This release closes #8 and ships the operator-facing inspection / debugging utility on top of the audit_payloads foundation that landed in v1.1.0. Three merged PRs (#10, #11, #12) layered the backend query / replay / streaming primitives, then the portal UI that consumes them.
+6240 / −111 across 45 files since v1.1.1 (which itself was the foundation cleanup release). Twelve commits on main.
Highlights
Click-to-expand audit drawer (4 tabs)
The portal's Audit page is now operator-grade. Click any row to open a side drawer with deep-linkable URL state (?id=<event-id>):
- Overview — timing, identity, request id, session id, source (
mcp/portal-tryit/portal-replay), andreplayed_fromlinkage with click-through. - Request — captured
request_params(sanitized viaaudit.redact_keys) and request headers whenaudit.capture_headers: true. Credential-bearing header names (Authorization,Cookie,Set-Cookie,Proxy-Authorization,X-API-Key) are stored as[redacted]; names remain visible so an operator can confirm "this request carried an Authorization header" without seeing the bearer. - Response — full
CallToolResultcontent blocks (text / image / audio / structured) plusresponse_errorwhen the call errored. Truncation banners when the response exceededaudit.max_payload_bytes. - Notifications — chronological list of every
notifications/*(progress, log message) the tool dispatched during the call window. Tab strip count appends+when the captured list was truncated.
role="dialog" + aria-modal + auto-focus on close button + return-focus-on-close for assistive tech. Esc and backdrop close.
Side-by-side comparison
/portal/audit/compare?a=<id>&b=<id> renders a JSON-path-aware structural diff of two events. Walks objects and arrays by key/index so reordered keys don't masquerade as changes; one-side-undefined trees show per-key only-A / only-B leaves rather than a single (undefined) → {…} line; deep trees indent linearly via per-<ul> padding (no off-panel bleed). Summary, request_params, response_result, response_error, and notifications all render distinct panels.
Replay endpoint
POST /api/v1/portal/audit/events/{id}/replay re-invokes the captured tool call through an in-process MCP client. New audit row tagged source=portal-replay with replayed_from set; the new event fires with the portal-replay caller's identity, not the original caller's, so the audit row reflects who triggered the replay.
- Per-identity rate limit: 5 burst, one token refilled every 12 seconds (sustained 5/min), scoped by API-key id or OIDC subject.
429withRetry-Afterwhen exhausted. - Tokens consumed only after validation passes — clicks on non-replayable rows return
400without burning the operator's budget. - Refuses
400on: invalid UUID, missing event, no captured payload, redacted parameter values, unregistered tool. - HTTP
502on transport-level callErr OR tool-sideIsError, mirroring/admin/tryitsemantics. error_categoryprecedence mirrorspkg/mcpmw/audit.go(auth → tool → handler) so/events?error_category=toolfilters bucket replays alongside native tool calls.- CSRF-gated via
X-Requested-With.
The portal Replay button opens a confirmation modal that calls out the side-effect re-run; default focus is on Cancel so a reflexive Enter dismisses rather than fires. The button is disabled with a tooltip when the row is non-replayable (mirrors the server-side validation client-side via the [redacted] marker walk).
SSE live tail
GET /api/v1/portal/audit/stream opens a Server-Sent Events stream of new audit events as they're written.
- New
audit.SubscribingLoggercapability:AsyncLoggerbroadcasts afterinner.Logsucceeds;MemoryLoggerbroadcasts on everyLog. - Per-subscriber mutex serializes send-vs-cancel (race-tested).
- Atomic SSE frame write via
bytes.Buffer(no half-formed frames on partial encode failure). - Opening
: connectedcomment +: keepaliveevery 30 seconds; setsX-Accel-Buffering: nofor nginx-fronted deployments.
The portal Live tail toggle subscribes via fetch + ReadableStream (rather than EventSource, which can't carry custom headers — would lock out CLI / API-key callers). The client parser strips one optional leading space per W3C SSE, caps the line buffer at 1 MiB so a misbehaving producer can't OOM the tab, drops malformed events at parse time, surfaces 401 to the unauthorized handler without a per-stream banner flash, and reports server-close so the operator can re-enable.
New events land in a fixed-cap most-recent-first list (cap 20) above the table; the table itself stays a historical-filter view to avoid refetch-per-event storms under load.
JSONB path filters
/audit/events and /audit/export accept additional query parameters that compile to EXISTS (SELECT 1 FROM audit_payloads p WHERE p.event_id = audit_events.id AND p.<col> @> $N::jsonb) against the existing jsonb_path_ops GIN indexes:
?param.<dotted.path>=v— request_params containment (dotted path → nested object literal).?response.<dotted.path>=v— response_result containment.?header.<name>=v— request_headers containment (header name canonicalized).?has=<column>— payload column non-empty (allowlisted; closed-switch gate against SQL injection).
Values are type-detected (true/false → bool, integer / float → number, else string; quote to force string). Header values are always strings. Filters are AND-combined with each other and with the indexed-column filters.
The portal exposes a JSONB filter editor that produces this exact syntax. The editor sources its has-keys list from a new endpoint (/audit/meta) so a server-side schema change doesn't require a UI redeploy.
NDJSON export
GET /api/v1/portal/audit/export?format=jsonl streams the filtered set as newline-delimited summary rows for offline analysis, ad-hoc ETL, or backups.
- Hard cap at 100,000 rows per request; truncates silently at the cap (doc explicitly calls out the caveat and notes future versions may emit a sentinel — operator must verify row count against the filter window).
- Per-row context check so client disconnects stop the stream promptly.
Cache-Control: no-storeand deferredWriteHeaderso a backend error before the first row sends a clean 5xx instead of a half-written 200.- Full JSONB filter contract supported —
?success=false&has=notifications&from=...scopes a backfill cleanly.
Filter contract endpoint
GET /api/v1/portal/audit/meta returns:
{
"has_keys": [...],
"json_sources": ["param", "response", "header"],
"replay": {"burst": 5, "refill_secs": 12, "sustained_min": 5},
"export": {"max_rows": 100000}
}Lets a UI build its filter editor against the server's source of truth instead of duplicating allow-lists in client code. sustained_min is derived from 60 / refill_secs (not coincidentally equal to burst), so a tuning change to the rate limit propagates automatically.
Inspection walkthrough doc
docs/operations/inspection.md is the operator-facing end-to-end: capture a call → open the drawer → read each tab → replay it → compare to a baseline → filter via JSONB paths → live-tail → export. Cross-referenced against the actual replayBurst / replayRefill / maxExportEvents constants. Header redaction policy and the post-validation token-consumption contract are called out explicitly.
Security & operator follow-ups
These landed alongside the feature work to make the surface safe to ship:
- Header redaction at the source.
auth.WithHeadersnow redacts credential-bearing names before stashing onto ctx, soaudit_payloads.request_headersshows[redacted]rather than verbatim. Pre-existing leak (the comment claimed redaction; the implementation didn't); v1.2.0 was the first to put those bytes in front of UI users so the fix landed here.pkg/auth.RedactHeadersis now exported for reuse. - Try-It payload capture.
recordTryitAuditpreviously bypassed the MCP middleware and never built theaudit.Payloadsibling. Try-It rows landed withpayload=null, and the audit drawer's Response/Notifications tabs correctly reported "No response captured" — making it look like capture was disabled. Now mirrorsrecordReplayAudit: builds*audit.PayloadwithRequestParams,ResponseResult,ResponseError, witherrCategoryprecedence aligned to the regular middleware. - Empty-audit-log crash on fresh deployments. Go marshals nil
[]audit.Eventas JSONnull; the SPA'srecent.map(...)/events.map(...)crashed. Audit-store layer now initializes empty results as[]T{}so JSON marshals as[]. Belt-and-braces?? []on the client. NewTestMemoryLogger_EmptyResultsAreNotNilenforces the invariant. - Compare-stash cleared on signOut and on 401.
audit-compare-stashno longer survives a session on a shared workstation. - make-dev unblocked. Every
dev-*Makefile target that touches docker-compose now declaresdev-secretsas a prereq and sources.env.devinline before invoking compose. (Compose interpolates${MCPTEST_COOKIE_SECRET:?required}at parse time on every invocation, and Make subshells lose env state.)
Changes by area
Backend — pkg/audit
- New
SubscribingLoggerinterface;AsyncLoggerandMemoryLoggerimplementations with per-subscriber mutex. MaxQueryLimit = 1000exported as the single source of truth across Postgres + memory backends.- Postgres
Store.Query/TimeSeries/BreakdownandMemoryLogger.Breakdowninitialize empty results as[]T{}(no nil). JSONPathFiltertype compiles to JSONB containment;IsAllowedHasKey/IsAllowedJSONSourceclosed-switch gates withAllowedHasKeysList()/AllowedJSONSourcesList()clone helpers.ParseJSONFilterValuehandles the type-detection rules (true/false/int/float/quoted-string fallbacks).MemoryLogger.Logauto-assignsEvent.IDwhen unset, mirroring Postgres so callers can read the assigned id back viaSnapshot().
Backend — pkg/httpsrv
- New endpoints:
/audit/meta,/audit/events/{id}(single event detail),/audit/events/{id}/replay,/audit/stream,/audit/export. - New
identityRateLimiter(token-bucket per identity, GC of idle buckets).replayBurst=5,replayRefill=12s. Tested viapkg/httpsrv/ratelimit_test.go. recordReplayAuditandrecordTryitAuditnow build fullaudit.Payloadsiblings, mirroring the regular MCP middleware.
Backend — pkg/mcpmw
- Notification recorder wires per-call into the audit Event; trims to
max_payload_byteswith anotifications_truncatedflag on the prefix.
Frontend — ui/src
- New
pages/Compare.tsx(369 lines) — JSON-path-aware diff tree. - New
components/EventDrawer.tsx(420 lines) — 4-tab drawer with replay confirm, focus management, deep-link via?id=. - New
components/ConfirmModal.tsx(107 lines) — Cancel-default-focus modal for destructive-action confirmation. - New
components/JsonView.tsx— pretty JSON + copy-to-clipboard. - New
lib/storage-keys.ts— centralized localStorage key names. lib/api.ts— new typesAuditPayload,AuditNotification,ReplayResponse,AuditMeta; newstreamAuditEventsSSE helper;auditEvent,auditReplay,auditMetaportalAPI methods.pages/Audit.tsx— drawer integration via?id=, JSONB filter editor (sources from/audit/meta), live-tail toggle, compare-stash bar.stores/auth.ts—clearSessionScopedStateclears the compare stash on signOut and 401.
Schema
No new migrations in this release. v1.1.1's 0003_audit_payloads_cleanup remains the most recent migration; greenfield installs run 0001 → 0002 → 0003 and converge to the same shape as upgraders.
CI / tooling
.github/codeql/codeql-config.yml— excludesgo/clear-text-loggingonaudit.Logwith documented justification (the audit logger's contract is to captureerr.Error()for forensics; CodeQL data-flow can't see that).make codeqltarget reproduces CI locally;scripts/codeql-gate.shparses SARIF and applies the same exclusions (portable bash 3.2 — works on macOS default shell).make verifynow writes.claude/.last-verify-passedwith the diff hash for the maintainer's pre-commit gate.
Upgrade notes
- No breaking changes. Existing endpoints preserve their wire contract; new endpoints are purely additive.
- No new schema migrations. Run the v1.1.1 migrations (
0001,0002,0003) and you're current. - Optional config knobs are unchanged.
audit.capture_payloads,audit.capture_headers, andaudit.max_payload_byteskeep their existing defaults (all opt-in remain opt-in; capture-on-by-default remain on-by-default). - Sensitive headers are now redacted in audit_payloads. If you have any tooling reading
request_headersfrom a stored audit row, it will see[redacted]for the canonicalized names listed above. Names remain visible.
Verification
make verifygreen at 80.2% filtered coverage (gate: ≥80%).make codeqlclean against.github/codeql/codeql-config.yml.- UI
pnpm tsc --noEmit + pnpm buildclean. - Race detector enabled across the suite (
go test -race -count=1). - New integration tests:
tests/audit_replay_test.go,tests/audit_stream_test.go.
Process notes
The maintainer's pre-commit adversarial-review gate (~/.claude/hooks/review-gate.sh) ran across every PR in this release, with the deliberate goal of landing each PR review-clean on the first commit. Only PR #11 broke that target — its CodeQL data-flow finding (the go/clear-text-logging rule on audit.Log) wasn't catchable by gosec or semgrep, which is why this release also adds make codeql as a documented pre-push step. PRs #9, #10, and #12 each landed without a fix(...): address PR #N critical review follow-up commit on main (PR-internal review rounds were caught and fixed in the working tree before commit).
Closes #8.