Extracting Variables and Tokens from Figma with get_variable_defs
You can extract complete design token definitions from any Figma file by asynchronously enumerating local variable collections, resolving each variable ID with getVariableByIdAsync, and serializing the returned metadata including modes, scopes, and code syntax.
The figma/mcp-server-guide repository demonstrates how to programmatically harvest design-system assets using headless Figma plugins. This guide covers the canonical pattern—often referred to as get_variable_defs—for pulling variable definitions (tokens) from Figma's Variable API.
The Variable Extraction Pipeline
Figma's Variable API requires a three-step resolution process. Unlike simpler APIs, there is no single "list all variables" endpoint; you must traverse collections and resolve IDs individually to access token data.
Enumerating Local Collections
Begin by fetching all variable collections defined in the current file using figma.variables.getLocalVariableCollectionsAsync(). This returns an array of VariableCollection objects, each representing a logical group like "Colors" or "Spacing" and containing an array of variable IDs.
const collections = await figma.variables.getLocalVariableCollectionsAsync();
According to the source code in skills/figma-generate-library/scripts/inspectFileStructure.js (line 46), this is the entry point for all variable extraction operations.
Resolving Variable Definitions
Each collection exposes its members through the variableIds property. To obtain full variable objects—including names, types, and values—you must map these IDs through figma.variables.getVariableByIdAsync(id). The repository implements this as a parallel fetch using Promise.all for performance.
const vars = await Promise.all(
coll.variableIds.map(id => figma.variables.getVariableByIdAsync(id))
);
This pattern appears at line 49 of inspectFileStructure.js and constitutes the core "get variable definitions" logic.
Assembling Token Metadata
Once resolved, each Variable object contains rich metadata. Extract per-mode values using getValueForMode(modeId) and platform-specific code syntax via getVariableCodeSyntax(). The repository aggregates these into plain objects for JSON serialization.
Key properties to capture:
- name: The token identifier (e.g., "primary/500")
- type: The data type (
COLOR,FLOAT,STRING,BOOLEAN) - scopes: Allowed binding contexts (e.g.,
PAINT,TEXT_CONTENT) - modes: Mode-specific values (light/dark themes)
- codeSyntax: Platform naming conventions (CSS, Swift, etc.)
Implementation Walkthrough
The canonical implementation lives in skills/figma-generate-library/scripts/inspectFileStructure.js. This script walks every collection, resolves each variable ID, and builds an inventory of the file's design tokens.
The workflow follows this exact sequence:
- Retrieve collections via
getLocalVariableCollectionsAsync - Iterate
variableIdsarrays (line 48) - Resolve definitions with
getVariableByIdAsync(line 49) - Extract metadata fields (lines 51-58)
For state reconstruction or drift detection, skills/figma-generate-library/scripts/rehydrateState.js (lines 60-70) demonstrates how to persist these definitions for later comparison against a source-of-truth JSON file.
Practical Code Examples
These self-contained snippets work in headless Figma plugin environments, matching the MCP Server Guide's execution context.
Extract All Variables with Full Metadata
This function implements the complete get_variable_defs pattern, returning a JSON-serializable array of all tokens:
async function extractAllVariables() {
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const result = [];
for (const coll of collections) {
const vars = await Promise.all(
coll.variableIds.map(id => figma.variables.getVariableByIdAsync(id))
);
for (const v of vars.filter(Boolean)) {
const modes = {};
for (const mode of coll.modes) {
modes[mode.name] = v.getValueForMode(mode.modeId);
}
result.push({
collection: coll.name,
id: v.id,
name: v.name,
type: v.type,
scopes: v.scopes,
modes,
codeSyntax: v.getVariableCodeSyntax()
});
}
}
return result;
}
Filter Variables by Collection Name
To extract only tokens from a specific collection (e.g., "Colors"):
async function getVariablesByCollection(collectionName) {
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const target = collections.find(c => c.name === collectionName);
if (!target) return [];
const vars = await Promise.all(
target.variableIds.map(id => figma.variables.getVariableByIdAsync(id))
);
return vars.filter(Boolean).map(v => ({
id: v.id,
name: v.name,
type: v.type,
value: v.getValueForMode(target.modes[0].modeId)
}));
}
Export to JSON for CI Pipelines
Headless plugins can post extracted data back to the host process:
(async () => {
const allVariables = await extractAllVariables();
const json = JSON.stringify(allVariables, null, 2);
figma.ui.postMessage({
type: 'variablesExport',
payload: json
});
figma.closePlugin();
})();
Core Files in the Repository
| File | Purpose |
|---|---|
skills/figma-generate-library/scripts/inspectFileStructure.js |
Full inventory implementation showing collection enumeration and variable resolution |
skills/figma-generate-library/scripts/rehydrateState.js |
State collection and persistence for token comparison |
skills/figma-generate-library/scripts/createSemanticTokens.js |
Demonstrates variable creation after extraction |
skills/figma-use/references/variable-patterns.md |
Design system best practices for naming and scoping |
Summary
- Use
getLocalVariableCollectionsAsyncto discover all variable collections in a Figma file - Resolve IDs individually via
getVariableByIdAsync—there is no bulk fetch endpoint - Extract mode-specific values with
getValueForMode()to capture theme variations - Serialize code syntax using
getVariableCodeSyntax()for platform-specific token names - Reference
inspectFileStructure.jsin thefigma/mcp-server-guiderepository for the canonical implementation
Frequently Asked Questions
How do I extract variables from a specific Figma file using the MCP Server Guide?
Load the headless plugin environment from the figma/mcp-server-guide repository and invoke figma.variables.getLocalVariableCollectionsAsync() to enumerate collections. Then iterate through each collection's variableIds array, calling figma.variables.getVariableByIdAsync(id) for every ID to resolve the full variable definition including type, scopes, and values.
What is the difference between a VariableCollection and a Variable in Figma's API?
A VariableCollection is a logical grouping (such as "Colors" or "Typography") that contains an array of variableIds. A Variable is the atomic token object containing the actual name, data type, allowed scopes, and per-mode values. You must traverse collections to discover variable IDs before you can resolve the variable definitions themselves.
Can I export Figma variables directly to a JSON token format?
Yes. After resolving variables with getVariableByIdAsync, assemble the metadata into a plain object structure including name, type, modes, and codeSyntax. Use JSON.stringify() to serialize the array, then write to disk via the plugin's fs API or post the payload to a host process using figma.ui.postMessage() for CI pipeline integration.
Why does the extraction require multiple async calls instead of a single list endpoint?
Figma's Variable API design separates collections (which hold ID references) from variable objects (which hold data). This architecture supports complex aliasing and mode-specific values. The pattern demonstrated in inspectFileStructure.js uses Promise.all() to parallelize the ID resolution, minimizing the performance impact of the required N+1 query pattern.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →