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
| Name | Required | Description | Default |
|---|---|---|---|
| cartridgeName | Yes | Name of the cartridge (e.g., "plugin_example") | |
| targetPath | No | 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 | No | 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. |
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'], }, }, ];
- src/tool-configs/cartridge-tool-config.ts:17-41 (registration)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}`, }, };
- src/core/handlers/cartridge-handler.ts:14-58 (registration)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`, }; }