facebook/memlab/mcp-server

Claude Code and agent skill by facebook/memlab

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Install

npx vskill@latest install facebook/memlab/mcp-server

SKILL.md

The same SKILL.md was published earlier as facebook/memlab/mcp-server.

MemLab MCP Investigation Skill

This document provides a structured investigation methodology for AI coding assistants using the MemLab MCP server to analyze JavaScript heap snapshots. It teaches assistants how to systematically identify memory leaks, diagnose retention patterns, and suggest fixes.

For MCP server setup and tool reference, see the MCP server README. For general MemLab usage (test scenarios, CLI, programmatic API), see the AI Assistant Guide.

This method is also packaged as the `memlab-analyze-heap-snapshot` Agent Skill, which Claude Code and Codex users get with the memlab plugin.

Step 0: Obtain the Snapshot

memlab_load_snapshot takes a local absolute path to a .heapsnapshot file (e.g. /tmp/snapshot.heapsnapshot). If only a gzipped copy exists (/tmp/snapshot.heapsnapshot.gz), pass the path without .gz and the server decompresses it. If the snapshot is on a remote server, download it first:

bash
curl -o /tmp/snapshot.heapsnapshot <URL>

Then proceed to Step 1.

Working with multiple snapshots

Pass keep_previous: true to memlab_load_snapshot to keep earlier snapshots resident (for before/after diffing or app-to-app comparison). Each loaded snapshot gets a handle; use memlab_snapshots to list them, switch the active one (action: "switch", handle: "..."), or unload one to free memory (action: "unload"). Node ids are only valid within the snapshot they came from — switch to the right handle before reusing an id. Each resident snapshot holds its full graph in memory, so watch the server's RSS for multi-GB heaps; unload snapshots you're done with.

Step 1: Load and Triage

  1. Call memlab_load_snapshot with the file path.
  2. Read the quick diagnosis output carefully — it flags the highest-severity

issues immediately.

  1. Call memlab_quick_diagnosis for a combined overview in one call — it

returns snapshot summary, top objects by retained size, a class histogram (retained size shown as a lower/upper-bound range by default), and duplicated strings. This saves 3-4 round trips compared to calling each tool separately. Pass exact_retained_size:true only if the user explicitly wants exact per-class retained sizes — that adds a per-class dominator walk that can stall on very large heaps.

  1. Call memlab_auto_investigate for deep analysis — it finds the top retained

objects, traces retainer chains with severity scoring (CRITICAL/HIGH/MEDIUM/LOW), identifies pinch points, detects unbounded caches, scans for pending Promises, summarizes object shape clusters, and extracts source file hints from retainer paths. It also merges multi-path retention (one subtree reached via several retainers is reported once, with correct — never >100% — combined retained size) and runs framework detectors: OpenTelemetry metric cardinality explosion, Relay store growth, suspended async-function frames, undici pool buffering, and AsyncLocalStorage/TCP context retention.

  1. If you need more detail, call memlab_check_health for comprehensive

prioritized triage.

  1. Note the environment (Browser vs Node.js) from the output — this determines

which tools are relevant.

Parallel-safe tools: After memlab_load_snapshot, all analysis tools are read-only and can be called concurrently. Batch independent calls in a single message for parallel execution. For example, call memlab_quick_diagnosis and memlab_auto_investigate together to cut analysis time in half.

Step 2: Choose an Investigation Path

Based on the triage results, follow the most relevant path below. You may need to follow multiple paths if several issues are flagged.

Path A: String Waste (duplicated/large strings)

Triggered when: triage shows high string duplication or strings consuming >30% of heap.

  1. memlab_duplicated_strings — identify top duplicated strings by total

retained size and per-entry savings. Use include_node_ids: true only when you plan to follow up with retainer_summary (omitting node IDs saves tokens per entry).

  1. memlab_intern_opportunities — start here for interning: groups

duplicated strings by the property name and parent object shape that holds them, showing total savings per (property × shape) combination, split into within-load / co-retained / cross-load buckets with a Dup × column (copies ÷ unique). Pass summary_only: true for a compact triage view (headline split + one-line verdict + ranked table only) when screening many snapshots. This replaces the manual workflow of duplicated_strings → retainer_summary → codebase grep.

  1. memlab_string_patterns — group strings by prefix to find families (API

responses, IDs, URLs)

  1. memlab_sliced_strings — check if small substrings keep massive parent

strings alive

  1. For the top duplicated string: memlab_retainer_summary with

class_name: "string" or use node_ids from the duplicated_strings output (with include_node_ids: true) to cluster retainer patterns. Use compact: true and framework_filter: true to reduce token usage.

  1. Follow the dominant retainer chain to identify the code path creating

duplicates

Common fixes:

  • Duplicated short strings from JSON.parse() or API responses → string

interning with a Map<string, string> pool at ingestion time

  • SlicedStrings keeping large parents alive → copy the substring:

str.slice(start, end) doesn't free the parent; use Buffer.from(str).toString() or concatenation to create an independent copy

  • Large serialized payloads held in closures → release references after parsing
Path B: DOM Leaks (browser snapshots only)

Triggered when: triage shows detached DOM elements.

  1. memlab_detached_dom — find detached DOM elements still retained
  2. memlab_detached_dom with group_by: "retainer" — group detached nodes by

what's retaining them (answers "which component is leaking the most DOM?")

  1. memlab_detached_dom with group_by: "element" — group by HTML tag to see

distribution

  1. memlab_detached_dom with group_by: "testid" — group by data-testid

attribute (most useful for React apps)

  1. Pick the top entry by retained size → memlab_retainer_trace with its

node ID

  1. If a closure appears in the retainer chain → memlab_closure_inspection on

the closure node to see captured variables

  1. memlab_stale_collections — find Map/Set/Array holding detached DOM

references. Use min_stale_count: 5 or min_stale_retained_size: 10240 to filter trivially small stale collections.

  1. memlab_find_by_property with __reactFiber$ to find React components

still referencing detached nodes

Common fixes:

  • Missing removeEventListener in cleanup / useEffect return
  • React refs not cleared on unmount
  • Global event handlers capturing component scope
  • Stale entries in a cache Map — use WeakRef or clear on unmount
Path C: Object Accumulation / Unbounded Growth

Triggered when: triage shows classes with >10,000 instances or a single object retaining >5% of heap.

  1. memlab_class_histogram — see per-class instance counts and self sizes. It

runs with include_retained_size: false by default (fast single O(N) pass, sorted by self size) — the safe default on large heaps. Only pass include_retained_size: true if the user EXPLICITLY asks for dominator-aware retained sizes; that path walks the dominator tree and can be slow or time out on very large heaps (deep PromiseReaction/Context chains). Use suppress_suggestions: true on repeat calls to save tokens.

  1. memlab_shape_histogram — group generic Object instances by property

structure to identify distinct record types (often reveals 3-5 distinct shapes behind millions of "Object" instances). Retained size per shape is a lower/upper-bound range by default; pass exact_retained_size:true (slow on huge heaps) for the exact dominator-deduped value.

  1. memlab_cache_analysis — scan for unbounded Map/Set/Array caches with high

entry counts and no eviction. Also detects ad-hoc TTL caches, configured caches, warm-on-boot caches, and globalThis registries. Use detect_identical_entries: true to flag caches with structurally identical entries (suggests caching once instead of per-key). 3b. memlab_object_cost_breakdown — when a cache uses more memory than expected, this tool shows the V8 overhead breakdown (object headers, heap numbers vs SMIs, collection storage) and compares to theoretical minimum

  1. memlab_pinch_points — find small objects retaining disproportionately

large subtrees (best candidates to free)

  1. For the top anomalous class: memlab_retainer_summary with its class

name — this samples instances and groups retainer chains by shape. Use compact: true for abbreviated paths and framework_filter: true to hide V8/Node.js internals (system / Context, PromiseReaction, module cache patterns). The tool uses early termination — if the first 5 samples all share the same pattern, it stops and reports high confidence.

  1. If a single large retainer: memlab_trace_dominators to auto-walk the

dominator tree from the top retainer to the actual data in one call (replaces 10+ sequential get_references calls)

  1. memlab_object_shape on representative instances to understand

structure — use node_ids parameter to batch-inspect multiple nodes in one call

  1. For growth detection: memlab_diff_snapshots comparing a before and after

snapshot

Common fixes:

  • Unbounded cache → add LRU eviction or use WeakMap/WeakSet
  • Event listener accumulation → ensure symmetric add/remove
  • Module-level arrays that grow per-request (Node.js) → scope to request

lifecycle

Path D: Closure Leaks

Triggered when: large closures appear in retainer traces, or class_histogram shows many closures.

  1. memlab_find_nodes_by_class with class name of the closure's function

name (if known)

  1. memlab_closure_inspection on the closure node — shows captured variables

and their sizes

  1. Identify which captured variable is unexpectedly large
  2. memlab_retainer_trace on the large captured variable to understand why

it's retained

Common fixes:

  • Closure captures entire object when only one property is needed →

destructure before creating closure

  • Timer callbacks (setInterval) not cleared → clear in cleanup
  • Promise chains holding references to resolved data → let data flow through,

don't capture in outer scope

Path E: Global Variable Bloat

Triggered when: triage shows significant global variable retained size.

  1. memlab_global_variables — list non-built-in globals by retained size
  2. For top entries: memlab_get_references to see what they point to
  3. memlab_dominator_subtree to understand total memory impact

Common fixes:

  • Module caches growing without bounds → add eviction
  • Debug/dev globals left in production → gate behind __DEV__
  • Polyfill-installed globals → evaluate if still needed
Path F: Subscription/Listener Accumulation

Triggered when: auto_investigate or check_health reports shapes with callback/handler/listener + context properties in high counts.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
5,061
Repository forks
148
7-day trend score
48

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/facebook/memlab/mcp-server/badge)](https://verified-skill.com/skills/facebook/memlab/mcp-server)

Something wrong with this skill or its page? Tell us.