An MCP proxy that sits between your AI agent and browser/design tools. It wraps Playwright MCP and optionally a Figma MCP, exposing a single unified MCP server while transparently adding:
Automatic session recovery — dead browser sessions are revived; the agent never sees a crash error
Proxy MCP: one server that runs Playwright, Figma, Chrome DevTools, Shopify Dev and Context7 behind a single connection - and cuts their token cost with compact snapshots, caching and session recovery.
星數
24
工具
—
可用率
—
Token optimization — compact snapshots, delta diffs, snapshot cache, and eval caching reduce browser snapshot cost by 70–90%
Figma response optimization — strips metadata, invisible layers, duplicate component instances, and SVG geometry blobs before the response reaches the agent
Screenshot policy — redirect, warn, block, or allow screenshot calls
Works with Claude Code, Claude Desktop, Cursor, Codex, or any MCP-compatible agent.
Figma MCP is optional. If FIGMA_MCP_CMD is not set, PlayGuard runs in browser-only mode with no behavior changes. Playwright MCP is bundled as a dependency — no separate installation required.
Features
Browser (Playwright)
Automatic Session Recovery
PlayGuard intercepts dead-session errors before the agent sees them:
It restarts Playwright MCP, restores the last URL, and retries the call transparently. Two concurrent calls during a crash → one restart, both calls continue.
Compact Snapshots
browser_snapshot normally returns the full accessibility tree. PlayGuard keeps only lines with [ref=] (interactive elements) and structural landmarks (nav, main, form, dialog, …). Static text and decorative images have no refs and are not needed for navigation.
For pages where even the compact tree is large, browser_snapshot accepts optional params to narrow the result to one subtree:
section — return only the landmark subtree whose label starts with or contains this string (e.g. "form", "navigation \"Footer\"")
around — return only the landmark subtree containing this [ref=N], useful once you know a specific element's ref
depth — cap the returned subtree's depth (combine with section/around for a high-level overview first, or use alone to flatten the whole tree)
Falls back to the full snapshot with a [PlayGuard: ... not found] warning if the requested section/ref doesn't exist. Switching filters between calls always forces a fresh snapshot — it never returns a stale UNCHANGED/cached result from a differently-filtered request.
Smart Wait
Set PLAYGUARD_SMART_WAIT=1 to have browser_snapshot retry when a page looks mid-load — few interactive refs plus a loading/spinner/skeleton indicator in the text. Retries PLAYGUARD_SMART_WAIT_MAX_RETRIES times, PLAYGUARD_SMART_WAIT_MS apart, before returning (with a warning if it still looks like it's loading). Off by default — it adds latency to every snapshot call.
Set PLAYGUARD_COMPACT=false to receive the raw snapshot.
Delta Snapshots
When a page changes only slightly, PlayGuard returns a diff instead of the full snapshot:
After browser_navigate, PlayGuard immediately fetches a snapshot in the background. The next browser_snapshot is served from cache instantly. An unchanged page returns UNCHANGED without hitting the browser.
Screenshot Policy
Mode
Behavior
warn (default)
Screenshot executes; warning written to stderr
redirect
Replaced with browser_snapshot. Pass {visual:true} for a real screenshot
block
Blocked with an error; agent is told which env var to change
allow
No restriction
Eval Cache + Output Compaction
Repeated browser_evaluate calls with the same script on the same URL are served from cache (configurable TTL). Large eval output is truncated to a character limit to avoid blowing the context window.
Figma Optimizer
PlayGuard intercepts Figma MCP responses and runs them through an optimization pipeline before delivering to the agent.
[PlayGuard figma: -68% (284.0KB→91.0KB)]
Note: Modules 1–4 and 6 target raw Figma REST API JSON (document.children, componentId, fillGeometry). If your Figma MCP upstream returns pre-simplified YAML (e.g. Framelink figma-developer-mcp), those modules find nothing to strip — Module 8 handles that shape instead — and inBytes/outBytes are still measured from the actual upstream response text, so the automatic YAML→JSON reformatting (typically ~2x on its own) and Module 5's metadata trim both still count as real savings. parseSkip in the NDJSON log means the response body couldn't be parsed as JSON or YAML at all, not that the optimizer no-op'd. Framelink 0.13+ defaults to a tree text format that is neither, so PlayGuard starts the Figma child with OUTPUT_FORMAT=json unless you set OUTPUT_FORMAT yourself (yaml and json both work; tree disables the optimizer and playguard_compare_design).
Module 1 — Metadata Cleaner: Removes fields irrelevant to layout: createdAt, updatedAt, creator, thumbnailUrl, pluginData, sharedPluginData, exportSettings, reactions, interactions, etc.
Module 2 — Invisible Layer Pruner: Recursively removes nodes where visible === false or opacity === 0.
Module 3 — Component Deduplication: Repeated instances of the same component are collapsed to a reference. 100 buttons → first full definition + 99 references with overrides only.
Module 4 — SVG Refs: Replaces inline SVG geometry (fillGeometry) with { "_svgRef": "nodeId" }. The agent gets the shape identifier without thousands of path coordinates.
Module 6 — Layout Compressor: Removes absolute x/y from nodes inside Auto Layout containers — they are redundant because position is determined by layoutMode, gap, and padding.
Module 5 — Top-Level Metadata Trim: Drops metadata.thumbnailUrl (a signed, single-use preview URL) and metadata.lastModified from pre-simplified upstream shapes like Framelink's { metadata, nodes, globalVars } — fields Module 1 can't reach because it only walks document/children, not a sibling metadata key.
Module 8 — Framelink Shape Optimizer: Targets the pre-simplified { metadata, nodes[], globalVars.styles } shape (Framelink figma-developer-mcp), where Modules 2/4/6 find nothing to strip. 8a: sibling subtrees identical except for ids collapse to { id, name, _sameAs: firstId } (repeated cards/icons); structural copies that differ only in text/name/position collapse to the same stub plus a _textDiff map. 8b: no-op layout styles ({ mode: "none", sizing: {} }) are dropped from globalVars.styles along with node refs to them. 8c: float noise in styles is rounded to 2 decimals ("1.3999999364217122em" → "1.4em"); node text is never touched.
Module 7 — Budget Trim: If the optimized tree still exceeds FIGMA_TEXT_COMPACT, it's trimmed structurally instead of sliced as text. Budget is allocated depth-first, proportional to each branch's size; a branch that doesn't fit collapses to an {id, name, type, _stub:true} marker instead of being silently dropped, so every top-level section stays visible and the agent can re-fetch a stubbed branch by its id. Only a genuinely unparseable response (parseSkip) falls back to a raw text slice.
Design Diff
playguard_compare_design compares a Figma node against the live DOM element that implements it and reports the exact differences — no screenshots, no eyeballing.
Several at once; one bad selector doesn't sink the rest
Auto-map
figmaNodeId + autoMap: true
Point at a component; layers beneath are matched to DOM elements by data-figma-id, data-testid, id, class, or exact text
Notes on how it decides:
Properties are auto-selected per node. A TEXT layer gets its typography and colour; a container gets backgroundColor/padding/borderRadius/boxShadow. Pass properties[] to override.
Tolerances. Sizes compare within PLAYGUARD_DESIGN_DIFF_TOLERANCE_PX, colours within PLAYGUARD_DESIGN_DIFF_TOLERANCE_COLOR per channel. Box properties (padding, margin, borderRadius, borderWidth) compare side-by-side, so 8px 8px 0 0 never passes as 8px.
Unset ≠ unknown. A property Figma leaves unset but CSS zero-defaults (no shadow, no border) is still checked, so a stray browser value is caught. margin is the exception — Figma has no margin concept, so it is reported as unknown rather than as a defect.
Typography follows the label. A button's font size is read from its TEXT layer at any depth, and its background is never mistaken for its text colour.
width/height are never auto-selected — they depend on the viewport, not the design. Request them explicitly and a warning rides along.
Auto-map never guesses. A candidate selector matching zero or several elements is reported as unmapped, not silently attached to the wrong element.
A missing node is an error, not a substitute. A figmaNodeId the upstream response doesn't contain fails that pair, rather than falling back to whatever the response's root frame happens to be.
Both upstream shapes are handled: the raw Figma REST API (@figma/mcp) and Framelink's pre-simplified globalVars.styles form (figma-developer-mcp).
Requirements
Node.js 18+
npm
Installation
No install needed — run via npx. For local development instead:
git clone https://github.com/ZenyaDAR/PlayGuard.git
cd playguard
npm install
npm run build
Usage
Claude Code
Add to ~/.claude/claude_desktop_config.json (or your project's .claude/settings.json):
Set false to disable compact snapshots and receive the raw accessibility tree
PLAYGUARD_DELTA
true
Set false to disable delta snapshots
PLAYGUARD_DELTA_THRESHOLD
0.4
Fraction of lines that must change to trigger a full snapshot instead of a delta (0–1)
PLAYGUARD_TOKEN_BUDGET
0
Max tokens per snapshot; truncates on a line boundary so [ref=] tags are never split. 0 = off
PLAYGUARD_HINT_THRESHOLD
4
After N consecutive snapshots without any action, inject a hint listing available interactive refs
PLAYGUARD_PREFETCH_SNAPSHOT
true
Set false to disable background snapshot prefetch after browser_navigate
PLAYGUARD_SMART_WAIT
false
Set 1/true to retry a snapshot that looks mid-load (few refs + a loading/spinner indicator) instead of returning it as-is
PLAYGUARD_SMART_WAIT_MS
1000
Delay between smart-wait retries, in ms
PLAYGUARD_SMART_WAIT_MAX_RETRIES
3
Max smart-wait retries before giving up and returning the snapshot with a warning
PLAYGUARD_SMART_WAIT_MIN_REFS
5
A snapshot with at least this many [ref=] elements is never considered "still loading"
PLAYGUARD_EVAL_CACHE_TTL
500
browser_evaluate cache TTL in ms. 0 = off
PLAYGUARD_EVAL_COMPACT
10000
Max characters for eval output. 0 = off
PLAYWRIGHT_MCP_CMD
bundled binary
Override the Playwright MCP command
PLAYWRIGHT_MCP_ARGS
—
Extra arguments passed to Playwright MCP (space-separated; wrap an argument in "..." or '...' if it contains a space, e.g. a path). Passing --output-dir here takes precedence over PLAYGUARD_OUTPUT_DIR
PLAYGUARD_OUTPUT_DIR
.playguard/
Where all on-disk artifacts go, split by origin: .playguard/.qa/ for everything from the site under test (screenshots, traces, PDFs, downloads, session) and .playguard/.figma/ for Figma image exports. Defaults to .playguard/ in the project root instead of the upstream's .playwright-mcp/
PLAYGUARD_PROJECT_ROOT
nearest .git/package.json above cwd
The root .playguard/ is created in. process.cwd() is whatever the MCP client spawned the server with, so it is not trusted; set this to pin the location outright
PLAYGUARD_LOG_DIR
logs/
Override the NDJSON analytics log directory
Figma
Variable
Default
Description
FIGMA_MCP_CMD
—
Figma MCP launch command. Unset = Figma disabled
FIGMA_MCP_ARGS
—
Extra arguments for Figma MCP (space-separated; wrap an argument in "..." or '...' if it contains a space)
FIGMA_CACHE_TTL
0
Figma response cache TTL in ms. 0 = off
FIGMA_SVG_REFS
true
Set false to keep SVG geometry inline
FIGMA_TEXT_COMPACT
10000
Max characters for the Figma text response. When the optimizer parsed the tree, an over-budget response is trimmed structurally (Module 7) — branches collapse to {id,name,type} stubs, never silently disappear. Only falls back to a raw text slice if the response never parsed (parseSkip). 0 = off
FIGMA_API_KEY
—
Forwarded to the Figma MCP child process
OUTPUT_FORMAT
json
Output format requested from Framelink (figma-developer-mcp). Must be json or yaml for the optimizer and Design Diff to parse it
Design Diff
Variable
Default
Description
PLAYGUARD_DESIGN_DIFF_TOLERANCE_PX
2
Size difference, in px, still counted as a match
PLAYGUARD_DESIGN_DIFF_TOLERANCE_COLOR
5
Per-channel RGB difference still counted as a match
Measures proxy overhead, snapshot vs screenshot size, cache hit rate, and crash recovery time. No LLM in the loop — raw numbers only.
Tests
npm test
Covers collapseRuns, compactSnap (including token budget boundary), the full Figma optimizer pipeline (optimizeFigmaResponse), the structural budget trim (budgetTrimFigma), and the artifact-path plumbing — withOutputDir, figmaLocalPath, and resolveUpstream, which locates the Playwright MCP through the module graph — in test/playguard.test.mjs, plus dead() crash detection, splitArgs() quoting, the shared ttlCache() helper, the decideSnapshot() cache/delta/hint decision logic, the section/around/depth snapshot filtering, the looksLikeLoading() smart-wait heuristic, the sortDeep() Figma cache-key normalization, and the Module 8 Framelink-shape optimizations in test/playguard-core.test.mjs. test/design-diff.test.mjs covers the design-diff side: property extraction from both upstream Figma shapes (REST and Framelink), colour/border/typography normalization, node resolution including the not-found case, the comparison and tolerance rules, and the generated auto-map and eval scripts.
CI (GitHub Actions, .github/workflows/ci.yml) runs npm test on every push and pull request to main.
Proxy MCP: one server that runs Playwright, Figma, Chrome DevTools, Shopify Dev and Context7 behind a single connection - and cuts their token cost with compact snapshots, caching and session recovery
Proxy MCP: one server that runs Playwright, Figma, Chrome DevTools, Shopify Dev and Context7 behind a single connection - and cuts their token cost with compact snapshots, caching and session recovery.
上次檢查時間:2026-11-11。 Proxy MCP: one server that runs Playwright, Figma, Chrome DevTools, Shopify Dev and Context7 behind a single connection - and cuts their token cost with compact snapshots, caching and session recovery.