Skip to content

Instantly share code, notes, and snippets.

@eonist
Created May 29, 2025 08:19
Show Gist options
  • Save eonist/b9e2b8f34449f5a472921fdf32791a2d to your computer and use it in GitHub Desktop.
Save eonist/b9e2b8f34449f5a472921fdf32791a2d to your computer and use it in GitHub Desktop.
comment improvements

Looking at the additional TypeScript files you've provided, here are the improved JSDoc comments for each:

effect-tools.ts Improvements

/**
 * Registers effect-related styling commands for the MCP server.
 * 
 * This module provides comprehensive effect management tools including:
 * - Direct effect application with custom parameters (shadows, blurs, etc.)
 * - Effect style variable application for reusable effects
 * - Batch operations for efficient bulk updates
 * - Support for multiple effect types (DROP_SHADOW, INNER_SHADOW, LAYER_BLUR, etc.)
 * 
 * Registered commands:
 * - `set_effect`: Applies effects directly or via style variables to nodes
 * - `create_effect_style_variable`: Creates reusable effect style variables
 * 
 * @param {McpServer} server - The MCP server instance to register tools on
 * @param {FigmaClient} figmaClient - The Figma client for API communication
 * @returns {void}
 * 
 * @example
 * ```
 * registerEffectTools(server, figmaClient);
 * 
 * // Apply a drop shadow effect directly
 * await figmaClient.executeCommand('set_effect', {
 *   entries: {
 *     nodeId: "123:456",
 *     effects: {
 *       type: "DROP_SHADOW",
 *       color: { r: 0, g: 0, b: 0, a: 0.25 },
 *       radius: 4,
 *       offset: { x: 0, y: 2 }
 *     }
 *   }
 * });
 * 
 * // Apply via style variable
 * await figmaClient.executeCommand('set_effect', {
 *   entries: { nodeId: "123:456", effectStyleId: "S:effect123" }
 * });
 * ```
 * 
 * @throws {Error} When nodeId is invalid or malformed
 * @throws {Error} When neither effects nor effectStyleId is provided
 * @throws {Error} When effect parameters are invalid (missing required properties)
 */
export function registerEffectTools(server: McpServer, figmaClient: FigmaClient) {

effects-tools.ts Improvements

/**
 * Registers legacy effect-related commands on the MCP server.
 * 
 * This module provides backward compatibility for effect styling operations.
 * It focuses on applying predefined effect styles to individual nodes.
 * 
 * **Note**: This module is complementary to `effect-tools.ts` which provides
 * more comprehensive effect management capabilities including batch operations
 * and direct effect application.
 * 
 * Registered commands:
 * - `apply_effect_style`: Applies predefined effect styles to individual nodes
 * 
 * @param {McpServer} server - The MCP server instance to register the tools on
 * @param {FigmaClient} figmaClient - The Figma client used to execute commands against the Figma API
 * @returns {void} This function does not return a value but registers the tools asynchronously
 * 
 * @example
 * ```
 * registerEffectsTools(server, figmaClient);
 * 
 * // Apply an effect style to a node
 * const result = await figmaClient.executeCommand('apply_effect_style', {
 *   nodeId: "123:456",
 *   effectStyleId: "S:effect123"
 * });
 * ```
 * 
 * @throws {Error} When nodeId is invalid or not in proper Figma format
 * @throws {Error} When effectStyleId is empty, too long, or references non-existent style
 * @throws {Error} When the specified node doesn't support effects
 * 
 * @see {@link registerEffectTools} - For comprehensive effect management with batch operations
 */
export function registerEffectsTools(server: McpServer, figmaClient: FigmaClient) {

fill-tools.ts Improvements

/**
 * Registers fill and stroke styling commands for the MCP server.
 * 
 * This module provides unified tools for managing visual styling properties
 * on Figma nodes, including fill colors, stroke colors, and stroke weights.
 * Supports both single node operations and efficient batch processing.
 * 
 * Registered commands:
 * - `set_fill_and_stroke`: Sets fill/stroke colors and stroke weight on nodes
 * - `get_fill_and_stroke`: Retrieves current fill/stroke properties from nodes
 * 
 * @param {McpServer} server - The MCP server instance to register tools on
 * @param {FigmaClient} figmaClient - The Figma client for API communication
 * @returns {void}
 * 
 * @example
 * ```
 * registerFillTools(server, figmaClient);
 * 
 * // Set fill and stroke on a single node
 * await figmaClient.executeCommand('set_fill_and_stroke', {
 *   nodeId: "123:456",
 *   fillColor: { r: 1, g: 0, b: 0, a: 1 }, // Red fill
 *   strokeColor: { r: 0, g: 0, b: 1, a: 1 }, // Blue stroke
 *   strokeWeight: 2
 * });
 * 
 * // Batch operation on multiple nodes
 * await figmaClient.executeCommand('set_fill_and_stroke', {
 *   nodeIds: ["123:456", "789:101"],
 *   fillColor: { r: 0, g: 1, b: 0, a: 0.8 } // Semi-transparent green
 * });
 * 
 * // Get current styling properties
 * const styles = await figmaClient.executeCommand('get_fill_and_stroke', {
 *   nodeId: "123:456"
 * });
 * ```
 * 
 * @throws {Error} When both nodeId and nodeIds are provided (mutually exclusive)
 * @throws {Error} When neither nodeId nor nodeIds is provided
 * @throws {Error} When no style properties (fillColor, strokeColor, strokeWeight) are specified for set operations
 * @throws {Error} When node IDs are invalid or malformed
 */
export function registerFillTools(server: McpServer, figmaClient: FigmaClient) {

font-tools.ts Improvements

/**
 * Registers font management commands on the MCP server.
 * 
 * This module provides essential font loading capabilities for Figma text operations.
 * Font loading is a prerequisite for applying text styles, as fonts must be
 * asynchronously loaded before they can be used in text formatting operations.
 * 
 * **Important**: Always load fonts before applying text styles that use them,
 * as Figma requires fonts to be explicitly loaded for text manipulation.
 * 
 * Registered commands:
 * - `load_font_async`: Loads a specific font family and style asynchronously
 * 
 * @param {McpServer} server - The MCP server instance to register the tools on
 * @param {FigmaClient} figmaClient - The Figma client used to execute commands against the Figma API
 * @returns {void} This function does not return a value but registers the tools asynchronously
 * 
 * @example
 * ```
 * registerFontTools(server, figmaClient);
 * 
 * // Load a font before using it
 * await figmaClient.executeCommand('load_font_async', {
 *   family: 'Roboto',
 *   style: 'Regular'
 * });
 * 
 * // Load multiple font styles
 * await figmaClient.executeCommand('load_font_async', {
 *   family: 'Inter',
 *   style: 'Bold'
 * });
 * 
 * // Now you can safely apply text styles using these fonts
 * ```
 * 
 * @throws {Error} When font family name is invalid or not available in Figma
 * @throws {Error} When font style is not available for the specified family
 * @throws {Error} When font loading fails due to network or permission issues
 * 
 * @see {@link registerTextStyleTools} - For applying loaded fonts to text nodes
 */
export function registerFontTools(server: McpServer, figmaClient: FigmaClient) {

gradient-tools.ts Improvements

/**
 * Registers gradient-related styling commands for the MCP server.
 * 
 * This module provides comprehensive gradient management capabilities including:
 * - Creating reusable gradient style variables with custom parameters
 * - Applying gradients directly to nodes with full customization
 * - Applying existing gradient styles to nodes for consistency
 * - Support for all gradient types (LINEAR, RADIAL, ANGULAR, DIAMOND)
 * - Batch operations for efficient bulk gradient application
 * - Flexible application targets (FILL, STROKE, or BOTH)
 * 
 * Registered commands:
 * - `create_gradient_style`: Creates one or more reusable gradient style variables
 * - `set_gradient`: Applies gradients directly or via style variables to nodes
 * 
 * @param {McpServer} server - The MCP server instance to register tools on
 * @param {FigmaClient} figmaClient - The Figma client for API communication
 * @returns {void}
 * 
 * @example
 * ```
 * registerGradientTools(server, figmaClient);
 * 
 * // Create a gradient style variable
 * await figmaClient.executeCommand('create_gradient_style', {
 *   gradients: {
 *     name: "Primary Gradient",
 *     gradientType: "LINEAR",
 *     stops: [
 *       { position: 0, color: [1][1] }, // Red at start
 *       { position: 1, color: [1][1] }  // Blue at end
 *     ]
 *   }
 * });
 * 
 * // Apply gradient directly to a node
 * await figmaClient.executeCommand('set_gradient', {
 *   entries: {
 *     nodeId: "123:456",
 *     gradientType: "RADIAL",
 *     stops: [
 *       { position: 0, color: [1][1][1][1] },
 *       { position: 1, color: [0, 0, 0, 0.5] }
 *     ],
 *     applyTo: "FILL"
 *   }
 * });
 * 
 * // Apply existing gradient style
 * await figmaClient.executeCommand('set_gradient', {
 *   entries: {
 *     nodeId: "789:101",
 *     gradientStyleId: "S:gradient123",
 *     applyTo: "STROKE"
 *   }
 * });
 * 
 * // Batch gradient application
 * await figmaClient.executeCommand('set_gradient', {
 *   entries: [
 *     { nodeId: "123:456", gradientStyleId: "S:gradient123", applyTo: "FILL" },
 *     { nodeId: "789:101", gradientStyleId: "S:gradient456", applyTo: "BOTH" }
 *   ]
 * });
 * ```
 * 
 * @throws {Error} When gradient parameters are invalid (insufficient stops, invalid colors, etc.)
 * @throws {Error} When node IDs are malformed or reference non-existent nodes
 * @throws {Error} When gradient style IDs are invalid or reference non-existent styles
 * @throws {Error} When color values are outside the valid range (0-1)
 * @throws {Error} When stop positions are outside the valid range (0-1)
 * @throws {Error} When neither direct gradient parameters nor style ID is provided
 * 
 * @see {@link registerFillTools} - For solid color fills and strokes
 * @see {@link registerEffectTools} - For visual effects that can complement gradients
 */
export function registerGradientTools(server: McpServer, figmaClient: FigmaClient) {

index.ts Improvements

/**
 * Main registration module for all styling-related MCP commands.
 * 
 * This module serves as the central orchestrator for registering all styling tools
 * with the MCP server. It provides a unified entry point for enabling comprehensive
 * styling capabilities across the Figma MCP integration.
 * 
 * **Registered tool categories:**
 * - **Fill & Stroke Tools**: Solid colors, stroke weights, and basic styling
 * - **Gradient Tools**: Linear, radial, angular, and diamond gradients with style variables
 * - **Effect Tools**: Shadows, blurs, and other visual effects with batch support
 * - **Legacy Effects Tools**: Backward compatibility for effect style application
 * - **Style Tools**: General styling utilities and node style management
 * - **Text Style Tools**: Typography styling, text formatting, and text-specific effects
 * - **Font Tools**: Font loading and management for text operations
 * 
 * **Architecture**: This module follows a modular registration pattern where each
 * tool category is implemented in its own module and registered independently,
 * allowing for granular control and maintainability.
 * 
 * @param {McpServer} server - The MCP server instance to register all styling tools on
 * @param {FigmaClient} figmaClient - The Figma client for API communication across all tools
 * @returns {void}
 * 
 * @example
 * ```
 * import { registerStyleCommands } from './styling';
 * import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
 * import { FigmaClient } from '../../../clients/figma-client';
 * 
 * const server = new McpServer();
 * const figmaClient = new FigmaClient();
 * 
 * // Register all styling commands at once
 * registerStyleCommands(server, figmaClient);
 * 
 * // Now all styling commands are available:
 * // - set_fill_and_stroke, get_fill_and_stroke
 * // - create_gradient_style, set_gradient
 * // - set_effect, apply_effect_style
 * // - load_font_async
 * // - text styling commands
 * // - general style utilities
 * ```
 * 
 * @see {@link registerFillTools} - For fill and stroke color management
 * @see {@link registerGradientTools} - For gradient creation and application
 * @see {@link registerEffectTools} - For comprehensive effect management
 * @see {@link registerEffectsTools} - For legacy effect style application
 * @see {@link registerStyleTools} - For general styling utilities
 * @see {@link registerTextStyleTools} - For typography and text formatting
 * @see {@link registerFontTools} - For font loading and management
 * 
 * @since 1.0.0
 */
export function registerStyleCommands(server: McpServer, figmaClient: FigmaClient): void {

Key Improvements Made:

Comprehensive Module Descriptions: Each function now has detailed descriptions explaining its specific role and how it fits into the larger styling ecosystem.

Clear Command Listings: Explicitly documented which commands each module registers for easy reference.

Practical Examples: Added realistic code examples showing common usage patterns for each module.

Error Documentation: Comprehensive @throws documentation covering all potential error conditions.

Cross-References: Added @see tags linking related modules and complementary functionality.

Architecture Notes: Explained the relationship between modules (e.g., effects-tools.ts vs effect-tools.ts).

Usage Context: Provided context about when and why to use each module's capabilities.

Batch Operation Examples: Showed both single and batch operation examples where applicable.

Parameter Validation: Documented validation rules and constraints for inputs.

Performance Considerations: Highlighted batch operations and efficiency considerations.

These improvements provide comprehensive documentation that will enhance developer experience, improve code maintainability, and provide better IntelliSense support in IDEs.

Citations: [1] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/b3cdf830-1f68-427e-b670-2f21008ce1bc/effect-tools.ts [2] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/f5cf1591-cab7-4ac2-86cb-74563c723643/effects-tools.ts [3] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/4dc2d82b-3910-4480-9f20-5d51747b33b7/fill-tools.ts [4] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/f9e2e27a-b7c9-49ab-a639-7acca9e9545a/font-tools.ts [5] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/e2920ad5-0090-42d3-ba39-dfe883c0d659/gradient-tools.ts [6] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/a7e79fb1-57a0-4795-bdd2-2b8095a32d00/index.ts [7] https://deliciousreverie.co.uk/posts/types-via-jsdoc-or-typescript/ [8] https://github.com/SoftwareBrothers/better-docs [9] https://dev.to/artxe2/how-to-set-up-jsdoc-for-npm-packages-1jm1 [10] https://www.ciccarello.me/blog/2024/02/17/trying-out-typescript-in-jsdoc-comments/ [11] https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html [12] https://www.reddit.com/r/vuejs/comments/st2zkt/jsdoc_or_typescript/ [13] https://dev.to/samuel-braun/boost-your-javascript-with-jsdoc-typing-3hb3 [14] jsdoc/jsdoc#1645 [15] https://blog.chainsafe.io/documenting-typescript-finding-the-right-tools-for-your-project/ [16] https://www.pullrequest.com/blog/leveraging-jsdoc-for-better-code-documentation-in-javascript/


Answer from Perplexity: pplx.ai/share

@eonist
Copy link
Author

eonist commented May 29, 2025

Looking at the TypeScript files provided, I can see several areas where JSDoc documentation can be significantly improved. The current code has minimal or missing JSDoc comments, which reduces code maintainability and developer experience.

Main Index File Improvements

/**
 * Registers all document manipulation commands and tools for the Figma MCP server.
 * This is the main entry point for all document-related functionality including
 * selection tools, document tools, and creation commands.
 * 
 * @param server - The MCP server instance to register tools with
 * @param figmaClient - The Figma client instance for executing commands
 * @example
 * ```
 * const server = new McpServer();
 * const figmaClient = new FigmaClient();
 * registerDocumentCommands(server, figmaClient);
 * ```
 */
export function registerDocumentCommands(server: McpServer, figmaClient: FigmaClient) {
    // Register selection modification tools (set selection, etc.)
    registerSelectionModifyTools(server, figmaClient);
    
    // Register selection query tools (get selection info)
    registerSelectionTools(server, figmaClient);
    
    // Register document creation commands (duplicate pages, etc.)
    registerDocumentCreationCommands(server, figmaClient);
    
    // Register document information tools (get document info, pages)
    registerDocumentTools(server, figmaClient);
}

Selection Tools Improvements

/**
 * Registers selection information retrieval tools for the Figma MCP server.
 * Provides read-only access to current selection state and properties.
 * 
 * @param server - The MCP server instance to register tools with
 * @param figmaClient - The Figma client instance for executing selection queries
 */
export function registerSelectionTools(server: McpServer, figmaClient: FigmaClient) {
    server.tool(
        MCP_COMMANDS.GET_SELECTION,
        `Get comprehensive information about the current selection in Figma.
        
        Returns detailed selection data including:
        - Node IDs and types of selected elements
        - Properties and attributes of selected nodes
        - Hierarchical relationships within selection
        
        Returns:
        - content: Array of objects with type "text" containing selection info as JSON
        `,
        {},
        {
            title: "Get Selection",
            idempotentHint: true,
            destructiveHint: false,
            readOnlyHint: true,
            openWorldHint: false,
            usageExamples: JSON.stringify([
                { description: "Get current selection info", input: {} }
            ]),
            edgeCaseWarnings: [
                "Returns an empty array if nothing is selected",
                "Selection info may include node IDs, types, and properties",
                "If multiple nodes are selected, the result is an array",
                "Large selections may return substantial JSON data"
            ],
            extraInfo: "Use this command to inspect the current selection context in the Figma document. Essential for understanding what elements are currently active."
        },
        async () => {
            try {
                const result = await figmaClient.executeCommand(MCP_COMMANDS.GET_SELECTION);
                const resultsArr = Array.isArray(result) ? result : [result];
                const response = { success: true, results: resultsArr };

                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(response)
                    }]
                };
            } catch (error) {
                const response = {
                    success: false,
                    error: {
                        message: error instanceof Error ? error.message : String(error),
                        results: [],
                        meta: {
                            operation: "get_selection",
                            params: {}
                        }
                    }
                };

                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(response)
                    }]
                };
            }
        }
    );
}

Document Tools Improvements

/**
 * Registers document information and page management tools for the Figma MCP server.
 * Provides read-only access to document structure, metadata, and page information.
 * 
 * @param server - The MCP server instance to register tools with
 * @param figmaClient - The Figma client instance for executing document queries
 */
export function registerDocumentTools(server: McpServer, figmaClient: FigmaClient) {
    /**
     * Tool: Get comprehensive document information
     * Retrieves full document structure, metadata, and settings
     */
    server.tool(
        MCP_COMMANDS.GET_DOCUMENT_INFO,
        `Get detailed information about the current Figma document.
        
        Provides comprehensive document data including:
        - Document metadata (name, version, permissions)
        - Page structure and hierarchy
        - Document-level settings and configurations
        - Asset libraries and shared styles
        
        Returns:
        - content: Array of objects with type "text" containing document info as JSON
        `,
        {},
        {
            title: "Get Document Info",
            idempotentHint: true,
            destructiveHint: false,
            readOnlyHint: true,
            openWorldHint: false,
            usageExamples: JSON.stringify([
                { description: "Get full document information", input: {} }
            ]),
            edgeCaseWarnings: [
                "Returns a large JSON object for complex documents",
                "May include document-level metadata, pages, and settings",
                "If the document is empty, the result may be minimal",
                "Large documents may have substantial response times"
            ],
            extraInfo: "Use this command to retrieve the full structure and metadata of the current Figma document. Essential for understanding document organization."
        },
        async () => {
            try {
                const result = await figmaClient.executeCommand(MCP_COMMANDS.GET_DOCUMENT_INFO);
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(result)
                    }]
                };
            } catch (error) {
                return {
                    content: [{
                        type: "text",
                        text: `Error getting document info: ${error instanceof Error ? error.message : String(error)}`
                    }]
                };
            }
        }
    );

    /**
     * Tool: Get document pages information
     * Retrieves information about all pages in the current document
     */
    server.tool(
        MCP_COMMANDS.GET_DOC_PAGES,
        `Get information about all pages in the current Figma document.
        
        Provides page-specific data including:
        - Page IDs, names, and metadata
        - Page order and organization
        - Basic page properties and settings
        
        Returns:
        - content: Array of objects with type "text" containing pages info as JSON
        `,
        {},
        {
            title: "Get Pages",
            idempotentHint: true,
            destructiveHint: false,
            readOnlyHint: true,
            openWorldHint: false,
            usageExamples: JSON.stringify([
                { description: "List all pages in document", input: {} }
            ]),
            edgeCaseWarnings: [
                "Returns information about all pages in the document",
                "Empty pages will still be included in the result",
                "If the document has no pages, an empty array will be returned"
            ],
            extraInfo: "Use this command to get a list of all pages in the current Figma document. Useful for navigation and page management operations."
        },
        async () => {
            try {
                const result = await figmaClient.getPages();
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(result)
                    }]
                };
            } catch (error) {
                return {
                    content: [{
                        type: "text",
                        text: `Error getting pages: ${error instanceof Error ? error.message : String(error)}`
                    }]
                };
            }
        }
    );
}

Selection Modify Tools Improvements

/**
 * Registers selection modification tools for the Figma MCP server.
 * Provides functionality to programmatically change the current selection state.
 * 
 * @param server - The MCP server instance to register tools with
 * @param figmaClient - The Figma client instance for executing selection commands
 */
export function registerSelectionModifyTools(server: McpServer, figmaClient: FigmaClient) {
    /**
     * Tool: Set current selection
     * Updates the active selection to specified node(s) by their IDs
     */
    server.tool(
        MCP_COMMANDS.SET_SELECTION,
        {
            description: `Set the current selection in Figma to the specified node(s) by ID.
            
            Allows precise control over which elements are selected:
            - Single node selection using nodeId parameter
            - Multiple node selection using nodeIds array
            - Validates node IDs before attempting selection
            - Reports success/failure for each node
            
            Returns:
            - content: Array of objects with type "text" containing selection result as JSON
            `,
            inputSchema: SetSelectionInputSchema,
            usageExamples: JSON.stringify([
                { 
                    description: "Select single node",
                    input: { nodeId: "123:456" }
                },
                { 
                    description: "Select multiple nodes",
                    input: { nodeIds: ["123:456", "789:101"] }
                }
            ]),
            extraInfo: "Node IDs must be valid Figma node identifiers and present on the current page. Returns detailed information about which nodes were successfully selected and which were not found."
        },
        async (params, { figmaClient }) => {
            try {
                const result = await figmaClient.executeCommand(MCP_COMMANDS.SET_SELECTION, params);
                const resultsArr = Array.isArray(result) ? result : [result];
                const response = { success: true, results: resultsArr };

                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(response)
                    }]
                };
            } catch (error) {
                const response = {
                    success: false,
                    error: {
                        message: error instanceof Error ? error.message : String(error),
                        results: [],
                        meta: {
                            operation: "set_selection",
                            params
                        }
                    }
                };

                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(response)
                    }]
                };
            }
        }
    );
}

Schema Documentation Improvements

/**
 * Zod validation schema for the set_selection command input parameters.
 * Ensures proper node ID format and validates input combinations.
 * 
 * @example
 * ```
 * // Valid single node selection
 * { nodeId: "123:456" }
 * 
 * // Valid multiple node selection  
 * { nodeIds: ["123:456", "789:101", "234:567"] }
 * ```
 */
export const SetSelectionInputSchema = z.object({
    /** 
     * A single Figma node ID to select.
     * Must be in the format "number:number" (e.g., "123:456")
     */
    nodeId: z.string()
        .refine(isValidNodeId, { 
            message: "Must be a valid Figma node ID in format 'number:number'." 
        })
        .optional()
        .describe("A single Figma node ID to select."),
    
    /** 
     * An array of Figma node IDs to select.
     * Each ID must be in the format "number:number"
     */
    nodeIds: z.array(
        z.string().refine(isValidNodeId, {
            message: "Each node ID must be a valid Figma node ID in format 'number:number'."
        })
    )
        .optional()
        .describe("An array of Figma node IDs to select."),
}).refine(
    (data) => data.nodeId || (Array.isArray(data.nodeIds) && data.nodeIds.length > 0),
    { 
        message: "You must provide either 'nodeId' for single selection or 'nodeIds' array for multiple selection." 
    }
).describe("Input schema for the set_selection command. Provide either 'nodeId' for single node selection or 'nodeIds' for multiple node selection.");

/**
 * Zod validation schema for the duplicate_page command input parameters.
 * Validates page ID format and optional naming parameters.
 * 
 * @example
 * ```
 * // Duplicate with auto-generated name
 * { pageId: "123:456" }
 * 
 * // Duplicate with custom name
 * { pageId: "123:456", newPageName: "My Custom Page Name" }
 * ```
 */
export const DuplicatePageSchema = z.object({
    /** 
     * The ID of the page to duplicate.
     * Must be a valid Figma page identifier.
     */
    pageId: z.string()
        .min(1, "Page ID cannot be empty")
        .describe("The ID of the page to duplicate."),
    
    /** 
     * Optional custom name for the duplicated page.
     * If not provided, Figma will auto-generate a name.
     */
    newPageName: z.string()
        .min(1, "Page name cannot be empty if provided")
        .optional()
        .describe("Optional name for the new page.")
});

Document Creation Improvements

/**
 * Registers document creation and manipulation commands for the Figma MCP server.
 * Provides functionality to create new pages and duplicate existing content.
 * 
 * @param server - The MCP server instance to register tools with
 * @param figmaClient - The Figma client instance for executing creation commands
 */
export function registerDocumentCreationCommands(server: McpServer, figmaClient: FigmaClient) {
    /**
     * Tool: Duplicate page
     * Creates a complete copy of an existing page with all its children and content
     */
    server.tool(
        MCP_COMMANDS.DUPLICATE_PAGE,
        `Duplicate a Figma page and all its children as a new page.
        
        Creates a complete copy including:
        - All child nodes and their properties
        - Layer hierarchy and organization
        - Styles and formatting
        - Component instances and overrides
        
        Returns:
        - content: Array of objects with type "text" containing new page info as JSON
        `,
        DuplicatePageSchema.shape,
        {
            title: "Duplicate Page",
            idempotentHint: false,
            destructiveHint: false,
            readOnlyHint: false,
            openWorldHint: false,
            usageExamples: JSON.stringify([
                { 
                    description: "Duplicate page with auto-generated name",
                    input: { pageId: "123:456" }
                },
                { 
                    description: "Duplicate page with custom name",
                    input: { pageId: "123:456", newPageName: "My Duplicated Page" }
                }
            ]),
            edgeCaseWarnings: [
                "Duplicates all children of the original page recursively",
                "The new page will have a unique name and independent children",
                "Large pages may take significant time to duplicate",
                "Component instances will maintain their connections"
            ],
            extraInfo: "Use this command to duplicate an entire page and its contents. Useful for creating page templates or backing up page states before major changes."
        },
        async (params: any) => {
            try {
                // Validate that the figmaClient has the required method
                if (typeof figmaClient.duplicatePage !== "function") {
                    throw new Error("FigmaClient does not implement duplicatePage method");
                }

                const result = await figmaClient.duplicatePage(params.pageId, params.newPageName);
                const response = {
                    success: true,
                    results: [result]
                };

                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(response)
                    }]
                };
            } catch (error: any) {
                const response = {
                    success: false,
                    error: {
                        message: `Error duplicating page: ${error instanceof Error ? error.message : String(error)}`,
                        results: [],
                        meta: {
                            operation: "duplicate_page",
                            params
                        }
                    }
                };

                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(response)
                    }]
                };
            }
        }
    );
}

These improvements provide comprehensive JSDoc documentation that includes detailed descriptions, parameter documentation, usage examples, return value specifications, and important warnings about edge cases. The documentation follows TypeScript and JSDoc best practices while making the code much more maintainable and developer-friendly.

Citations:
[1] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/0776f769-8e0a-446a-86f0-0622c90af44d/index.ts
[2] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/38c022fd-782a-417c-a675-c26462c71314/selection-tools.ts
[3] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/164833e4-bffb-4b15-81bc-637dcc0da328/document-tools.ts
[4] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/36f7422c-d7db-481f-8d09-8f49dff08b9c/selection-modify-tools.ts
[5] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/71e2367d-d62a-4dec-a831-10e84828a9df/set-selection-schema.ts
[6] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/d350905f-d8aa-44b5-95b5-0f17d5525254/document-creation-schema.ts
[7] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/9a4e5f81-1a3a-4fec-89fd-adca924e854e/document-creation.ts
[8] https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html
[9] https://www.jetbrains.com/help/rider/Creating_JSDoc_Comments.html
[10] https://jsdoc.app/about-getting-started
[11] https://www.youtube.com/watch?v=-gaLriaslpg
[12] https://www.youtube.com/watch?v=YK-GurROGIg
[13] https://johnnyreilly.com/typescript-jsdoc-and-intellisense
[14] https://stackoverflow.com/questions/66553490/how-do-i-annotate-react-forwardref-with-jsdoc-comments-so-that-intellisense-can
[15] https://jsdoc.app/
[16] jsdoc/jsdoc#272
[17] microsoft/TypeScript#14619


Answer from Perplexity: pplx.ai/share

@eonist
Copy link
Author

eonist commented May 29, 2025

Looking at the TypeScript files provided, I can see several areas where the JSDoc documentation can be significantly improved. Here are my recommendations for enhancing the documentation:

Function and Method Documentation

The current JSDoc comments are good but can be enhanced with more comprehensive parameter descriptions, return type specifications, and usage examples.

Enhanced JSDoc for registerComponentNodeTools

/**
 * Registers the unified batch/single component creation tool on the MCP server.
 * 
 * This function adds a tool named "create_components_from_nodes" to the MCP server,
 * enabling conversion of one or more Figma nodes into reusable components.
 * It validates input, executes the corresponding Figma command for each node, and returns the results.
 * 
 * @param {McpServer} server - The MCP server instance to register the tool on
 * @param {FigmaClient} figmaClient - The Figma client used to execute commands against the Figma API
 * @returns {void} This function does not return a value but registers the tool asynchronously
 * 
 * @throws {Error} Throws an error if the server or figmaClient is invalid
 * 
 * @example
 * ```
 * const server = new McpServer();
 * const figmaClient = new FigmaClient(apiKey);
 * registerComponentNodeTools(server, figmaClient);
 * ```
 * 
 * @since 1.0.0
 * @see {@link MCP_COMMANDS.CREATE_COMPONENTS_FROM_NODE} for the command constant
 */

Enhanced JSDoc for Schema Objects

/**
 * Zod schema for a single node-to-component conversion entry.
 * 
 * Validates the structure of data required to convert a Figma node into a component,
 * including node ID validation and optional position maintenance settings.
 * 
 * @typedef {Object} NodeToComponentEntry
 * @property {string} nodeId - The Figma node ID to convert (format: "123:456")
 * @property {boolean} [maintain_position] - Whether to maintain the node's position after conversion
 * 
 * @example
 * ```
 * const validEntry = {
 *   nodeId: "123:456",
 *   maintain_position: true
 * };
 * 
 * const result = NodeToComponentEntrySchema.parse(validEntry);
 * ```
 * 
 * @throws {ZodError} Throws validation error if nodeId format is invalid
 * @since 1.0.0
 */
export const NodeToComponentEntrySchema = z.object({
  // ... schema definition
});

Type Definitions and Interfaces

For better TypeScript integration, add comprehensive type documentation:

/**
 * Configuration options for component instance creation.
 * 
 * @interface ComponentInstanceConfig
 * @property {string} componentKey - Unique identifier for the component (1-100 characters)
 * @property {number} x - X coordinate on canvas (range: -10000 to 10000)
 * @property {number} y - Y coordinate on canvas (range: -10000 to 10000)
 * 
 * @example
 * ```
 * const config: ComponentInstanceConfig = {
 *   componentKey: "abc:123",
 *   x: 100,
 *   y: 200
 * };
 * ```
 */

Async Function Documentation

Enhance async function documentation with Promise return types:

/**
 * Creates component instances from the provided configuration entries.
 * 
 * Processes either a single entry or multiple entries in batch, creating
 * component instances at specified coordinates on the Figma canvas.
 * 
 * @async
 * @function
 * @param {Object} params - The parameters object
 * @param {ComponentInstanceEntrySchema} [params.entry] - Single instance configuration
 * @param {ComponentInstanceEntrySchema[]} [params.entries] - Multiple instance configurations
 * @returns {Promise}>} Promise resolving to operation results
 * 
 * @throws {Error} Throws error if neither entry nor entries is provided
 * @throws {FigmaAPIError} Throws error if Figma API call fails
 * 
 * @example
 * ```
 * // Single instance
 * const result = await createInstances({
 *   entry: { componentKey: "abc:123", x: 100, y: 200 }
 * });
 * 
 * // Multiple instances
 * const batchResult = await createInstances({
 *   entries: [
 *     { componentKey: "abc:123", x: 100, y: 200 },
 *     { componentKey: "def:456", x: 300, y: 400 }
 *   ]
 * });
 * ```
 * 
 * @since 1.0.0
 */

Module-Level Documentation

Add comprehensive module documentation at the top of each file:

/**
 * @fileoverview Component management tools for Figma MCP integration.
 * 
 * This module provides tools for creating, managing, and manipulating Figma components
 * through the Model Context Protocol (MCP) server. It includes functionality for:
 * - Converting nodes to components
 * - Creating component instances
 * - Managing component variants
 * - Batch operations for improved efficiency
 * 
 * @module ComponentTools
 * @version 1.0.0
 * @author Your Team Name
 * @since 2025-01-01
 * 
 * @requires @modelcontextprotocol/sdk/server/mcp
 * @requires ../../../clients/figma-client
 * @requires zod
 * 
 * @example
 * ```
 * import { registerComponentTools } from './component-tools.js';
 * 
 * const server = new McpServer();
 * const figmaClient = new FigmaClient(apiKey);
 * registerComponentTools(server, figmaClient);
 * ```
 */

Error Handling Documentation

Document error scenarios more comprehensively:

/**
 * @typedef {Object} OperationResult
 * @property {string} nodeId - The processed node ID
 * @property {string} [componentId] - Created component ID (if successful)
 * @property {boolean} success - Whether the operation succeeded
 * @property {string} [error] - Error message (if failed)
 * @property {Object} [meta] - Additional metadata about the operation
 * @property {string} meta.operation - The operation type performed
 * @property {Object} meta.params - The parameters used for the operation
 */

Enum and Constant Documentation

/**
 * Available sources for component retrieval.
 * 
 * @enum {string}
 * @readonly
 */
const ComponentSource = {
  /** Components from the current Figma document */
  LOCAL: 'local',
  /** Components from the team library */
  TEAM: 'team',
  /** Components from remote team libraries */
  REMOTE: 'remote'
} as const;

These improvements will provide better IDE support, clearer documentation for API consumers, and more maintainable code with comprehensive type information and usage examples.

Citations:
[1] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/d1f80619-0da7-4e8e-b430-c9a8fa866a33/index.ts
[2] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/0988f95e-db9f-4134-baef-a354ba1539a8/component-node-tools.ts
[3] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/07acfcf6-3cd7-4d50-bfe0-7aad0a06c947/create-components-from-node-schema.ts
[4] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/2ed48252-6448-43e8-ae58-1e095876bc74/create-component-instance-schema.ts
[5] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/872857e1-5c8f-4132-ae45-3c3735d0383a/get-components-schema.ts
[6] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/2e1006c6-f786-4642-9d77-e0b20975f74c/variant-schema.ts
[7] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/8095498f-49d5-4187-be0c-890c52e87823/instance-tools.ts
[8] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/ec91a4e7-8ece-4297-9464-63e15a3beeb0/component-tools.ts
[9] https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/attachments/60313916/717bc25b-de7a-4e74-afac-251f31d1929a/variant-tools.ts
[10] https://stackoverflow.com/questions/70812483/how-to-use-jsdoc-annotations-in-indexed-types
[11] https://www.jetbrains.com/help/webstorm/creating-jsdoc-comments.html
[12] https://dev.to/kabartolo/how-to-document-an-express-api-with-swagger-ui-and-jsdoc-50do
[13] jsdoc/jsdoc#272
[14] https://stackoverflow.com/questions/57205260/how-do-i-add-jsdoc-comments-to-typescript-generated-with-the-typescript-ast-api
[15] https://jsdoc.app/
[16] https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html
[17] microsoft/TypeScript#47718
[18] https://stackoverflow.com/questions/44306153/how-do-i-refer-to-another-typescript-type-in-comments-jsdoc
[19] microsoft/TypeScript#14619


Answer from Perplexity: pplx.ai/share

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment