Skip to content

mcp-test-v1.2.0

Latest

Choose a tag to compare

@github-actions github-actions released this 07 May 00:07
· 12 commits to main since this release
2adf2dc

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), and replayed_from linkage with click-through.
  • Request — captured request_params (sanitized via audit.redact_keys) and request headers when audit.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 CallToolResult content blocks (text / image / audio / structured) plus response_error when the call errored. Truncation banners when the response exceeded audit.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. 429 with Retry-After when exhausted.
  • Tokens consumed only after validation passes — clicks on non-replayable rows return 400 without burning the operator's budget.
  • Refuses 400 on: invalid UUID, missing event, no captured payload, redacted parameter values, unregistered tool.
  • HTTP 502 on transport-level callErr OR tool-side IsError, mirroring /admin/tryit semantics.
  • error_category precedence mirrors pkg/mcpmw/audit.go (auth → tool → handler) so /events?error_category=tool filters 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.SubscribingLogger capability: AsyncLogger broadcasts after inner.Log succeeds; MemoryLogger broadcasts on every Log.
  • 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 : connected comment + : keepalive every 30 seconds; sets X-Accel-Buffering: no for 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-store and deferred WriteHeader so 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.WithHeaders now redacts credential-bearing names before stashing onto ctx, so audit_payloads.request_headers shows [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.RedactHeaders is now exported for reuse.
  • Try-It payload capture. recordTryitAudit previously bypassed the MCP middleware and never built the audit.Payload sibling. Try-It rows landed with payload=null, and the audit drawer's Response/Notifications tabs correctly reported "No response captured" — making it look like capture was disabled. Now mirrors recordReplayAudit: builds *audit.Payload with RequestParams, ResponseResult, ResponseError, with errCategory precedence aligned to the regular middleware.
  • Empty-audit-log crash on fresh deployments. Go marshals nil []audit.Event as JSON null; the SPA's recent.map(...) / events.map(...) crashed. Audit-store layer now initializes empty results as []T{} so JSON marshals as []. Belt-and-braces ?? [] on the client. New TestMemoryLogger_EmptyResultsAreNotNil enforces the invariant.
  • Compare-stash cleared on signOut and on 401. audit-compare-stash no longer survives a session on a shared workstation.
  • make-dev unblocked. Every dev-* Makefile target that touches docker-compose now declares dev-secrets as a prereq and sources .env.dev inline 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 SubscribingLogger interface; AsyncLogger and MemoryLogger implementations with per-subscriber mutex.
  • MaxQueryLimit = 1000 exported as the single source of truth across Postgres + memory backends.
  • Postgres Store.Query / TimeSeries / Breakdown and MemoryLogger.Breakdown initialize empty results as []T{} (no nil).
  • JSONPathFilter type compiles to JSONB containment; IsAllowedHasKey / IsAllowedJSONSource closed-switch gates with AllowedHasKeysList() / AllowedJSONSourcesList() clone helpers.
  • ParseJSONFilterValue handles the type-detection rules (true/false/int/float/quoted-string fallbacks).
  • MemoryLogger.Log auto-assigns Event.ID when unset, mirroring Postgres so callers can read the assigned id back via Snapshot().

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 via pkg/httpsrv/ratelimit_test.go.
  • recordReplayAudit and recordTryitAudit now build full audit.Payload siblings, mirroring the regular MCP middleware.

Backend — pkg/mcpmw

  • Notification recorder wires per-call into the audit Event; trims to max_payload_bytes with a notifications_truncated flag 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 types AuditPayload, AuditNotification, ReplayResponse, AuditMeta; new streamAuditEvents SSE helper; auditEvent, auditReplay, auditMeta portalAPI methods.
  • pages/Audit.tsx — drawer integration via ?id=, JSONB filter editor (sources from /audit/meta), live-tail toggle, compare-stash bar.
  • stores/auth.ts — clearSessionScopedState clears 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 — excludes go/clear-text-logging on audit.Log with documented justification (the audit logger's contract is to capture err.Error() for forensics; CodeQL data-flow can't see that).
  • make codeql target reproduces CI locally; scripts/codeql-gate.sh parses SARIF and applies the same exclusions (portable bash 3.2 — works on macOS default shell).
  • make verify now writes .claude/.last-verify-passed with 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, and audit.max_payload_bytes keep 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_headers from a stored audit row, it will see [redacted] for the canonicalized names listed above. Names remain visible.

Verification

  • make verify green at 80.2% filtered coverage (gate: ≥80%).
  • make codeql clean against .github/codeql/codeql-config.yml.
  • UI pnpm tsc --noEmit + pnpm build clean.
  • 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.