Skip to main content
Glama
taurgis

SFCC Development MCP Server

by taurgis

generate_cartridge_structure

Creates organized cartridge directory structures with required files and configurations for Salesforce B2C Commerce Cloud development projects.

Instructions

Generate a complete cartridge directory structure with all necessary files and configurations. Use this when creating new cartridges to ensure proper organization and include all required components. This tool creates all necessary files directly in the specified target directory, ensuring the cartridge is created exactly where needed in your project structure.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cartridgeNameYesName of the cartridge (e.g., "plugin_example")
targetPathNoTarget directory path where the cartridge files should be placed. If not specified, files will be placed in the current working directory. Use absolute paths for best results (e.g., "/Users/username/projects/my-sfcc-project/").
fullProjectSetupNoWhether to create a complete project setup (package.json, webpack, etc.) or just add a cartridge to existing project structure. Use true for new projects, false to add cartridge to existing projects. Always send the root of the project directory as the targetPath.

Implementation Reference

  • Core handler function that executes the cartridge structure generation, handling both full project setup and cartridge-only modes by creating directories and files.
    async generateCartridgeStructure(options: CartridgeGenerationOptions): Promise<{
      success: boolean;
      message: string;
      createdFiles: string[];
      createdDirectories: string[];
      skippedFiles: string[];
    }> {
      const { cartridgeName, targetPath, fullProjectSetup = true } = options;
      const createdFiles: string[] = [];
      const createdDirectories: string[] = [];
      const skippedFiles: string[] = [];
    
      try {
        this.logger.info(`Starting cartridge generation for: ${cartridgeName}`);
    
        // Determine the working directory and normalize path
        let workingDir = targetPath ?? process.cwd();
        workingDir = this.normalizeTargetPath(workingDir);
    
        if (fullProjectSetup) {
          // Full project setup - create everything directly in the working directory
          this.logger.info(`Creating full project setup directly in: ${workingDir}`);
    
          // Ensure the working directory exists
          await this.ensureDirectory(workingDir);
          if (!createdDirectories.includes(workingDir)) {
            createdDirectories.push(workingDir);
          }
    
          // Create root files directly in working directory
          await this.createRootFiles(workingDir, cartridgeName, createdFiles, skippedFiles);
    
          // Create cartridge structure directly in working directory
          await this.createCartridgeStructure(workingDir, cartridgeName, createdFiles, createdDirectories, skippedFiles);
    
          return {
            success: true,
            message: `Successfully created full project setup for cartridge '${cartridgeName}' in '${workingDir}'`,
            createdFiles,
            createdDirectories,
            skippedFiles,
          };
        } else {
          // Cartridge-only setup - add to existing project
          const cartridgesDir = this.pathService.join(workingDir, 'cartridges');
    
          // Ensure cartridges directory exists
          await this.ensureDirectory(cartridgesDir);
          if (!createdDirectories.includes(cartridgesDir)) {
            createdDirectories.push(cartridgesDir);
          }
    
          // Create cartridge structure
          await this.createCartridgeStructure(workingDir, cartridgeName, createdFiles, createdDirectories, skippedFiles);
    
          return {
            success: true,
            message: `Successfully created cartridge '${cartridgeName}' in existing project at '${workingDir}'`,
            createdFiles,
            createdDirectories,
            skippedFiles,
          };
        }
      } catch (error) {
        this.logger.error('Error generating cartridge structure:', error);
        return {
          success: false,
          message: `Failed to generate cartridge structure: ${error instanceof Error ? error.message : 'Unknown error'}`,
          createdFiles,
          createdDirectories,
          skippedFiles,
        };
      }
    }
  • MCP protocol tool schema definition, including name, description, and detailed input schema with parameters and validation.
    export const CARTRIDGE_GENERATION_TOOLS = [
      {
        name: 'generate_cartridge_structure',
        description: 'Generate a complete cartridge directory structure with all necessary files and configurations. Use this when creating new cartridges to ensure proper organization and include all required components. This tool creates all necessary files directly in the specified target directory, ensuring the cartridge is created exactly where needed in your project structure.',
        inputSchema: {
          type: 'object',
          properties: {
            cartridgeName: {
              type: 'string',
              description: 'Name of the cartridge (e.g., "plugin_example")',
            },
            targetPath: {
              type: 'string',
              description: 'Target directory path where the cartridge files should be placed. If not specified, files will be placed in the current working directory. Use absolute paths for best results (e.g., "/Users/username/projects/my-sfcc-project/").',
            },
            fullProjectSetup: {
              type: 'boolean',
              description: 'Whether to create a complete project setup (package.json, webpack, etc.) or just add a cartridge to existing project structure. Use true for new projects, false to add cartridge to existing projects. Always send the root of the project directory as the targetPath.',
              default: true,
            },
          },
          required: ['cartridgeName'],
        },
      },
    ];
  • Tool registration configuration defining defaults, input validation schema, execution handler (delegating to client), and logging for the generate_cartridge_structure tool.
    export const CARTRIDGE_TOOL_CONFIG: Record<CartridgeToolName, GenericToolSpec<ToolArguments, any>> = {
      generate_cartridge_structure: {
        defaults: (args: ToolArguments) => ({
          ...args,
          fullProjectSetup: args.fullProjectSetup ?? true,
        }),
        validate: (args: ToolArguments, toolName: string) => {
          ValidationHelpers.validateArguments(args, CommonValidations.requiredField(
            'cartridgeName',
            'string',
            (value: string) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value),
            'cartridgeName must be a valid identifier (letters, numbers, underscore, hyphen)',
          ), toolName);
        },
        exec: async (args: ToolArguments, context: ToolExecutionContext) => {
          const client = context.cartridgeClient as CartridgeGenerationClient;
          return client.generateCartridgeStructure({
            cartridgeName: args.cartridgeName as string,
            targetPath: args.targetPath as string | undefined,
            fullProjectSetup: args.fullProjectSetup as boolean,
          });
        },
        logMessage: (args: ToolArguments) => `Generate cartridge structure for ${args.cartridgeName}`,
      },
    };
  • Handler class that registers and dispatches cartridge tools using the CARTRIDGE_TOOL_CONFIG, initializes the CartridgeGenerationClient, and provides execution context.
    export class CartridgeToolHandler extends BaseToolHandler<CartridgeToolName> {
      private cartridgeClient: CartridgeGenerationClient | null = null;
      private clientFactory: ClientFactory;
    
      constructor(context: HandlerContext, subLoggerName: string) {
        super(context, subLoggerName);
        this.clientFactory = new ClientFactory(context, this.logger);
      }
    
      protected async onInitialize(): Promise<void> {
        if (!this.cartridgeClient) {
          this.cartridgeClient = this.clientFactory.createCartridgeClient();
          this.logger.debug('Cartridge generation client initialized');
        }
      }
    
      protected async onDispose(): Promise<void> {
        this.cartridgeClient = null;
        this.logger.debug('Cartridge generation client disposed');
      }
    
      canHandle(toolName: string): boolean {
        return CARTRIDGE_TOOL_NAMES_SET.has(toolName as CartridgeToolName);
      }
    
      protected getToolNameSet(): Set<CartridgeToolName> {
        return CARTRIDGE_TOOL_NAMES_SET;
      }
    
      protected getToolConfig(): Record<string, GenericToolSpec<ToolArguments, any>> {
        return CARTRIDGE_TOOL_CONFIG;
      }
    
      protected async createExecutionContext(): Promise<ToolExecutionContext> {
        if (!this.cartridgeClient) {
          throw new Error('Cartridge generation client not initialized');
        }
    
        return {
          handlerContext: this.context,
          logger: this.logger,
          cartridgeClient: this.cartridgeClient,
        };
      }
    }
  • Helper function providing all file templates used in cartridge generation (package.json, webpack.config.js, .project, properties, etc.).
      private initializeTemplates(): CartridgeTemplates {
        return {
          packageJson: (cartridgeName: string) => ({
            name: cartridgeName,
            version: '0.0.1',
            description: 'New overlay cartridge',
            main: 'index.js',
            scripts: {
              'lint': 'npm run lint:css && npm run lint:js',
              'lint:css': 'sgmf-scripts --lint css',
              'lint:js': 'sgmf-scripts --lint js',
              'lint:fix': 'eslint cartridges --fix',
              upload: 'sgmf-scripts --upload -- ',
              uploadCartridge: `sgmf-scripts --uploadCartridge ${cartridgeName}`,
              'compile:js': 'sgmf-scripts --compile js',
              'compile:scss': 'sgmf-scripts --compile css',
            },
            devDependencies: {
              autoprefixer: '^10.4.14',
              bestzip: '^2.2.1',
              'css-loader': '^6.0.0',
              'css-minimizer-webpack-plugin': '^5.0.1',
              eslint: '^8.56.0',
              'eslint-config-airbnb-base': '^15.0.0',
              'eslint-config-prettier': '^9.1.0',
              'eslint-plugin-import': '^2.29.0',
              'mini-css-extract-plugin': '^2.7.6',
              'postcss-loader': '^7.0.0',
              sass: '^1.69.7',
              'sass-loader': '^13.3.2',
              'sgmf-scripts': '^3.0.0',
              shx: '^0.3.4',
              stylelint: '^15.4.0',
              'stylelint-config-standard-scss': '^11.0.0',
              'webpack-remove-empty-scripts': '^1.0.4',
            },
            browserslist: [
              'last 2 versions',
              'ie >= 10',
            ],
          }),
    
          dwJson: () => ({
            hostname: '',
            username: '',
            password: '',
            'code-version': '',
          }),
    
          webpackConfig: (cartridgeName: string) => `'use strict';
    
    var path = require('path');
    var MiniCssExtractPlugin = require('mini-css-extract-plugin');
    var CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
    var sgmfScripts = require('sgmf-scripts');
    var RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
    
    module.exports = [{
        mode: 'development',
        name: 'js',
        entry: sgmfScripts.createJsPath(),
        output: {
            path: path.resolve('./cartridges/${cartridgeName}/cartridge/static'),
            filename: '[name].js'
        }
    }, {
        mode: 'none',
        name: 'scss',
        entry: sgmfScripts.createScssPath(),
        output: {
            path: path.resolve('./cartridges/${cartridgeName}/cartridge/static')
        },
        module: {
            rules: [{
                test: /\\.scss$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        esModule: false
                    }
                },
                {
                    loader: 'css-loader',
                    options: {
                        url: false
                    }
                }, {
                    loader: 'postcss-loader',
                    options: {
                        postcssOptions: {
                            plugins: [require('autoprefixer')]
                        }
                    }
                }, {
                    loader: 'sass-loader',
                    options: {
                        implementation: require('sass'),
                        sassOptions: {
                            includePaths: [
                                path.resolve(path.resolve(process.cwd(), '../storefront-reference-architecture/node_modules/')),
                                path.resolve(process.cwd(), '../storefront-reference-architecture/node_modules/flag-icons/sass')
                            ]
                        }
                    }
                }]
            }]
        },
        plugins: [
            new RemoveEmptyScriptsPlugin(),
            new MiniCssExtractPlugin({
                filename: '[name].css',
                chunkFilename: '[name].css'
            })
        ],
        optimization: {
            minimizer: ['...', new CssMinimizerPlugin()]
        }
    }];`,
    
          dotProject: (cartridgeName: string) => `<?xml version="1.0" encoding="UTF-8"?>
    <projectDescription>
        <name>${cartridgeName}</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
            <buildCommand>
                <name>com.demandware.studio.core.beehiveElementBuilder</name>
                <arguments>
                </arguments>
            </buildCommand>
        </buildSpec>
        <natures>
            <nature>com.demandware.studio.core.beehiveNature</nature>
        </natures>
    </projectDescription>`,
    
          projectProperties: (cartridgeName: string) => `## cartridge.properties for cartridge ${cartridgeName}
    #demandware.cartridges.${cartridgeName}.multipleLanguageStorefront=true`,
    
          eslintrc: () => ({
            root: true,
            extends: 'airbnb-base/legacy',
            globals: {
              session: 'readonly',
              request: 'readonly',
            },
            rules: {
              'import/no-unresolved': 'off',
              indent: ['error', 4, { SwitchCase: 1, VariableDeclarator: 1 }],
              'func-names': 'off',
              'require-jsdoc': 'error',
              'valid-jsdoc': ['error', {
                preferType: {
                  Boolean: 'boolean',
                  Number: 'number',
                  object: 'Object',
                  String: 'string',
                },
                requireReturn: false,
              }],
              'vars-on-top': 'off',
              'global-require': 'off',
              'no-shadow': ['error', { allow: ['err', 'callback'] }],
              'max-len': 'off',
              'no-plusplus': 'off',
            },
          }),
    
          stylelintrc: () => ({
            extends: 'stylelint-config-standard-scss',
            plugins: [
              'stylelint-scss',
            ],
          }),
    
          eslintignore: () => `node_modules/
    cartridges/**/cartridge/static/
    coverage/
    doc/
    bin/
    codecept.conf.js`,
    
          gitignore: () => `node_modules/
    cartridges/*/cartridge/static/
    .DS_Store
    *.log
    npm-debug.log*
    yarn-debug.log*
    yarn-error.log*
    coverage/
    .nyc_output/
    .env
    dw.json`,
        };
      }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Since no annotations are provided, the description carries the full burden. It effectively discloses key behavioral traits: it creates files directly in the target directory, ensures proper organization, and includes all required components. However, it doesn't mention potential side effects like overwriting existing files or permission requirements.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with three sentences that each earn their place: stating the purpose, providing usage guidance, and explaining the behavioral outcome. It's front-loaded with the core purpose and avoids unnecessary elaboration.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a creation tool with no annotations and no output schema, the description does well by explaining what the tool does and when to use it. However, it could provide more detail about what 'complete cartridge directory structure' includes or potential error conditions, given the complexity of file generation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the schema already documents all three parameters thoroughly. The description doesn't add any meaningful parameter semantics beyond what's in the schema, so it meets the baseline of 3 without providing extra value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('generate', 'create') and resources ('cartridge directory structure', 'files and configurations'). It distinguishes itself from sibling tools by focusing on cartridge creation rather than documentation retrieval or searching, which all sibling tools do.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly states when to use this tool ('Use this when creating new cartridges') and provides context about ensuring proper organization. It also implicitly distinguishes from siblings by focusing on creation rather than information retrieval, though it doesn't name specific alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/taurgis/sfcc-dev-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server