Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(visual-review): add MCP diff viewer with approve/tolerate (#58871)

Paul D'Ambra224a1ce035b3
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 3940b41ef7e9..063faf633229 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -115,6 +115,7 @@ def _to_snapshot(
cluster_summary, size_mismatch = _parse_diff_metadata(snapshot.diff_metadata)
return contracts.Snapshot(
id=snapshot.id,
+ run_id=snapshot.run_id,
identifier=snapshot.identifier,
result=snapshot.result,
classification_reason=snapshot.classification_reason or "",
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index 7cc4ed8f70e2..28c43f2bc37d 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -183,6 +183,7 @@ class Snapshot:
"""A snapshot with its comparison results."""
id: UUID
+ run_id: UUID
identifier: str
result: str
classification_reason: str # exact, tolerated_hash, below_threshold, or ""
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index 3d3dc5d36643..a188601b0e57 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -149,14 +149,56 @@ class UpdateRepoInputSerializer(DataclassSerializer):
class ApproveSnapshotInputSerializer(DataclassSerializer):
+ identifier = serializers.CharField(
+ help_text="The snapshot identifier to approve (e.g. Storybook story id plus theme).",
+ )
+ new_hash = serializers.CharField(
+ help_text="The content hash of the new baseline image to record for this identifier.",
+ )
+
class Meta:
dataclass = ApproveSnapshotInput
class ApproveRunInputSerializer(DataclassSerializer):
+ snapshots = ApproveSnapshotInputSerializer(
+ many=True,
+ required=False,
+ help_text=(
+ "Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true."
+ ),
+ )
+ approve_all = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Approve every changed and new snapshot in the run. "
+ "Mutually exclusive with `snapshots` — pass one or the other."
+ ),
+ )
+ commit_to_github = serializers.BooleanField(
+ required=False,
+ default=True,
+ help_text=(
+ "Whether to commit the updated baseline YAML to the PR branch on GitHub. "
+ "Set to false to record the approval without pushing a commit."
+ ),
+ )
+
class Meta:
dataclass = ApproveRunRequestInput
+ def validate(self, attrs: ApproveRunRequestInput) -> ApproveRunRequestInput:
+ if attrs.approve_all and attrs.snapshots:
+ raise serializers.ValidationError(
+ {"approve_all": "`approve_all` and `snapshots` are mutually exclusive — pass one or the other."}
+ )
+ if not attrs.approve_all and not attrs.snapshots:
+ raise serializers.ValidationError(
+ {"snapshots": "Provide a non-empty `snapshots` list or set `approve_all: true`."}
+ )
+ return attrs
+
class SnapshotHistoryEntrySerializer(DataclassSerializer):
current_artifact = ArtifactSerializer(allow_null=True, required=False)
@@ -171,7 +213,12 @@ class ToleratedHashEntrySerializer(DataclassSerializer):
class MarkToleratedInputSerializer(serializers.Serializer):
- snapshot_id = serializers.UUIDField()
+ snapshot_id = serializers.UUIDField(
+ help_text=(
+ "UUID of the changed snapshot to mark as a known tolerated alternate. "
+ "Future runs that produce the same alternate hash for this identifier will not be flagged as changes."
+ ),
+ )
class QuarantineSourceRunSerializer(DataclassSerializer):
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index 73145d2ec21b..68052c3dd55e 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -302,13 +302,18 @@ export interface AddSnapshotsResultApi {
}
export interface ApproveSnapshotInputApi {
+ /** The snapshot identifier to approve (e.g. Storybook story id plus theme). */
identifier: string
+ /** The content hash of the new baseline image to record for this identifier. */
new_hash: string
}
export interface ApproveRunRequestInputApi {
+ /** Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true. */
snapshots?: ApproveSnapshotInputApi[]
+ /** Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other. */
approve_all?: boolean
+ /** Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit. */
commit_to_github?: boolean
}
@@ -351,6 +356,7 @@ export interface SnapshotApi {
reviewed_by?: UserBasicInfoApi | null
cluster_summary?: ClusterSummaryApi | null
id: string
+ run_id: string
identifier: string
result: string
classification_reason: string
@@ -382,6 +388,7 @@ export interface PaginatedSnapshotListApi {
}
export interface MarkToleratedInputApi {
+ /** UUID of the changed snapshot to mark as a known tolerated alternate. Future runs that produce the same alternate hash for this identifier will not be flagged as changes. */
snapshot_id: string
}
diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.ts
index dcbc2e9a4956..c98c2774d7e3 100644
--- a/products/visual_review/frontend/generated/api.zod.ts
+++ b/products/visual_review/frontend/generated/api.zod.ts
@@ -122,22 +122,46 @@ export const VisualReviewRunsAddSnapshotsCreateBody = /* @__PURE__ */ zod.object
With approve_all=true, approves all changed+new snapshots and returns
signed baseline YAML. With specific snapshots, approves only those.
*/
+export const visualReviewRunsApproveCreateBodyApproveAllDefault = false
+export const visualReviewRunsApproveCreateBodyCommitToGithubDefault = true
+
export const VisualReviewRunsApproveCreateBody = /* @__PURE__ */ zod.object({
snapshots: zod
.array(
zod.object({
- identifier: zod.string(),
- new_hash: zod.string(),
+ identifier: zod
+ .string()
+ .describe('The snapshot identifier to approve (e.g. Storybook story id plus theme).'),
+ new_hash: zod
+ .string()
+ .describe('The content hash of the new baseline image to record for this identifier.'),
})
)
- .optional(),
- approve_all: zod.boolean().optional(),
- commit_to_github: zod.boolean().optional(),
+ .optional()
+ .describe(
+ 'Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true.'
+ ),
+ approve_all: zod
+ .boolean()
+ .default(visualReviewRunsApproveCreateBodyApproveAllDefault)
+ .describe(
+ 'Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other.'
+ ),
+ commit_to_github: zod
+ .boolean()
+ .default(visualReviewRunsApproveCreateBodyCommitToGithubDefault)
+ .describe(
+ 'Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit.'
+ ),
})
/**
* Mark a changed snapshot as a known tolerated alternate.
*/
export const VisualReviewRunsTolerateCreateBody = /* @__PURE__ */ zod.object({
- snapshot_id: zod.uuid(),
+ snapshot_id: zod
+ .uuid()
+ .describe(
+ 'UUID of the changed snapshot to mark as a known tolerated alternate. Future runs that produce the same alternate hash for this identifier will not be flagged as changes.'
+ ),
})
diff --git a/products/visual_review/mcp/apps/VisualReviewSnapshotsView.tsx b/products/visual_review/mcp/apps/VisualReviewSnapshotsView.tsx
new file mode 100644
index 000000000000..596b431db513
--- /dev/null
+++ b/products/visual_review/mcp/apps/VisualReviewSnapshotsView.tsx
@@ -0,0 +1,278 @@
+import { type ReactElement, useCallback, useMemo, useState } from 'react'
+
+import { Badge, Button, Card, CardContent } from '@posthog/quill'
+
+import type { ArtifactApi, PaginatedSnapshotListApi, SnapshotApi } from '../../frontend/generated/api.schemas'
+
+export type VisualReviewArtifact = ArtifactApi
+export type VisualReviewSnapshot = SnapshotApi
+export type VisualReviewSnapshotsData = PaginatedSnapshotListApi & { _posthogUrl?: string }
+
+export type SnapshotAction = 'approve' | 'tolerate'
+
+export interface ActionState {
+ loadingAs: SnapshotAction | null
+ error: string | null
+ succeededAs: SnapshotAction | null
+}
+
+export interface VisualReviewSnapshotsViewProps {
+ data: VisualReviewSnapshotsData
+ onAction?: (snapshot: VisualReviewSnapshot, action: SnapshotAction) => Promise<void>
+ actionStates?: Record<string, ActionState>
+}
+
+const resultVariant: Record<string, 'success' | 'destructive' | 'warning' | 'default'> = {
+ unchanged: 'success',
+ changed: 'destructive',
+ new: 'warning',
+ removed: 'default',
+}
+
+function resultLabel(result: string): string {
+ return result.charAt(0).toUpperCase() + result.slice(1)
+}
+
+function formatDiffPct(pct: number | null | undefined): string {
+ if (pct == null) {
+ return '—'
+ }
+ return `${pct.toFixed(2)}%`
+}
+
+function isApproved(snapshot: VisualReviewSnapshot, state: ActionState | undefined): boolean {
+ return snapshot.review_state === 'approved' || state?.succeededAs === 'approve'
+}
+
+function isTolerated(state: ActionState | undefined): boolean {
+ return state?.succeededAs === 'tolerate'
+}
+
+function ArtifactImage({
+ label,
+ artifact,
+}: {
+ label: string
+ artifact: VisualReviewArtifact | null | undefined
+}): ReactElement {
+ return (
+ <div className="flex flex-col gap-1 min-w-0">
+ <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{label}</span>
+ <div className="border rounded bg-secondary/30 flex items-center justify-center min-h-[120px] overflow-hidden">
+ {artifact?.download_url ? (
+ // eslint-disable-next-line react/forbid-elements
+ <img
+ src={artifact.download_url}
+ alt={`${label} image`}
+ loading="lazy"
+ className="max-w-full max-h-[480px] object-contain"
+ />
+ ) : (
+ <span className="text-xs text-muted-foreground p-4">No image</span>
+ )}
+ </div>
+ {artifact && (
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {artifact.content_hash.slice(0, 12)}
+ {artifact.width && artifact.height ? ` · ${artifact.width}×${artifact.height}` : ''}
+ </span>
+ )}
+ </div>
+ )
+}
+
+function SnapshotRow({
+ snapshot,
+ onClick,
+ isSelected,
+ actionState,
+}: {
+ snapshot: VisualReviewSnapshot
+ onClick: () => void
+ isSelected: boolean
+ actionState: ActionState | undefined
+}): ReactElement {
+ const variant = resultVariant[snapshot.result] ?? 'default'
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={
+ 'flex items-center justify-between gap-2 w-full text-left px-3 py-2 rounded border transition-colors ' +
+ (isSelected ? 'bg-secondary border-primary' : 'hover:bg-secondary/50 border-transparent')
+ }
+ >
+ <div className="flex items-center gap-2 min-w-0 flex-1">
+ <Badge variant={variant}>{resultLabel(snapshot.result)}</Badge>
+ <span className="text-sm truncate">{snapshot.identifier}</span>
+ </div>
+ <div className="flex items-center gap-2 text-xs text-muted-foreground shrink-0">
+ {isApproved(snapshot, actionState) && <Badge variant="success">Approved</Badge>}
+ {isTolerated(actionState) && <Badge variant="default">Tolerated</Badge>}
+ {snapshot.result === 'changed' && <span>{formatDiffPct(snapshot.diff_percentage)}</span>}
+ </div>
+ </button>
+ )
+}
+
+// Bound the rendered list so a broken run with thousands of snapshots
+// doesn't melt the host. Snapshots are sorted so the actionable ones
+// (changed > new > removed > unchanged) come first.
+const MAX_VISIBLE_SNAPSHOTS = 100
+
+const resultOrder: Record<string, number> = { changed: 0, new: 1, removed: 2, unchanged: 3 }
+
+function sortForReview(snapshots: VisualReviewSnapshot[]): VisualReviewSnapshot[] {
+ return [...snapshots].sort((a, b) => {
+ const ra = resultOrder[a.result] ?? 99
+ const rb = resultOrder[b.result] ?? 99
+ if (ra !== rb) {
+ return ra - rb
+ }
+ return a.identifier.localeCompare(b.identifier)
+ })
+}
+
+export function VisualReviewSnapshotsView({
+ data,
+ onAction,
+ actionStates,
+}: VisualReviewSnapshotsViewProps): ReactElement {
+ const sortedSnapshots = useMemo(() => sortForReview(data.results), [data.results])
+ const totalSnapshots = data.count ?? data.results.length
+ const snapshots = useMemo(() => sortedSnapshots.slice(0, MAX_VISIBLE_SNAPSHOTS), [sortedSnapshots])
+ const truncated = sortedSnapshots.length > MAX_VISIBLE_SNAPSHOTS || totalSnapshots > snapshots.length
+ const initialId = useMemo(() => {
+ const first = snapshots.find((s) => s.result === 'changed') ?? snapshots[0]
+ return first?.id
+ }, [snapshots])
+
+ const [selectedId, setSelectedId] = useState<string | undefined>(initialId)
+ const selected = snapshots.find((s) => s.id === selectedId) ?? snapshots[0]
+
+ const handleAction = useCallback(
+ (action: SnapshotAction) => {
+ if (!selected || !onAction) {
+ return
+ }
+ void onAction(selected, action)
+ },
+ [selected, onAction]
+ )
+
+ if (snapshots.length === 0) {
+ return (
+ <div className="p-4">
+ <span className="text-sm text-muted-foreground">No snapshots in this run.</span>
+ </div>
+ )
+ }
+
+ const selectedState = selected ? actionStates?.[selected.id] : undefined
+ const isLoading = selectedState?.loadingAs != null
+ const approveDisabled =
+ !onAction ||
+ isLoading ||
+ isApproved(selected!, selectedState) ||
+ selected!.result === 'unchanged' ||
+ selected!.result === 'removed'
+ const tolerateDisabled = !onAction || isLoading || selected!.result !== 'changed' || isTolerated(selectedState)
+
+ return (
+ <div className="flex flex-col gap-3 p-4">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <span className="text-sm text-muted-foreground">
+ {truncated
+ ? `Showing ${snapshots.length} of ${totalSnapshots} snapshots (most actionable first)`
+ : `${snapshots.length} snapshot${snapshots.length === 1 ? '' : 's'}`}
+ </span>
+ {truncated && (
+ <span className="text-xs text-muted-foreground">
+ Ask the agent to filter (e.g. only `result=changed`) to drill in further.
+ </span>
+ )}
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-[260px_1fr] gap-3">
+ <div className="flex flex-col gap-1 max-h-[600px] overflow-y-auto pr-1">
+ {snapshots.map((snapshot) => (
+ <SnapshotRow
+ key={snapshot.id}
+ snapshot={snapshot}
+ isSelected={snapshot.id === selected!.id}
+ onClick={() => setSelectedId(snapshot.id)}
+ actionState={actionStates?.[snapshot.id]}
+ />
+ ))}
+ </div>
+
+ {selected && (
+ <Card>
+ <CardContent>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <div className="flex flex-col gap-1 min-w-0">
+ <span className="text-sm font-semibold break-all">{selected.identifier}</span>
+ <div className="flex items-center gap-2 flex-wrap">
+ <Badge variant={resultVariant[selected.result] ?? 'default'}>
+ {resultLabel(selected.result)}
+ </Badge>
+ {selected.classification_reason && (
+ <Badge variant="default">{selected.classification_reason}</Badge>
+ )}
+ {selected.change_kind && (
+ <Badge variant="default">{selected.change_kind}</Badge>
+ )}
+ {selected.size_mismatch && <Badge variant="warning">Size mismatch</Badge>}
+ <span className="text-xs text-muted-foreground">
+ Diff {formatDiffPct(selected.diff_percentage)}
+ {selected.diff_pixel_count != null
+ ? ` · ${selected.diff_pixel_count.toLocaleString()} px`
+ : ''}
+ </span>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="default"
+ size="sm"
+ disabled={approveDisabled}
+ onClick={() => handleAction('approve')}
+ >
+ {selectedState?.loadingAs === 'approve' ? 'Working…' : 'Approve'}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={tolerateDisabled}
+ onClick={() => handleAction('tolerate')}
+ >
+ {selectedState?.loadingAs === 'tolerate' ? 'Working…' : 'Tolerate'}
+ </Button>
+ </div>
+ </div>
+
+ {selectedState?.error && (
+ <span className="text-xs text-destructive-foreground">{selectedState.error}</span>
+ )}
+ {selectedState?.succeededAs && (
+ <span className="text-xs text-muted-foreground">
+ {selectedState.succeededAs === 'approve'
+ ? 'Approved — baseline updated.'
+ : 'Tolerated — future runs ignore this variant.'}
+ </span>
+ )}
+
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
+ <ArtifactImage label="Baseline" artifact={selected.baseline_artifact} />
+ <ArtifactImage label="Current" artifact={selected.current_artifact} />
+ <ArtifactImage label="Diff" artifact={selected.diff_artifact} />
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/visual_review/mcp/apps/index.ts b/products/visual_review/mcp/apps/index.ts
new file mode 100644
index 000000000000..0897bba12791
--- /dev/null
+++ b/products/visual_review/mcp/apps/index.ts
@@ -0,0 +1,9 @@
+export {
+ VisualReviewSnapshotsView,
+ type ActionState,
+ type SnapshotAction,
+ type VisualReviewArtifact,
+ type VisualReviewSnapshot,
+ type VisualReviewSnapshotsData,
+ type VisualReviewSnapshotsViewProps,
+} from './VisualReviewSnapshotsView'
diff --git a/products/visual_review/mcp/tools.yaml b/products/visual_review/mcp/tools.yaml
index 047b1cf4bead..b8fbf47b791d 100644
--- a/products/visual_review/mcp/tools.yaml
+++ b/products/visual_review/mcp/tools.yaml
@@ -7,7 +7,11 @@
category: Visual review
feature: visual_review
url_prefix: /visual_review
-ui_apps: {}
+ui_apps:
+ visual-review-snapshots:
+ type: custom
+ app_name: PostHog Visual Review Snapshots
+ description: Visual review run snapshots — diff viewer with approve/tolerate actions
tools:
visual-review-repos-baselines-retrieve:
operation: visual_review_repos_baselines_retrieve
@@ -74,7 +78,21 @@ tools:
enabled: false
visual-review-runs-approve-create:
operation: visual_review_runs_approve_create
- enabled: false
+ enabled: true
+ scopes:
+ - visual_review:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Approve visual review snapshots
+ description: >
+ Approve visual changes for snapshots in a run. With `approve_all: true`, approves every changed and new
+ snapshot in the run. Otherwise pass an explicit `snapshots` list, each entry being `{identifier, new_hash}`
+ — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. Approval updates the baseline YAML
+ in the repo; `commit_to_github` (default true) also pushes a commit to the PR branch. Confirm with the user
+ before approving — this is the action that ships the visual change.
+ feature_flag: visual-review
visual-review-runs-complete-create:
operation: visual_review_runs_complete_create
enabled: false
@@ -163,11 +181,29 @@ tools:
List all snapshots captured in a run with their diff results. Each snapshot carries an `identifier` (e.g.
Storybook story id + theme), a `result` (`unchanged`, `changed`, `new`, `removed`), an optional
`classification_reason` (`tolerated_hash`, `below_threshold`, `exact`), diff percentage / pixel count, and
- `review_state` (`pending`, `approved`). Paginated.
+ `review_state` (`pending`, `approved`). Renders an interactive diff viewer with baseline / current / diff
+ images and approve / tolerate actions. Paginated — pass a `limit` (e.g. 50) when a run might have many
+ snapshots (a broken run can produce 3000+ pairs); the diff viewer caps the visible list at 100 and
+ prioritises actionable results regardless.
+ ui_app: visual-review-snapshots
feature_flag: visual-review
visual-review-runs-tolerate-create:
operation: visual_review_runs_tolerate_create
- enabled: false
+ enabled: true
+ scopes:
+ - visual_review:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Tolerate visual review snapshot
+ description: >
+ Mark a single changed snapshot as a known tolerated alternate. The snapshot's current hash is recorded
+ alongside the existing baseline so future runs producing the same alternate are not flagged as changes —
+ useful for benign rendering variants (anti-aliasing noise, blinking cursors, etc.). Pass `snapshot_id` — the
+ UUID of the snapshot in this run. Does not change the baseline. Use approve to actually update the baseline
+ image.
+ feature_flag: visual-review
visual-review-runs-tolerated-hashes-list:
operation: visual_review_runs_tolerated_hashes_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 4fb4ba69578f..1dec7931c68d 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5520,6 +5520,22 @@
},
"feature_flag": "visual-review"
},
+ "visual-review-runs-approve-create": {
+ "description": "Approve visual changes for snapshots in a run. With `approve_all: true`, approves every changed and new snapshot in the run. Otherwise pass an explicit `snapshots` list, each entry being `{identifier, new_hash}` — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. Approval updates the baseline YAML in the repo; `commit_to_github` (default true) also pushes a commit to the PR branch. Confirm with the user before approving — this is the action that ships the visual change.",
+ "category": "Visual review",
+ "feature": "visual_review",
+ "summary": "Approve visual review snapshots",
+ "title": "Approve visual review snapshots",
+ "required_scopes": ["visual_review:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "visual-review"
+ },
"visual-review-runs-counts-retrieve": {
"description": "Return review state counts across all runs for the current project: `needs_review`, `clean`, `processing`, `stale`. Useful as a single call to show reviewer workload before drilling into the list.",
"category": "Visual review",
@@ -5585,7 +5601,7 @@
"feature_flag": "visual-review"
},
"visual-review-runs-snapshots-list": {
- "description": "List all snapshots captured in a run with their diff results. Each snapshot carries an `identifier` (e.g. Storybook story id + theme), a `result` (`unchanged`, `changed`, `new`, `removed`), an optional `classification_reason` (`tolerated_hash`, `below_threshold`, `exact`), diff percentage / pixel count, and `review_state` (`pending`, `approved`). Paginated.",
+ "description": "List all snapshots captured in a run with their diff results. Each snapshot carries an `identifier` (e.g. Storybook story id + theme), a `result` (`unchanged`, `changed`, `new`, `removed`), an optional `classification_reason` (`tolerated_hash`, `below_threshold`, `exact`), diff percentage / pixel count, and `review_state` (`pending`, `approved`). Renders an interactive diff viewer with baseline / current / diff images and approve / tolerate actions. Paginated — pass a `limit` (e.g. 50) when a run might have many snapshots (a broken run can produce 3000+ pairs); the diff viewer caps the visible list at 100 and prioritises actionable results regardless.",
"category": "Visual review",
"feature": "visual_review",
"summary": "List run snapshots",
@@ -5600,6 +5616,22 @@
},
"feature_flag": "visual-review"
},
+ "visual-review-runs-tolerate-create": {
+ "description": "Mark a single changed snapshot as a known tolerated alternate. The snapshot's current hash is recorded alongside the existing baseline so future runs producing the same alternate are not flagged as changes — useful for benign rendering variants (anti-aliasing noise, blinking cursors, etc.). Pass `snapshot_id` — the UUID of the snapshot in this run. Does not change the baseline. Use approve to actually update the baseline image.",
+ "category": "Visual review",
+ "feature": "visual_review",
+ "summary": "Tolerate visual review snapshot",
+ "title": "Tolerate visual review snapshot",
+ "required_scopes": ["visual_review:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "visual-review"
+ },
"visual-review-runs-tolerated-hashes-list": {
"description": "List known tolerated alternate hashes for a snapshot `identifier` in the run's repo. Tolerated hashes catalog acceptable rendering variants (e.g. anti-aliasing noise) so future runs don't flag them as changes. Requires `identifier` query parameter.",
"category": "Visual review",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4f2768cc72ad..6b2eda378c69 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6001,6 +6001,22 @@
},
"feature_flag": "visual-review"
},
+ "visual-review-runs-approve-create": {
+ "description": "Approve visual changes for snapshots in a run. With `approve_all: true`, approves every changed and new snapshot in the run. Otherwise pass an explicit `snapshots` list, each entry being `{identifier, new_hash}` — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. Approval updates the baseline YAML in the repo; `commit_to_github` (default true) also pushes a commit to the PR branch. Confirm with the user before approving — this is the action that ships the visual change.",
+ "category": "Visual review",
+ "feature": "visual_review",
+ "summary": "Approve visual review snapshots",
+ "title": "Approve visual review snapshots",
+ "required_scopes": ["visual_review:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "visual-review"
+ },
"visual-review-runs-counts-retrieve": {
"description": "Return review state counts across all runs for the current project: `needs_review`, `clean`, `processing`, `stale`. Useful as a single call to show reviewer workload before drilling into the list.",
"category": "Visual review",
@@ -6066,7 +6082,7 @@
"feature_flag": "visual-review"
},
"visual-review-runs-snapshots-list": {
- "description": "List all snapshots captured in a run with their diff results. Each snapshot carries an `identifier` (e.g. Storybook story id + theme), a `result` (`unchanged`, `changed`, `new`, `removed`), an optional `classification_reason` (`tolerated_hash`, `below_threshold`, `exact`), diff percentage / pixel count, and `review_state` (`pending`, `approved`). Paginated.",
+ "description": "List all snapshots captured in a run with their diff results. Each snapshot carries an `identifier` (e.g. Storybook story id + theme), a `result` (`unchanged`, `changed`, `new`, `removed`), an optional `classification_reason` (`tolerated_hash`, `below_threshold`, `exact`), diff percentage / pixel count, and `review_state` (`pending`, `approved`). Renders an interactive diff viewer with baseline / current / diff images and approve / tolerate actions. Paginated — pass a `limit` (e.g. 50) when a run might have many snapshots (a broken run can produce 3000+ pairs); the diff viewer caps the visible list at 100 and prioritises actionable results regardless.",
"category": "Visual review",
"feature": "visual_review",
"summary": "List run snapshots",
@@ -6081,6 +6097,22 @@
},
"feature_flag": "visual-review"
},
+ "visual-review-runs-tolerate-create": {
+ "description": "Mark a single changed snapshot as a known tolerated alternate. The snapshot's current hash is recorded alongside the existing baseline so future runs producing the same alternate are not flagged as changes — useful for benign rendering variants (anti-aliasing noise, blinking cursors, etc.). Pass `snapshot_id` — the UUID of the snapshot in this run. Does not change the baseline. Use approve to actually update the baseline image.",
+ "category": "Visual review",
+ "feature": "visual_review",
+ "summary": "Tolerate visual review snapshot",
+ "title": "Tolerate visual review snapshot",
+ "required_scopes": ["visual_review:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "visual-review"
+ },
"visual-review-runs-tolerated-hashes-list": {
"description": "List known tolerated alternate hashes for a snapshot `identifier` in the run's repo. Tolerated hashes catalog acceptable rendering variants (e.g. anti-aliasing noise) so future runs don't flag them as changes. Requires `identifier` query parameter.",
"category": "Visual review",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2591f6eb3c82..11384ddd0a13 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4362,13 +4362,18 @@ export namespace Schemas {
}
export interface ApproveSnapshotInput {
+ /** The snapshot identifier to approve (e.g. Storybook story id plus theme). */
identifier: string;
+ /** The content hash of the new baseline image to record for this identifier. */
new_hash: string;
}
export interface ApproveRunRequestInput {
+ /** Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true. */
snapshots?: ApproveSnapshotInput[];
+ /** Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other. */
approve_all?: boolean;
+ /** Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit. */
commit_to_github?: boolean;
}
@@ -21209,6 +21214,7 @@ export namespace Schemas {
}
export interface MarkToleratedInput {
+ /** UUID of the changed snapshot to mark as a known tolerated alternate. Future runs that produce the same alternate hash for this identifier will not be flagged as changes. */
snapshot_id: string;
}
@@ -24316,6 +24322,7 @@ export namespace Schemas {
reviewed_by?: UserBasicInfo | null;
cluster_summary?: ClusterSummary | null;
id: string;
+ run_id: string;
identifier: string;
result: string;
classification_reason: string;
diff --git a/services/mcp/src/generated/visual_review/api.ts b/services/mcp/src/generated/visual_review/api.ts
index 6b3fe65063f5..2598f558a62d 100644
--- a/services/mcp/src/generated/visual_review/api.ts
+++ b/services/mcp/src/generated/visual_review/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 8 enabled ops
+ * PostHog API - MCP 10 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -68,6 +68,54 @@ export const VisualReviewRunsRetrieveParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Approve visual changes for snapshots in this run.
+
+With approve_all=true, approves all changed+new snapshots and returns
+signed baseline YAML. With specific snapshots, approves only those.
+ */
+export const VisualReviewRunsApproveCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const visualReviewRunsApproveCreateBodyApproveAllDefault = false
+export const visualReviewRunsApproveCreateBodyCommitToGithubDefault = true
+
+export const VisualReviewRunsApproveCreateBody = /* @__PURE__ */ zod.object({
+ snapshots: zod
+ .array(
+ zod.object({
+ identifier: zod
+ .string()
+ .describe('The snapshot identifier to approve (e.g. Storybook story id plus theme).'),
+ new_hash: zod
+ .string()
+ .describe('The content hash of the new baseline image to record for this identifier.'),
+ })
+ )
+ .optional()
+ .describe(
+ 'Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true.'
+ ),
+ approve_all: zod
+ .boolean()
+ .default(visualReviewRunsApproveCreateBodyApproveAllDefault)
+ .describe(
+ 'Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other.'
+ ),
+ commit_to_github: zod
+ .boolean()
+ .default(visualReviewRunsApproveCreateBodyCommitToGithubDefault)
+ .describe(
+ 'Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit.'
+ ),
+})
+
/**
* Recent change history for a snapshot identifier across runs.
*/
@@ -103,6 +151,26 @@ export const VisualReviewRunsSnapshotsListQueryParams = /* @__PURE__ */ zod.obje
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
+/**
+ * Mark a changed snapshot as a known tolerated alternate.
+ */
+export const VisualReviewRunsTolerateCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const VisualReviewRunsTolerateCreateBody = /* @__PURE__ */ zod.object({
+ snapshot_id: zod
+ .string()
+ .describe(
+ 'UUID of the changed snapshot to mark as a known tolerated alternate. Future runs that produce the same alternate hash for this identifier will not be flagged as changes.'
+ ),
+})
+
/**
* List known tolerated hashes for a snapshot identifier.
*/
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index 0900e8411d63..88a8b68ee3a0 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -25,6 +25,7 @@ export const SURVEY_LIST_RESOURCE_URI = 'ui://posthog/survey-list.html'
export const SURVEY_STATS_RESOURCE_URI = 'ui://posthog/survey-stats.html'
export const TRACE_SPAN_RESOURCE_URI = 'ui://posthog/trace-span.html'
export const TRACE_SPAN_LIST_RESOURCE_URI = 'ui://posthog/trace-span-list.html'
+export const VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI = 'ui://posthog/visual-review-snapshots.html'
export const WORKFLOW_RESOURCE_URI = 'ui://posthog/workflow.html'
export const WORKFLOW_LIST_RESOURCE_URI = 'ui://posthog/workflow-list.html'
@@ -54,6 +55,7 @@ export type UiAppKey =
| 'survey-stats'
| 'trace-span'
| 'trace-span-list'
+ | 'visual-review-snapshots'
| 'workflow'
| 'workflow-list'
@@ -83,6 +85,7 @@ export const URI_MAP: Record<UiAppKey, string> = {
'survey-stats': SURVEY_STATS_RESOURCE_URI,
'trace-span': TRACE_SPAN_RESOURCE_URI,
'trace-span-list': TRACE_SPAN_LIST_RESOURCE_URI,
+ 'visual-review-snapshots': VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI,
workflow: WORKFLOW_RESOURCE_URI,
'workflow-list': WORKFLOW_LIST_RESOURCE_URI,
}
@@ -243,6 +246,12 @@ export const UI_APPS: Array<{
description: 'Trace Span List view',
appDir: 'generated/trace-span-list',
},
+ {
+ name: 'PostHog Visual Review Snapshots',
+ uri: VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI,
+ description: 'Visual review run snapshots — diff viewer with approve/tolerate actions',
+ appDir: 'visual-review-snapshots',
+ },
{
name: 'PostHog Workflow',
uri: WORKFLOW_RESOURCE_URI,
diff --git a/services/mcp/src/tools/generated/visual_review.ts b/services/mcp/src/tools/generated/visual_review.ts
index 1e799f0d8c5f..29be480271e5 100644
--- a/services/mcp/src/tools/generated/visual_review.ts
+++ b/services/mcp/src/tools/generated/visual_review.ts
@@ -5,15 +5,20 @@ import type { Schemas } from '@/api/generated'
import {
VisualReviewReposListQueryParams,
VisualReviewReposRetrieveParams,
+ VisualReviewRunsApproveCreateBody,
+ VisualReviewRunsApproveCreateParams,
VisualReviewRunsListQueryParams,
VisualReviewRunsRetrieveParams,
VisualReviewRunsSnapshotHistoryListParams,
VisualReviewRunsSnapshotHistoryListQueryParams,
VisualReviewRunsSnapshotsListParams,
VisualReviewRunsSnapshotsListQueryParams,
+ VisualReviewRunsTolerateCreateBody,
+ VisualReviewRunsTolerateCreateParams,
VisualReviewRunsToleratedHashesListParams,
VisualReviewRunsToleratedHashesListQueryParams,
} from '@/generated/visual_review/api'
+import { withUiApp } from '@/resources/ui-apps'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -54,6 +59,37 @@ const visualReviewReposRetrieve = (): ToolBase<typeof VisualReviewReposRetrieveS
},
})
+const VisualReviewRunsApproveCreateSchema = VisualReviewRunsApproveCreateParams.omit({ project_id: true }).extend(
+ VisualReviewRunsApproveCreateBody.shape
+)
+
+const visualReviewRunsApproveCreate = (): ToolBase<
+ typeof VisualReviewRunsApproveCreateSchema,
+ Schemas.AutoApproveResult
+> => ({
+ name: 'visual-review-runs-approve-create',
+ schema: VisualReviewRunsApproveCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof VisualReviewRunsApproveCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.snapshots !== undefined) {
+ body['snapshots'] = params.snapshots
+ }
+ if (params.approve_all !== undefined) {
+ body['approve_all'] = params.approve_all
+ }
+ if (params.commit_to_github !== undefined) {
+ body['commit_to_github'] = params.commit_to_github
+ }
+ const result = await context.api.request<Schemas.AutoApproveResult>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/visual_review/runs/${encodeURIComponent(String(params.id))}/approve/`,
+ body,
+ })
+ return result
+ },
+})
+
const VisualReviewRunsCountsRetrieveSchema = z.object({})
const visualReviewRunsCountsRetrieve = (): ToolBase<
@@ -157,20 +193,43 @@ const VisualReviewRunsSnapshotsListSchema = VisualReviewRunsSnapshotsListParams.
const visualReviewRunsSnapshotsList = (): ToolBase<
typeof VisualReviewRunsSnapshotsListSchema,
WithPostHogUrl<Schemas.PaginatedSnapshotList>
-> => ({
- name: 'visual-review-runs-snapshots-list',
- schema: VisualReviewRunsSnapshotsListSchema,
- handler: async (context: Context, params: z.infer<typeof VisualReviewRunsSnapshotsListSchema>) => {
+> =>
+ withUiApp('visual-review-snapshots', {
+ name: 'visual-review-runs-snapshots-list',
+ schema: VisualReviewRunsSnapshotsListSchema,
+ handler: async (context: Context, params: z.infer<typeof VisualReviewRunsSnapshotsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedSnapshotList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/visual_review/runs/${encodeURIComponent(String(params.id))}/snapshots/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return await withPostHogUrl(context, result, '/visual_review')
+ },
+ })
+
+const VisualReviewRunsTolerateCreateSchema = VisualReviewRunsTolerateCreateParams.omit({ project_id: true }).extend(
+ VisualReviewRunsTolerateCreateBody.shape
+)
+
+const visualReviewRunsTolerateCreate = (): ToolBase<typeof VisualReviewRunsTolerateCreateSchema, Schemas.Snapshot> => ({
+ name: 'visual-review-runs-tolerate-create',
+ schema: VisualReviewRunsTolerateCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof VisualReviewRunsTolerateCreateSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedSnapshotList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/visual_review/runs/${encodeURIComponent(String(params.id))}/snapshots/`,
- query: {
- limit: params.limit,
- offset: params.offset,
- },
+ const body: Record<string, unknown> = {}
+ if (params.snapshot_id !== undefined) {
+ body['snapshot_id'] = params.snapshot_id
+ }
+ const result = await context.api.request<Schemas.Snapshot>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/visual_review/runs/${encodeURIComponent(String(params.id))}/tolerate/`,
+ body,
})
- return await withPostHogUrl(context, result, '/visual_review')
+ return result
},
})
@@ -202,10 +261,12 @@ const visualReviewRunsToleratedHashesList = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'visual-review-repos-list': visualReviewReposList,
'visual-review-repos-retrieve': visualReviewReposRetrieve,
+ 'visual-review-runs-approve-create': visualReviewRunsApproveCreate,
'visual-review-runs-counts-retrieve': visualReviewRunsCountsRetrieve,
'visual-review-runs-list': visualReviewRunsList,
'visual-review-runs-retrieve': visualReviewRunsRetrieve,
'visual-review-runs-snapshot-history-list': visualReviewRunsSnapshotHistoryList,
'visual-review-runs-snapshots-list': visualReviewRunsSnapshotsList,
+ 'visual-review-runs-tolerate-create': visualReviewRunsTolerateCreate,
'visual-review-runs-tolerated-hashes-list': visualReviewRunsToleratedHashesList,
}
diff --git a/services/mcp/src/ui-apps/apps/visual-review-snapshots.tsx b/services/mcp/src/ui-apps/apps/visual-review-snapshots.tsx
new file mode 100644
index 000000000000..c8c33dc30b1b
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/visual-review-snapshots.tsx
@@ -0,0 +1,104 @@
+import '../styles/tailwind.css'
+
+import type { App } from '@modelcontextprotocol/ext-apps'
+import { useCallback, useState } from 'react'
+import { createRoot } from 'react-dom/client'
+
+import {
+ type ActionState,
+ type SnapshotAction,
+ type VisualReviewSnapshot,
+ type VisualReviewSnapshotsData,
+ VisualReviewSnapshotsView,
+} from 'products/visual_review/mcp/apps'
+
+import { AppWrapper } from '../components/AppWrapper'
+
+function VisualReviewSnapshotsApp(): JSX.Element {
+ return (
+ <AppWrapper<VisualReviewSnapshotsData> appName="PostHog Visual Review Snapshots">
+ {({ data, app }) => <VisualReviewSnapshotsContent data={data!} app={app} />}
+ </AppWrapper>
+ )
+}
+
+function VisualReviewSnapshotsContent({
+ data,
+ app,
+}: {
+ data: VisualReviewSnapshotsData
+ app: App | null
+}): JSX.Element {
+ const [actionStates, setActionStates] = useState<Record<string, ActionState>>({})
+
+ const updateState = useCallback((snapshotId: string, partial: Partial<ActionState>) => {
+ setActionStates((prev) => {
+ const existing = prev[snapshotId] ?? { loadingAs: null, error: null, succeededAs: null }
+ return { ...prev, [snapshotId]: { ...existing, ...partial } }
+ })
+ }, [])
+
+ const handleAction = useCallback(
+ async (snapshot: VisualReviewSnapshot, action: SnapshotAction): Promise<void> => {
+ // The view gates Approve on `result === 'changed' | 'new'` and requires
+ // a current_artifact to render. If we still landed here without a
+ // content_hash, refuse to dispatch rather than silently sending '' to
+ // the backend (where it would produce ArtifactNotFoundError).
+ if (action === 'approve' && !snapshot.current_artifact?.content_hash) {
+ updateState(snapshot.id, {
+ loadingAs: null,
+ error: 'No current artifact to approve.',
+ succeededAs: null,
+ })
+ return
+ }
+ if (!app) {
+ updateState(snapshot.id, {
+ loadingAs: null,
+ error: 'Actions are not available in this host. Ask the agent to approve or tolerate via chat.',
+ succeededAs: null,
+ })
+ return
+ }
+ updateState(snapshot.id, { loadingAs: action, error: null, succeededAs: null })
+ try {
+ const toolName =
+ action === 'approve' ? 'visual-review-runs-approve-create' : 'visual-review-runs-tolerate-create'
+ const args =
+ action === 'approve'
+ ? {
+ id: snapshot.run_id,
+ snapshots: [
+ {
+ identifier: snapshot.identifier,
+ // Guarded above; `!` is safe here.
+ new_hash: snapshot.current_artifact!.content_hash,
+ },
+ ],
+ approve_all: false,
+ commit_to_github: true,
+ }
+ : { id: snapshot.run_id, snapshot_id: snapshot.id }
+
+ const result = await app.callServerTool({ name: toolName, arguments: args })
+ if (result.isError) {
+ const message = result.content?.find((c) => c.type === 'text')?.text ?? `${action} failed.`
+ updateState(snapshot.id, { loadingAs: null, error: message })
+ return
+ }
+ updateState(snapshot.id, { loadingAs: null, error: null, succeededAs: action })
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ updateState(snapshot.id, { loadingAs: null, error: message })
+ }
+ },
+ [app, updateState]
+ )
+
+ return <VisualReviewSnapshotsView data={data} onAction={handleAction} actionStates={actionStates} />
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<VisualReviewSnapshotsApp />)
+}